{"jsonrpc":"2.0","id":"","result":{"genesis":{"genesis_time":"2026-09-08T12:14:16Z","chain_id":"gno-sam-rehearsal","consensus_params":{"Block":{"MaxTxBytes":"1000000","MaxDataBytes":"2000000","MaxBlockBytes":"0","MaxGas":"3000000000","TimeIotaMS":"100"},"Validator":{"PubKeyTypeURLs":["/tm.PubKeyEd25519"]}},"validators":[{"address":"g1zusv4vef52mzuw0ra2j7vqwx7e9fl0jw078qlz","pub_key":{"@type":"/tm.PubKeyEd25519","value":"N3Uh7He+3Srvv6i6vEtrFECursIBwuu2WzpBdJaciIo="},"power":"90","name":"sentry"},{"address":"g15t7f9q6km3ldt885duwl8xu5dncs98528amk4f","pub_key":{"@type":"/tm.PubKeyEd25519","value":"ttILeghsqDTcV/ca746GTBxa/1sPVRG4i/z+hm3jINo="},"power":"5","name":"sam-1"},{"address":"g14ktqynquws35pgx7mpl3h4ug6qxcv6jguzu647","pub_key":{"@type":"/tm.PubKeyEd25519","value":"UE08TpoWx9k/VfEiulUtR9NVU/qAlRZBc4zk0OY+vQ8="},"power":"5","name":"sam-2"}],"app_hash":null,"app_state":{"@type":"/gno.GenesisState","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":["g1zusv4vef52mzuw0ra2j7vqwx7e9fl0jw078qlz"],"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},"balances":["g1zusv4vef52mzuw0ra2j7vqwx7e9fl0jw078qlz=10000000000000ugnot","g15t7f9q6km3ldt885duwl8xu5dncs98528amk4f=10000000000000ugnot","g14ktqynquws35pgx7mpl3h4ug6qxcv6jguzu647=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"},{"name":"ufmt_test.gno","body":"package ufmt\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n)\n\ntype stringer struct{}\n\nfunc (stringer) String() string {\n\treturn \"I'm a stringer\"\n}\n\nfunc TestSprintf(t *testing.T) {\n\ttru := true\n\tcases := []struct {\n\t\tformat         string\n\t\tvalues         []any\n\t\texpectedOutput string\n\t}{\n\t\t{\"hello %s!\", []any{\"planet\"}, \"hello planet!\"},\n\t\t{\"hello %v!\", []any{\"planet\"}, \"hello planet!\"},\n\t\t{\"hi %%%s!\", []any{\"worl%d\"}, \"hi %worl%d!\"},\n\t\t{\"%s %c %d %t\", []any{\"foo\", 'α', 421, true}, \"foo α 421 true\"},\n\t\t{\"string [%s]\", []any{\"foo\"}, \"string [foo]\"},\n\t\t{\"int [%d]\", []any{int(42)}, \"int [42]\"},\n\t\t{\"int [%v]\", []any{int(42)}, \"int [42]\"},\n\t\t{\"int8 [%d]\", []any{int8(8)}, \"int8 [8]\"},\n\t\t{\"int8 [%v]\", []any{int8(8)}, \"int8 [8]\"},\n\t\t{\"int16 [%d]\", []any{int16(16)}, \"int16 [16]\"},\n\t\t{\"int16 [%v]\", []any{int16(16)}, \"int16 [16]\"},\n\t\t{\"int32 [%d]\", []any{int32(32)}, \"int32 [32]\"},\n\t\t{\"int32 [%v]\", []any{int32(32)}, \"int32 [32]\"},\n\t\t{\"int64 [%d]\", []any{int64(64)}, \"int64 [64]\"},\n\t\t{\"int64 [%v]\", []any{int64(64)}, \"int64 [64]\"},\n\t\t{\"uint [%d]\", []any{uint(42)}, \"uint [42]\"},\n\t\t{\"uint [%v]\", []any{uint(42)}, \"uint [42]\"},\n\t\t{\"uint8 [%d]\", []any{uint8(8)}, \"uint8 [8]\"},\n\t\t{\"uint8 [%v]\", []any{uint8(8)}, \"uint8 [8]\"},\n\t\t{\"uint16 [%d]\", []any{uint16(16)}, \"uint16 [16]\"},\n\t\t{\"uint16 [%v]\", []any{uint16(16)}, \"uint16 [16]\"},\n\t\t{\"uint32 [%d]\", []any{uint32(32)}, \"uint32 [32]\"},\n\t\t{\"uint32 [%v]\", []any{uint32(32)}, \"uint32 [32]\"},\n\t\t{\"uint64 [%d]\", []any{uint64(64)}, \"uint64 [64]\"},\n\t\t{\"uint64 [%v]\", []any{uint64(64)}, \"uint64 [64]\"},\n\t\t{\"float64 [%e]\", []any{float64(64.1)}, \"float64 [6.41e+01]\"},\n\t\t{\"float64 [%E]\", []any{float64(64.1)}, \"float64 [6.41E+01]\"},\n\t\t{\"float64 [%f]\", []any{float64(64.1)}, \"float64 [64.100000]\"},\n\t\t{\"float64 [%F]\", []any{float64(64.1)}, \"float64 [64.100000]\"},\n\t\t{\"float64 [%g]\", []any{float64(64.1)}, \"float64 [64.1]\"},\n\t\t{\"float64 [%G]\", []any{float64(64.1)}, \"float64 [64.1]\"},\n\t\t{\"bool [%t]\", []any{true}, \"bool [true]\"},\n\t\t{\"bool [%v]\", []any{true}, \"bool [true]\"},\n\t\t{\"bool [%t]\", []any{false}, \"bool [false]\"},\n\t\t{\"bool [%v]\", []any{false}, \"bool [false]\"},\n\t\t{\"no args\", nil, \"no args\"},\n\t\t{\"finish with %\", nil, \"finish with %\"},\n\t\t{\"stringer [%s]\", []any{stringer{}}, \"stringer [I'm a stringer]\"},\n\t\t{\"â\", nil, \"â\"},\n\t\t{\"Hello, World! 😊\", nil, \"Hello, World! 😊\"},\n\t\t{\"unicode formatting: %s\", []any{\"😊\"}, \"unicode formatting: 😊\"},\n\t\t{\"invalid hex [%x]\", []any{\"invalid\"}, \"invalid hex [(unhandled)]\"},\n\t\t{\"rune as character [%c]\", []any{rune('A')}, \"rune as character [A]\"},\n\t\t{\"int as character [%c]\", []any{int('B')}, \"int as character [B]\"},\n\t\t{\"quoted string [%q]\", []any{\"hello\"}, \"quoted string [\\\"hello\\\"]\"},\n\t\t{\"quoted string with escape [%q]\", []any{\"\\thello\\nworld\\\\\"}, \"quoted string with escape [\\\"\\\\thello\\\\nworld\\\\\\\\\\\"]\"},\n\t\t{\"invalid quoted string [%q]\", []any{123}, \"invalid quoted string [(unhandled)]\"},\n\t\t{\"type of bool [%T]\", []any{true}, \"type of bool [bool]\"},\n\t\t{\"type of int [%T]\", []any{123}, \"type of int [int]\"},\n\t\t{\"type of string [%T]\", []any{\"hello\"}, \"type of string [string]\"},\n\t\t{\"type of []byte [%T]\", []any{[]byte{1, 2, 3}}, \"type of []byte [[]byte]\"},\n\t\t{\"type of []rune [%T]\", []any{[]rune{'a', 'b', 'c'}}, \"type of []rune [[]rune]\"},\n\t\t{\"type of unknown [%T]\", []any{struct{}{}}, \"type of unknown [unknown]\"},\n\t\t// mismatch printing\n\t\t{\"%s\", []any{nil}, \"%!s(\u003cnil\u003e)\"},\n\t\t{\"%s\", []any{421}, \"%!s(int=421)\"},\n\t\t{\"%s\", []any{\"z\"}, \"z\"},\n\t\t{\"%s\", []any{tru}, \"%!s(bool=true)\"},\n\t\t{\"%s\", []any{'z'}, \"%!s(int32=122)\"},\n\n\t\t{\"%c\", []any{nil}, \"%!c(\u003cnil\u003e)\"},\n\t\t{\"%c\", []any{421}, \"ƥ\"},\n\t\t{\"%c\", []any{\"z\"}, \"%!c(string=z)\"},\n\t\t{\"%c\", []any{tru}, \"%!c(bool=true)\"},\n\t\t{\"%c\", []any{'z'}, \"z\"},\n\n\t\t{\"%d\", []any{nil}, \"%!d(\u003cnil\u003e)\"},\n\t\t{\"%d\", []any{421}, \"421\"},\n\t\t{\"%d\", []any{\"z\"}, \"%!d(string=z)\"},\n\t\t{\"%d\", []any{tru}, \"%!d(bool=true)\"},\n\t\t{\"%d\", []any{'z'}, \"122\"},\n\n\t\t{\"%t\", []any{nil}, \"%!t(\u003cnil\u003e)\"},\n\t\t{\"%t\", []any{421}, \"%!t(int=421)\"},\n\t\t{\"%t\", []any{\"z\"}, \"%!t(string=z)\"},\n\t\t{\"%t\", []any{tru}, \"true\"},\n\t\t{\"%t\", []any{'z'}, \"%!t(int32=122)\"},\n\n\t\t{\"%.2f\", []any{3.14159}, \"3.14\"},\n\t\t{\"%.4f\", []any{3.14159}, \"3.1416\"},\n\t\t{\"%.0f\", []any{3.14159}, \"3\"},\n\t\t{\"%.1f\", []any{3.0}, \"3.0\"},\n\t\t{\"%.3F\", []any{3.14159}, \"3.142\"},\n\t\t{\"%.2e\", []any{314.159}, \"3.14e+02\"},\n\t\t{\"%.3E\", []any{314.159}, \"3.142E+02\"},\n\t\t{\"%.3g\", []any{3.14159}, \"3.14\"},\n\t\t{\"%.5G\", []any{3.14159}, \"3.1416\"},\n\t\t{\"%.0f\", []any{3.6}, \"4\"},\n\t\t{\"%.0f\", []any{3.4}, \"3\"},\n\t\t{\"%.1f\", []any{0.0}, \"0.0\"},\n\t\t{\"%.2f\", []any{1e6}, \"1000000.00\"},\n\t\t{\"%.2f\", []any{1e-6}, \"0.00\"},\n\n\t\t{\"%5s\", []any{\"Hello World\"}, \"Hello World\"},\n\t\t{\"%3s\", []any{\"Hi\"}, \" Hi\"},\n\t\t{\"%2s\", []any{\"Hello\"}, \"Hello\"},\n\t\t{\"%1s\", []any{\"A\"}, \"A\"},\n\t\t{\"%0s\", []any{\"Test\"}, \"Test\"},\n\t\t{\"%5s!\", []any{\"Hello World\"}, \"Hello World!\"},\n\t\t{\"_%5s_\", []any{\"abc\"}, \"_  abc_\"},\n\t\t{\"%2s%4s\", []any{\"ab\", \"cde\"}, \"ab cde\"},\n\t\t{\"%5s\", []any{\"\"}, \"     \"},\n\t\t{\"%3s\", []any{nil}, \"%!s(\u003cnil\u003e)\"},\n\t\t{\"%2s\", []any{123}, \"%!s(int=123)\"},\n\t}\n\n\tfor _, tc := range cases {\n\t\tname := fmt.Sprintf(tc.format, tc.values...)\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tgot := Sprintf(tc.format, tc.values...)\n\t\t\tif got != tc.expectedOutput {\n\t\t\t\tt.Errorf(\"got %q, want %q.\", got, tc.expectedOutput)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestErrorf(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tformat   string\n\t\targs     []any\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"simple string\",\n\t\t\tformat:   \"error: %s\",\n\t\t\targs:     []any{\"something went wrong\"},\n\t\t\texpected: \"error: something went wrong\",\n\t\t},\n\t\t{\n\t\t\tname:     \"integer value\",\n\t\t\tformat:   \"value: %d\",\n\t\t\targs:     []any{42},\n\t\t\texpected: \"value: 42\",\n\t\t},\n\t\t{\n\t\t\tname:     \"boolean value\",\n\t\t\tformat:   \"success: %t\",\n\t\t\targs:     []any{true},\n\t\t\texpected: \"success: true\",\n\t\t},\n\t\t{\n\t\t\tname:     \"multiple values\",\n\t\t\tformat:   \"error %d: %s (success=%t)\",\n\t\t\targs:     []any{123, \"failure occurred\", false},\n\t\t\texpected: \"error 123: failure occurred (success=false)\",\n\t\t},\n\t\t{\n\t\t\tname:     \"literal percent\",\n\t\t\tformat:   \"literal %%\",\n\t\t\targs:     []any{},\n\t\t\texpected: \"literal %\",\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 := Errorf(tt.format, tt.args...)\n\t\t\tif err.Error() != tt.expected {\n\t\t\t\tt.Errorf(\"Errorf(%q, %v) = %q, expected %q\", tt.format, tt.args, err.Error(), tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestPrintErrors(t *testing.T) {\n\tgot := Sprintf(\"error: %s\", errors.New(\"can I be printed?\"))\n\texpectedOutput := \"error: can I be printed?\"\n\tif got != expectedOutput {\n\t\tt.Errorf(\"got %q, want %q.\", got, expectedOutput)\n\t}\n}\n\nfunc TestSprint(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\targs     []any\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"Empty args\",\n\t\t\targs:     []any{},\n\t\t\texpected: \"\",\n\t\t},\n\t\t{\n\t\t\tname:     \"String args\",\n\t\t\targs:     []any{\"Hello\", \"World\"},\n\t\t\texpected: \"Hello World\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Integer args\",\n\t\t\targs:     []any{1, 2, 3},\n\t\t\texpected: \"1 2 3\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Mixed args\",\n\t\t\targs:     []any{\"Hello\", 42, true, false, \"World\"},\n\t\t\texpected: \"Hello 42 true false World\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Unhandled type\",\n\t\t\targs:     []any{\"Hello\", 3.14, []int{1, 2, 3}},\n\t\t\texpected: \"Hello 3.140000 (unhandled)\",\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tgot := Sprint(tc.args...)\n\t\t\tif got != tc.expected {\n\t\t\t\tt.Errorf(\"got %q, want %q.\", got, tc.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestFprintf(t *testing.T) {\n\tvar buf bytes.Buffer\n\tn, err := Fprintf(\u0026buf, \"Count: %d, Message: %s\", 42, \"hello\")\n\tif err != nil {\n\t\tt.Fatalf(\"Fprintf failed: %v\", err)\n\t}\n\n\tconst expected = \"Count: 42, Message: hello\"\n\tif buf.String() != expected {\n\t\tt.Errorf(\"Expected %q, got %q\", expected, buf.String())\n\t}\n\tif n != len(expected) {\n\t\tt.Errorf(\"Expected %d bytes written, got %d\", len(expected), n)\n\t}\n}\n\n// TODO: replace os.Stdout with a buffer to capture the output and test it.\nfunc TestPrintf(t *testing.T) {\n\tn, err := Printf(\"The answer is %d\", 42)\n\tif err != nil {\n\t\tt.Fatalf(\"Printf failed: %v\", err)\n\t}\n\n\tconst expected = \"The answer is 42\"\n\tif n != len(expected) {\n\t\tt.Errorf(\"Expected 14 bytes written, got %d\", n)\n\t}\n}\n\nfunc TestAppendf(t *testing.T) {\n\tb := []byte(\"Header: \")\n\tresult := Appendf(b, \"Value %d\", 7)\n\tconst expected = \"Header: Value 7\"\n\tif string(result) != expected {\n\t\tt.Errorf(\"Expected %q, got %q\", expected, string(result))\n\t}\n}\n\nfunc TestFprint(t *testing.T) {\n\tvar buf bytes.Buffer\n\tn, err := Fprint(\u0026buf, \"Hello\", 42, true)\n\tif err != nil {\n\t\tt.Fatalf(\"Fprint failed: %v\", err)\n\t}\n\n\tconst expected = \"Hello 42 true\"\n\tif buf.String() != expected {\n\t\tt.Errorf(\"Expected %q, got %q\", expected, buf.String())\n\t}\n\tif n != len(expected) {\n\t\tt.Errorf(\"Expected %d bytes written, got %d\", len(expected), n)\n\t}\n}\n\n// TODO: replace os.Stdout with a buffer to capture the output and test it.\nfunc TestPrint(t *testing.T) {\n\tn, err := Print(\"Mixed\", 3.14, false)\n\tif err != nil {\n\t\tt.Fatalf(\"Print failed: %v\", err)\n\t}\n\n\tconst expected = \"Mixed 3.140000 false\"\n\tif n != len(expected) {\n\t\tt.Errorf(\"Expected 12 bytes written, got %d\", n)\n\t}\n}\n\nfunc TestAppend(t *testing.T) {\n\tb := []byte{0x01, 0x02}\n\tresult := Append(b, \"Test\", 99)\n\n\tconst expected = \"\\x01\\x02Test 99\"\n\tif string(result) != expected {\n\t\tt.Errorf(\"Expected %q, got %q\", expected, string(result))\n\t}\n}\n\nfunc TestFprintln(t *testing.T) {\n\tvar buf bytes.Buffer\n\tn, err := Fprintln(\u0026buf, \"Line\", 1)\n\tif err != nil {\n\t\tt.Fatalf(\"Fprintln failed: %v\", err)\n\t}\n\n\tconst expected = \"Line 1\\n\"\n\tif buf.String() != expected {\n\t\tt.Errorf(\"Expected %q, got %q\", expected, buf.String())\n\t}\n\tif n != len(expected) {\n\t\tt.Errorf(\"Expected %d bytes written, got %d\", len(expected), n)\n\t}\n}\n\n// TODO: replace os.Stdout with a buffer to capture the output and test it.\nfunc TestPrintln(t *testing.T) {\n\tn, err := Println(\"Output\", \"test\")\n\tif err != nil {\n\t\tt.Fatalf(\"Println failed: %v\", err)\n\t}\n\n\tconst expected = \"Output test\\n\"\n\tif n != len(expected) {\n\t\tt.Errorf(\"Expected 12 bytes written, got %d\", n)\n\t}\n}\n\nfunc TestSprintln(t *testing.T) {\n\tresult := Sprintln(\"Item\", 42)\n\n\tconst expected = \"Item 42\\n\"\n\tif result != expected {\n\t\tt.Errorf(\"Expected %q, got %q\", expected, result)\n\t}\n}\n\nfunc TestAppendln(t *testing.T) {\n\tb := []byte(\"Start:\")\n\tresult := Appendln(b, \"End\")\n\n\tconst expected = \"Start:End\\n\"\n\tif string(result) != expected {\n\t\tt.Errorf(\"Expected %q, got %q\", expected, string(result))\n\t}\n}\n\nfunc assertNoError(t *testing.T, err error) {\n\tt.Helper()\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"aFZFmaUQgDcEjLLnTyPmATQp1500XoL1fP5tCM4BXdYd0JDRbw96s+c07TIqFoKwRSksZN0oGJXxRX6WMRUcRg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"diff","path":"gno.land/p/onbloc/diff","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":"diff_test.gno","body":"package diff\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestMyersDiff(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\told      string\n\t\tnew      string\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"No difference\",\n\t\t\told:      \"abc\",\n\t\t\tnew:      \"abc\",\n\t\t\texpected: \"abc\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Simple insertion\",\n\t\t\told:      \"ac\",\n\t\t\tnew:      \"abc\",\n\t\t\texpected: \"a[+b]c\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Simple deletion\",\n\t\t\told:      \"abc\",\n\t\t\tnew:      \"ac\",\n\t\t\texpected: \"a[-b]c\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Simple substitution\",\n\t\t\told:      \"abc\",\n\t\t\tnew:      \"abd\",\n\t\t\texpected: \"ab[-c][+d]\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Multiple changes\",\n\t\t\told:      \"The quick brown fox jumps over the lazy dog\",\n\t\t\tnew:      \"The quick brown cat jumps over the lazy dog\",\n\t\t\texpected: \"The quick brown [-fox][+cat] jumps over the lazy dog\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Prefix and suffix\",\n\t\t\told:      \"Hello, world!\",\n\t\t\tnew:      \"Hello, beautiful world!\",\n\t\t\texpected: \"Hello, [+beautiful ]world!\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Complete change\",\n\t\t\told:      \"abcdef\",\n\t\t\tnew:      \"ghijkl\",\n\t\t\texpected: \"[-abcdef][+ghijkl]\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Empty strings\",\n\t\t\told:      \"\",\n\t\t\tnew:      \"\",\n\t\t\texpected: \"\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Old empty\",\n\t\t\told:      \"\",\n\t\t\tnew:      \"abc\",\n\t\t\texpected: \"[+abc]\",\n\t\t},\n\t\t{\n\t\t\tname:     \"New empty\",\n\t\t\told:      \"abc\",\n\t\t\tnew:      \"\",\n\t\t\texpected: \"[-abc]\",\n\t\t},\n\t\t{\n\t\t\tname:     \"non-ascii (Korean characters)\",\n\t\t\told:      \"ASCII 문자가 아닌 것도 되나?\",\n\t\t\tnew:      \"ASCII 문자가 아닌 것도 됨.\",\n\t\t\texpected: \"ASCII 문자가 아닌 것도 [-되나?][+됨.]\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Emoji diff\",\n\t\t\told:      \"Hello 👋 World 🌍\",\n\t\t\tnew:      \"Hello 👋 Beautiful 🌸 World 🌍\",\n\t\t\texpected: \"Hello 👋 [+Beautiful 🌸 ]World 🌍\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Mixed multibyte and ASCII\",\n\t\t\told:      \"こんにちは World\",\n\t\t\tnew:      \"こんばんは World\",\n\t\t\texpected: \"こん[-にち][+ばん]は World\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Chinese characters\",\n\t\t\told:      \"我喜欢编程\",\n\t\t\tnew:      \"我喜欢看书和编程\",\n\t\t\texpected: \"我喜欢[+看书和]编程\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Combining characters\",\n\t\t\told:      \"e\\u0301\", // é (e + ´)\n\t\t\tnew:      \"e\\u0300\", // è (e + `)\n\t\t\texpected: \"e[-\\u0301][+\\u0300]\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Right-to-Left languages\",\n\t\t\told:      \"שלום\",\n\t\t\tnew:      \"שלום עולם\",\n\t\t\texpected: \"שלום[+ עולם]\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Normalization NFC and NFD\",\n\t\t\told:      \"e\\u0301\", // NFD (decomposed)\n\t\t\tnew:      \"\\u00e9\",  // NFC (precomposed)\n\t\t\texpected: \"[-e\\u0301][+\\u00e9]\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Case sensitivity\",\n\t\t\told:      \"abc\",\n\t\t\tnew:      \"Abc\",\n\t\t\texpected: \"[-a][+A]bc\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Surrogate pairs\",\n\t\t\told:      \"Hello 🌍\",\n\t\t\tnew:      \"Hello 🌎\",\n\t\t\texpected: \"Hello [-🌍][+🌎]\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Control characters\",\n\t\t\told:      \"Line1\\nLine2\",\n\t\t\tnew:      \"Line1\\r\\nLine2\",\n\t\t\texpected: \"Line1[+\\r]\\nLine2\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Mixed scripts\",\n\t\t\told:      \"Hello नमस्ते こんにちは\",\n\t\t\tnew:      \"Hello สวัสดี こんにちは\",\n\t\t\texpected: \"Hello [-नमस्ते][+สวัสดี] こんにちは\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Unicode normalization\",\n\t\t\told:      \"é\",       // U+00E9 (precomposed)\n\t\t\tnew:      \"e\\u0301\", // U+0065 U+0301 (decomposed)\n\t\t\texpected: \"[-é][+e\\u0301]\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Directional marks\",\n\t\t\told:      \"Hello\\u200Eworld\", // LTR mark\n\t\t\tnew:      \"Hello\\u200Fworld\", // RTL mark\n\t\t\texpected: \"Hello[-\\u200E][+\\u200F]world\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Zero-width characters\",\n\t\t\told:      \"ab\\u200Bc\", // Zero-width space\n\t\t\tnew:      \"abc\",\n\t\t\texpected: \"ab[-\\u200B]c\",\n\t\t},\n\t\t{\n\t\t\tname:     \"Worst-case scenario (completely different strings)\",\n\t\t\told:      strings.Repeat(\"a\", 1000),\n\t\t\tnew:      strings.Repeat(\"b\", 1000),\n\t\t\texpected: \"[-\" + strings.Repeat(\"a\", 1000) + \"][+\" + strings.Repeat(\"b\", 1000) + \"]\",\n\t\t},\n\t\t//{ // disabled for testing performance\n\t\t// XXX: consider adding a flag to run such tests, not like `-short`, or switching to a `-bench`, maybe.\n\t\t//\tname:     \"Very long strings\",\n\t\t//\told:      strings.Repeat(\"a\", 10000) + \"b\" + strings.Repeat(\"a\", 10000),\n\t\t//\tnew:      strings.Repeat(\"a\", 10000) + \"c\" + strings.Repeat(\"a\", 10000),\n\t\t//\texpected: strings.Repeat(\"a\", 10000) + \"[-b][+c]\" + strings.Repeat(\"a\", 10000),\n\t\t//},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tdiff := MyersDiff(tc.old, tc.new)\n\t\t\tresult := Format(diff)\n\t\t\tif result != tc.expected {\n\t\t\t\tt.Errorf(\"Expected: %s, got: %s\", tc.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/onbloc/diff\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"R4ghyGWe6CEzqnC2ecXaHSrCYWcr6ESatdbSbrEX7WcO21lGXC8LViegujNfVd0M6zRO/ND9qOPFZiu/W8ak7A=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"nestedpkg","path":"gno.land/p/demo/nestedpkg","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/nestedpkg\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"zCuNR6AfY9ffbnLTmATy9/Zn1w9FX5FXt8NY4tRXws8PNrwptFI0dDshtzIlIw+zXs6J0ck3/Vf0nBvh4nkYVg=="}],"memo":""}},{"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":"crypto_test.gno","body":"package testutils\n\nimport (\n\t\"testing\"\n)\n\nfunc TestTestAddress(t *testing.T) {\n\ttestAddr := TestAddress(\"author1\")\n\tif string(testAddr) != \"g1v96hg6r0wgc47h6lta047h6lta047h6lm33tq6\" {\n\t\tpanic(\"not equal\")\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 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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"S2GS9l2jNZn1phK/xCDULMARx+Gkmyg5BAfWpQ1sA0pAJQ5fXdepcOVSlX48O4lgdXI15Rov2GKCpLRs/sLYgQ=="}],"memo":""}},{"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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"NO7N6qazzJ5R9XhE/IvfFrrrjd6Cn7Rn3ylfurcictxtDny+tXlHtMUw0edt1m9x5Jjj/6XcDP56XiDDDkHi3A=="}],"memo":""}},{"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":"nestedpkg_test.gno","body":"package vm\n\nimport (\n\t\"testing\"\n)\n\nfunc TestNestedPkg(cur realm, t *testing.T) {\n\t// direct child\n\tcurPath := \"gno.land/r/tests/vm/foo\"\n\ttesting.SetRealm(testing.NewCodeRealm(curPath))\n\tif !IsCallerSubPath(cross(cur)) {\n\t\tt.Errorf(curPath + \" should be a sub path\")\n\t}\n\tif IsCallerParentPath(cross(cur)) {\n\t\tt.Errorf(curPath + \" should not be a parent path\")\n\t}\n\tif !HasCallerSameNamespace(cross(cur)) {\n\t\tt.Errorf(curPath + \" should be from the same namespace\")\n\t}\n\n\t// grand-grand-child\n\tcurPath = \"gno.land/r/tests/vm/foo/bar/baz\"\n\ttesting.SetRealm(testing.NewCodeRealm(curPath))\n\tif !IsCallerSubPath(cross(cur)) {\n\t\tt.Errorf(curPath + \" should be a sub path\")\n\t}\n\tif IsCallerParentPath(cross(cur)) {\n\t\tt.Errorf(curPath + \" should not be a parent path\")\n\t}\n\tif !HasCallerSameNamespace(cross(cur)) {\n\t\tt.Errorf(curPath + \" should be from the same namespace\")\n\t}\n\n\t// NOTE: This is now back in the gno.land/r/tests/vm structure,\n\t// so the direct parent test case is valid again.\n\n\t// direct parent (was previously fake parent)\n\tcurPath = \"gno.land/r/test\" // without the 's' at the end\n\ttesting.SetRealm(testing.NewCodeRealm(curPath))\n\tif IsCallerSubPath(cross(cur)) {\n\t\tt.Errorf(curPath + \" should not be a sub path\")\n\t}\n\tif IsCallerParentPath(cross(cur)) {\n\t\tt.Errorf(curPath + \" should not be a parent path\")\n\t}\n\tif HasCallerSameNamespace(cross(cur)) {\n\t\tt.Errorf(curPath + \" should not be from the same namespace\")\n\t}\n\n\t// fake parent (prefix)\n\tcurPath = \"gno.land/r/dem\"\n\ttesting.SetRealm(testing.NewCodeRealm(curPath))\n\tif IsCallerSubPath(cross(cur)) {\n\t\tt.Errorf(curPath + \" should not be a sub path\")\n\t}\n\tif IsCallerParentPath(cross(cur)) {\n\t\tt.Errorf(curPath + \" should not be a parent path\")\n\t}\n\tif HasCallerSameNamespace(cross(cur)) {\n\t\tt.Errorf(curPath + \" should not be from the same namespace\")\n\t}\n\n\t// different namespace\n\tcurPath = \"gno.land/r/foo\"\n\ttesting.SetRealm(testing.NewCodeRealm(curPath))\n\tif IsCallerSubPath(cross(cur)) {\n\t\tt.Errorf(curPath + \" should not be a sub path\")\n\t}\n\tif IsCallerParentPath(cross(cur)) {\n\t\tt.Errorf(curPath + \" should not be a parent path\")\n\t}\n\tif HasCallerSameNamespace(cross(cur)) {\n\t\tt.Errorf(curPath + \" should not be from the same namespace\")\n\t}\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/demo/nestedpkg\"\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"},{"name":"tests_test.gno","body":"package vm_test\n\nimport (\n\t\"chain\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\ttests \"gno.land/r/tests/vm\"\n)\n\nfunc TestAssertOriginCall(cur realm, t *testing.T) {\n\t// CallAssertOriginCall(): no panic\n\tcaller := testutils.TestAddress(\"caller\")\n\ttesting.SetRealm(testing.NewUserRealm(caller))\n\ttests.CallAssertOriginCall(cross(cur))\n\tif !tests.CallIsOriginCall(cross(cur)) {\n\t\tt.Errorf(\"expected IsOriginCall=true but got false\")\n\t}\n\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/tests/vm\"))\n\t// CallAssertOriginCall() from a block: abort\n\tr := revive(func() {\n\t\t// if called inside a function literal, this is no longer an origin call\n\t\t// because there's one additional frame (the function literal block).\n\t\tif tests.CallIsOriginCall(cross(cur)) {\n\t\t\tt.Errorf(\"expected IsOriginCall=false but got true\")\n\t\t}\n\t\ttests.CallAssertOriginCall(cross(cur)) // \u003c---\n\t})\n\tif fmt.Sprintf(\"%v\", r) != \"invalid non-origin call\" {\n\t\tt.Error(\"expected abort but did not\")\n\t}\n\t// CallSubtestsAssertOriginCall(): abort\n\tr = revive(func() {\n\t\t// if called inside a function literal, this is no longer an origin call\n\t\t// because there's one additional frame (the function literal block).\n\t\tif tests.CallSubtestsIsOriginCall(cross(cur)) {\n\t\t\tt.Errorf(\"expected IsOriginCall=false but got true\")\n\t\t}\n\t\ttests.CallSubtestsAssertOriginCall(cross(cur))\n\t})\n\tif fmt.Sprintf(\"%v\", r) != \"invalid non-origin call\" {\n\t\tt.Error(\"expected abort but did not\")\n\t}\n}\n\nfunc TestPreviousRealm(cur realm, t *testing.T) {\n\tvar (\n\t\tfirstRealm = chain.PackageAddress(\"gno.land/r/tests/vm_test\")\n\t\trTestsAddr = chain.PackageAddress(\"gno.land/r/tests/vm\")\n\t)\n\t// When only one realm in the frames, PreviousRealm returns the same realm\n\tif addr := tests.GetPreviousRealm(cross(cur)).Address(); addr != firstRealm {\n\t\tprintln(tests.GetPreviousRealm(cross(cur)))\n\t\tt.Errorf(\"want GetPreviousRealm().Address==%s, got %s\", firstRealm, addr)\n\t}\n\t// When 2 or more realms in the frames, PreviousRealm returns the second to last\n\tif addr := tests.GetRSubtestsPreviousRealm(cross(cur)).Address(); addr != rTestsAddr {\n\t\tt.Errorf(\"want GetRSubtestsPreviousRealm().Address==%s, got %s\", rTestsAddr, addr)\n\t}\n}\n"},{"name":"z0_filetest.gno","body":"// PKGPATH: gno.land/r/tests/vm/filetests/z0_filetest\n\npackage z0_filetest\n\nimport (\n\ttests \"gno.land/r/tests/vm\"\n)\n\nfunc main(cur realm) {\n\tprintln(\"tests.CallIsOriginCall:\", tests.CallIsOriginCall(cross(cur)))\n\ttests.CallAssertOriginCall(cross(cur))\n\tprintln(\"tests.CallAssertOriginCall doesn't panic when called directly\")\n\n\t{\n\t\t// if called inside a block, this is no longer an origin call because\n\t\t// there's one additional frame (the block).\n\t\tprintln(\"tests.CallIsOriginCall:\", tests.CallIsOriginCall(cross(cur)))\n\t\tdefer func() {\n\t\t\tr := recover()\n\t\t\tprintln(\"tests.AssertOriginCall panics if when called inside a function literal:\", r)\n\t\t}()\n\t\ttests.CallAssertOriginCall(cross(cur))\n\t}\n}\n\n// Output:\n// tests.CallIsOriginCall: false\n// tests.CallAssertOriginCall doesn't panic when called directly\n// tests.CallIsOriginCall: false\n// tests.AssertOriginCall panics if when called inside a function literal: undefined\n"},{"name":"z1_filetest.gno","body":"// PKGPATH: gno.land/r/tests/vm/filetests/z1_filetest\n\npackage z1_filetest\n\nimport (\n\ttests \"gno.land/r/tests/vm\"\n)\n\nfunc main(cur realm) {\n\tprintln(tests.Counter(cross(cur)))\n\ttests.IncCounter(cross(cur))\n\tprintln(tests.Counter(cross(cur)))\n}\n\n// Output:\n// 0\n// 1\n"},{"name":"z2_filetest.gno","body":"// PKGPATH: gno.land/r/tests/vm/filetests/z2_filetest\n\npackage z2_filetest\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\ttests \"gno.land/r/tests/vm\"\n)\n\n// When a single realm in the frames, PreviousRealm returns the user\n// When 2 or more realms in the frames, PreviousRealm returns the second to last\nfunc main(cur realm) {\n\tvar (\n\t\teoa = testutils.TestAddress(\"someone\")\n\t\t_   = chain.PackageAddress(\"gno.land/r/tests/vm\")\n\t)\n\ttesting.SetOriginCaller(eoa)\n\tprintln(\"tests.GetPreviousRealm().Address(): \", tests.GetPreviousRealm(cross(cur)).Address())\n\tprintln(\"tests.GetRSubtestsPreviousRealm().Address(): \", tests.GetRSubtestsPreviousRealm(cross(cur)).Address())\n}\n\n// Output:\n// tests.GetPreviousRealm().Address():  g1wdhk6et0dej47h6lta047h6lta047h6lrnerlk\n// tests.GetRSubtestsPreviousRealm().Address():  g1dhh6vhw9f5lmmpfz52rkf5dsk8lqzmad3fmpw7\n"},{"name":"z3_filetest.gno","body":"// PKGPATH: gno.land/r/tests_z3\npackage tests_z3\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/r/tests/vm\"\n)\n\nfunc main(cur realm) {\n\tvar (\n\t\teoa        = testutils.TestAddress(\"someone\")\n\t\trTestsAddr = chain.PackageAddress(\"gno.land/r/tests/vm\")\n\t)\n\ttesting.SetOriginCaller(eoa)\n\t// Contrarily to z2_filetest.gno we EXPECT GetPreviousRealms != eoa (#1704)\n\tif addr := vm.GetPreviousRealm(cross(cur)).Address(); addr != eoa {\n\t\tprintln(\"want vm.GetPreviousRealm().Address ==\", eoa, \"got\", addr)\n\t}\n\t// When 2 or more realms in the frames, it is also different\n\tif addr := vm.GetRSubtestsPreviousRealm(cross(cur)).Address(); addr != rTestsAddr {\n\t\tprintln(\"want GetRSubtestsPreviousRealm().Address ==\", rTestsAddr, \"got\", addr)\n\t}\n\tprintln(\"Done.\")\n}\n\n// Output:\n// Done.\n"},{"name":"z4_filetest.gno","body":"// PKGPATH: gno.land/r/tests/vm/z4_filetest\n\npackage z4_filetest\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\ttests \"gno.land/r/tests/vm\"\n)\n\nfunc main(cur realm) {\n\ttesting.SetOriginSend(chain.Coins{{Denom: \"foo\", Amount: 42}, {Denom: \"ugnot\", Amount: 100}})\n\tprintln(\"tests.BankerOriginSend: \" + tests.BankerOriginSend(cross(cur)))\n\n\t// unsafe.OriginSend() always returns the origin send regardless of call\n\t// depth.\n\tprintln(\"tests.RTestsOriginSend: \" + tests.RTestsOriginSend(cross(cur)))\n}\n\n// Output:\n// tests.BankerOriginSend: 42foo,100ugnot\n// tests.RTestsOriginSend: 42foo,100ugnot\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"PIfIvAtNbSQhPLZkZDsk8rqPwGbXuZ1Gu4YRkBr7cWtizkaQJa/GK9QXLyJKA+a6B03Q1fanxtZ+Q2uJGCG3lw=="}],"memo":""}},{"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":"mock_test.gno","body":"package uassert_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\ntype mockTestingT struct {\n\tfmt  string\n\targs []any\n}\n\n// --- interface mock\n\nvar _ uassert.TestingT = (*mockTestingT)(nil)\n\nfunc (mockT *mockTestingT) Helper()                      { /* noop */ }\nfunc (mockT *mockTestingT) Skip(args ...any)             { /* not implmented */ }\nfunc (mockT *mockTestingT) Fail()                        { /* not implmented */ }\nfunc (mockT *mockTestingT) FailNow()                     { /* not implmented */ }\nfunc (mockT *mockTestingT) Logf(fmt string, args ...any) { /* noop */ }\n\nfunc (mockT *mockTestingT) Fatalf(fmt string, args ...any) {\n\tmockT.fmt = \"fatal: \" + fmt\n\tmockT.args = args\n}\n\nfunc (mockT *mockTestingT) Errorf(fmt string, args ...any) {\n\tmockT.fmt = \"error: \" + fmt\n\tmockT.args = args\n}\n\n// --- helpers\n\nfunc (mockT *mockTestingT) actualString() string {\n\tres := fmt.Sprintf(mockT.fmt, mockT.args...)\n\tmockT.reset()\n\treturn res\n}\n\nfunc (mockT *mockTestingT) reset() {\n\tmockT.fmt = \"\"\n\tmockT.args = nil\n}\n\nfunc (mockT *mockTestingT) equals(t *testing.T, expected string) {\n\tactual := mockT.actualString()\n\n\tif expected != actual {\n\t\tt.Errorf(\"mockT differs:\\n- expected: %s\\n- actual:   %s\\n\", expected, actual)\n\t}\n}\n\nfunc (mockT *mockTestingT) empty(t *testing.T) {\n\tif mockT.fmt != \"\" || mockT.args != nil {\n\t\tactual := mockT.actualString()\n\t\tt.Errorf(\"mockT should be empty, got %s\", actual)\n\t}\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\"\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"},{"name":"uassert_test.gno","body":"package uassert_test\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\ttests \"gno.land/r/tests/vm\"\n)\n\n// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\nvar _ uassert.TestingT = (*testing.T)(nil)\n\nfunc TestMock(t *testing.T) {\n\tmockT := new(mockTestingT)\n\tmockT.empty(t)\n\tuassert.NoError(mockT, errors.New(\"foo\"))\n\tmockT.equals(t, \"error: unexpected error: foo\")\n\tuassert.NoError(mockT, errors.New(\"foo\"), \"custom message\")\n\tmockT.equals(t, \"error: unexpected error: foo - custom message\")\n\tuassert.NoError(mockT, errors.New(\"foo\"), \"custom\", \"message\")\n\tmockT.equals(t, \"error: unexpected error: foo - custom message\")\n}\n\nfunc TestNoError(t *testing.T) {\n\tmockT := new(mockTestingT)\n\tuassert.True(t, uassert.NoError(mockT, nil))\n\tmockT.empty(t)\n\tuassert.False(t, uassert.NoError(mockT, errors.New(\"foo bar\")))\n\tmockT.equals(t, \"error: unexpected error: foo bar\")\n}\n\nfunc TestError(t *testing.T) {\n\tmockT := new(mockTestingT)\n\tuassert.True(t, uassert.Error(mockT, errors.New(\"foo bar\")))\n\tmockT.empty(t)\n\tuassert.False(t, uassert.Error(mockT, nil))\n\tmockT.equals(t, \"error: an error is expected but got nil\")\n}\n\nfunc TestErrorContains(t *testing.T) {\n\tmockT := new(mockTestingT)\n\n\t// nil error\n\tvar err error\n\tuassert.False(t, uassert.ErrorContains(mockT, err, \"\"), \"ErrorContains should return false for nil arg\")\n}\n\nfunc TestTrue(t *testing.T) {\n\tmockT := new(mockTestingT)\n\tif !uassert.True(mockT, true) {\n\t\tt.Error(\"True should return true\")\n\t}\n\tmockT.empty(t)\n\tif uassert.True(mockT, false) {\n\t\tt.Error(\"True should return false\")\n\t}\n\tmockT.equals(t, \"error: should be true\")\n}\n\nfunc TestFalse(t *testing.T) {\n\tmockT := new(mockTestingT)\n\tif !uassert.False(mockT, false) {\n\t\tt.Error(\"False should return true\")\n\t}\n\tmockT.empty(t)\n\tif uassert.False(mockT, true) {\n\t\tt.Error(\"False should return false\")\n\t}\n\tmockT.equals(t, \"error: should be false\")\n}\n\nfunc TestPanicsWithMessage(cur realm, t *testing.T) {\n\tmockT := new(mockTestingT)\n\tif !uassert.PanicsWithMessage(mockT, cur, \"panic\", func() {\n\t\tpanic(errors.New(\"panic\"))\n\t}) {\n\t\tt.Error(\"PanicsWithMessage should return true\")\n\t}\n\tmockT.empty(t)\n\n\tif uassert.PanicsWithMessage(mockT, cur, \"Panic!\", func() {\n\t\t// noop\n\t}) {\n\t\tt.Error(\"PanicsWithMessage should return false\")\n\t}\n\tmockT.equals(t, \"error: func should panic\\n\\tPanic value:\\tnil\")\n\n\tif uassert.PanicsWithMessage(mockT, cur, \"at the disco\", func() {\n\t\tpanic(errors.New(\"panic\"))\n\t}) {\n\t\tt.Error(\"PanicsWithMessage should return false\")\n\t}\n\tmockT.equals(t, \"error: func should panic with message:\\t\\\"at the disco\\\"\\n\\tActual panic value:\\t\\\"panic\\\"\")\n\n\tif uassert.PanicsWithMessage(mockT, cur, \"Panic!\", func() {\n\t\tpanic(\"panic\")\n\t}) {\n\t\tt.Error(\"PanicsWithMessage should return false\")\n\t}\n\tmockT.equals(t, \"error: func should panic with message:\\t\\\"Panic!\\\"\\n\\tActual panic value:\\t\\\"panic\\\"\")\n}\n\nfunc TestPanicsContains(cur realm, t *testing.T) {\n\tmockT := new(mockTestingT)\n\tif !uassert.PanicsContains(mockT, cur, \"panic\", func() {\n\t\tpanic(errors.New(\"panic: something happened\"))\n\t}) {\n\t\tt.Error(\"PanicsContains should return true for substring match\")\n\t}\n\tmockT.empty(t)\n\n\tif uassert.PanicsContains(mockT, cur, \"notfound\", func() {\n\t\tpanic(errors.New(\"panic: something happened\"))\n\t}) {\n\t\tt.Error(\"PanicsContains should return false for missing substring\")\n\t}\n\tmockT.equals(t, \"error: func should panic with message containing:\\t\\\"notfound\\\"\\n\\tActual panic value:\\t\\\"panic: something happened\\\"\")\n\n\tif uassert.PanicsContains(mockT, cur, \"panic\", func() {\n\t\t// noop\n\t}) {\n\t\tt.Error(\"PanicsContains should return false when no panic occurs\")\n\t}\n\tmockT.equals(t, \"error: func should panic\\n\\tPanic value:\\tnil\")\n}\n\nfunc TestAbortsWithMessage(cur realm, t *testing.T) {\n\tmockT := new(mockTestingT)\n\tif !uassert.AbortsWithMessage(mockT, cur, \"abort message\", func() {\n\t\ttests.ExecSwitch(cross(cur), func() {\n\t\t\tpanic(\"abort message\")\n\t\t})\n\t\tpanic(\"dontcare\")\n\t}) {\n\t\tt.Error(\"AbortsWithMessage should return true\")\n\t}\n\tmockT.empty(t)\n\n\tif uassert.AbortsWithMessage(mockT, cur, \"Abort!\", func() {\n\t\t// noop\n\t}) {\n\t\tt.Error(\"AbortsWithMessage should return false\")\n\t}\n\tmockT.equals(t, \"error: func should abort\")\n\n\tif uassert.AbortsWithMessage(mockT, cur, \"at the disco\", func() {\n\t\ttests.ExecSwitch(cross(cur), func() {\n\t\t\tpanic(\"abort message\")\n\t\t})\n\t\tpanic(\"dontcare\")\n\t}) {\n\t\tt.Error(\"AbortsWithMessage should return false (wrong message)\")\n\t}\n\tmockT.equals(t, \"error: func should abort with message:\\t\\\"at the disco\\\"\\n\\tActual abort value:\\t\\\"abort message\\\"\")\n\n\t// Test that non-crossing panics don't count as abort.\n\tuassert.PanicsWithMessage(mockT, cur, \"non-abort panic\", func() {\n\t\tuassert.AbortsWithMessage(mockT, cur, \"dontcare2\", func() {\n\t\t\tpanic(\"non-abort panic\")\n\t\t})\n\t\tt.Error(\"AbortsWithMessage should not have caught non-abort panic\")\n\t}, \"non-abort panic\")\n\tmockT.empty(t)\n\n\t// Test case where abort value is not a string\n\tif uassert.AbortsWithMessage(mockT, cur, \"doesn't matter\", func() {\n\t\ttests.ExecSwitch(cross(cur), func() {\n\t\t\tpanic(123) // abort with an integer\n\t\t})\n\t\tpanic(\"dontcare\")\n\t}) {\n\t\tt.Error(\"AbortsWithMessage should return false when abort value is not a string\")\n\t}\n\tmockT.equals(t, \"error: func should abort with message:\\t\\\"doesn't matter\\\"\\n\\tActual abort value:\\t\\\"123\\\"\")\n\n\t// XXX: test with Error\n}\n\nfunc TestAbortsContains(cur realm, t *testing.T) {\n\tmockT := new(mockTestingT)\n\tif !uassert.AbortsContains(mockT, cur, \"abort\", func() {\n\t\ttests.ExecSwitch(cross(cur), func() {\n\t\t\tpanic(\"abort message: something happened\")\n\t\t})\n\t\tpanic(\"dontcare\")\n\t}) {\n\t\tt.Error(\"AbortsContains should return true for substring match\")\n\t}\n\tmockT.empty(t)\n\n\tif uassert.AbortsContains(mockT, cur, \"notfound\", func() {\n\t\ttests.ExecSwitch(cross(cur), func() {\n\t\t\tpanic(\"abort message: something happened\")\n\t\t})\n\t\tpanic(\"dontcare\")\n\t}) {\n\t\tt.Error(\"AbortsContains should return false for missing substring\")\n\t}\n\tmockT.equals(t, \"error: func should abort with message containing:\\t\\\"notfound\\\"\\n\\tActual abort value:\\t\\\"abort message: something happened\\\"\")\n\n\tif uassert.AbortsContains(mockT, cur, \"abort\", func() {\n\t\t// noop\n\t}) {\n\t\tt.Error(\"AbortsContains should return false when no abort occurs\")\n\t}\n\tmockT.equals(t, \"error: func should abort\")\n}\n\nfunc TestNotAborts(cur realm, t *testing.T) {\n\tmockT := new(mockTestingT)\n\n\tif !uassert.NotPanics(mockT, cur, func() {\n\t\t// noop\n\t}) {\n\t\tt.Error(\"NotAborts should return true\")\n\t}\n\tmockT.empty(t)\n\n\tif uassert.NotPanics(mockT, cur, func() {\n\t\ttests.ExecSwitch(cross(cur), func() {\n\t\t\tpanic(\"Abort!\")\n\t\t})\n\t\tpanic(\"dontcare\")\n\t}) {\n\t\tt.Error(\"NotAborts should return false\")\n\t}\n\tmockT.equals(t, \"error: func should not abort\\n\\tAbort value:\\tAbort!\")\n}\n\nfunc TestNotPanics(cur realm, t *testing.T) {\n\tmockT := new(mockTestingT)\n\n\tif !uassert.NotPanics(mockT, cur, func() {\n\t\t// noop\n\t}) {\n\t\tt.Error(\"NotPanics should return true\")\n\t}\n\tmockT.empty(t)\n\n\tif uassert.NotPanics(mockT, cur, func() {\n\t\tpanic(\"Panic!\")\n\t}) {\n\t\tt.Error(\"NotPanics should return false\")\n\t}\n\tmockT.equals(t, \"error: func should not panic\\n\\tPanic value:\\tPanic!\")\n}\n\nfunc TestEqual(t *testing.T) {\n\tmockT := new(mockTestingT)\n\n\tcases := []struct {\n\t\texpected any\n\t\tactual   any\n\t\tresult   bool\n\t\tremark   string\n\t}{\n\t\t// expected to be equal\n\t\t{\"Hello World\", \"Hello World\", true, \"\"},\n\t\t{123, 123, true, \"\"},\n\t\t{123.5, 123.5, true, \"\"},\n\t\t{nil, nil, true, \"\"},\n\t\t{int32(123), int32(123), true, \"\"},\n\t\t{uint64(123), uint64(123), true, \"\"},\n\t\t{address(\"g12345\"), address(\"g12345\"), true, \"\"},\n\t\t// XXX: continue\n\n\t\t// not expected to be equal\n\t\t{\"Hello World\", 42, false, \"\"},\n\t\t{41, 42, false, \"\"},\n\t\t{10, uint(10), false, \"\"},\n\t\t// XXX: continue\n\n\t\t// expected to raise errors\n\t\t// XXX: todo\n\t}\n\n\tfor _, c := range cases {\n\t\tname := fmt.Sprintf(\"Equal(%v, %v)\", c.expected, c.actual)\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tres := uassert.Equal(mockT, c.expected, c.actual)\n\n\t\t\tif res != c.result {\n\t\t\t\tt.Errorf(\"%s should return %v: %s - %s\", name, c.result, c.remark, mockT.actualString())\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNotEqual(t *testing.T) {\n\tmockT := new(mockTestingT)\n\n\tcases := []struct {\n\t\texpected any\n\t\tactual   any\n\t\tresult   bool\n\t\tremark   string\n\t}{\n\t\t// expected to be not equal\n\t\t{\"Hello World\", \"Hello\", true, \"\"},\n\t\t{123, 124, true, \"\"},\n\t\t{123.5, 123.6, true, \"\"},\n\t\t{nil, 123, true, \"\"},\n\t\t{int32(123), int32(124), true, \"\"},\n\t\t{uint64(123), uint64(124), true, \"\"},\n\t\t{address(\"g12345\"), address(\"g67890\"), true, \"\"},\n\t\t// XXX: continue\n\n\t\t// not expected to be not equal\n\t\t{\"Hello World\", \"Hello World\", false, \"\"},\n\t\t{123, 123, false, \"\"},\n\t\t{123.5, 123.5, false, \"\"},\n\t\t{nil, nil, false, \"\"},\n\t\t{int32(123), int32(123), false, \"\"},\n\t\t{uint64(123), uint64(123), false, \"\"},\n\t\t{address(\"g12345\"), address(\"g12345\"), false, \"\"},\n\t\t// XXX: continue\n\n\t\t// expected to raise errors\n\t\t// XXX: todo\n\t}\n\n\tfor _, c := range cases {\n\t\tname := fmt.Sprintf(\"NotEqual(%v, %v)\", c.expected, c.actual)\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tres := uassert.NotEqual(mockT, c.expected, c.actual)\n\n\t\t\tif res != c.result {\n\t\t\t\tt.Errorf(\"%s should return %v: %s - %s\", name, c.result, c.remark, mockT.actualString())\n\t\t\t}\n\t\t})\n\t}\n}\n\ntype myStruct struct {\n\tS string\n\tI int\n}\n\nfunc TestEmpty(t *testing.T) {\n\tmockT := new(mockTestingT)\n\n\tcases := []struct {\n\t\tobj           any\n\t\texpectedEmpty bool\n\t}{\n\t\t// expected to be empty\n\t\t{\"\", true},\n\t\t{0, true},\n\t\t{int(0), true},\n\t\t{int32(0), true},\n\t\t{int64(0), true},\n\t\t{uint(0), true},\n\t\t// XXX: continue\n\n\t\t// not expected to be empty\n\t\t{\"Hello World\", false},\n\t\t{1, false},\n\t\t{int32(1), false},\n\t\t{uint64(1), false},\n\t\t{address(\"g12345\"), false},\n\n\t\t// unsupported\n\t\t{nil, false},\n\t\t{myStruct{}, false},\n\t\t{\u0026myStruct{}, false},\n\t}\n\n\tfor _, c := range cases {\n\t\tname := fmt.Sprintf(\"Empty(%v)\", c.obj)\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tres := uassert.Empty(mockT, c.obj)\n\n\t\t\tif res != c.expectedEmpty {\n\t\t\t\tt.Errorf(\"%s should return %v: %s\", name, c.expectedEmpty, mockT.actualString())\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestEqualWithStringDiff(t *testing.T) {\n\tcases := []struct {\n\t\tname        string\n\t\texpected    string\n\t\tactual      string\n\t\tshouldPass  bool\n\t\texpectedMsg string\n\t}{\n\t\t{\n\t\t\tname:        \"Identical strings\",\n\t\t\texpected:    \"Hello, world!\",\n\t\t\tactual:      \"Hello, world!\",\n\t\t\tshouldPass:  true,\n\t\t\texpectedMsg: \"\",\n\t\t},\n\t\t{\n\t\t\tname:        \"Different strings - simple\",\n\t\t\texpected:    \"Hello, world!\",\n\t\t\tactual:      \"Hello, World!\",\n\t\t\tshouldPass:  false,\n\t\t\texpectedMsg: \"error: uassert.Equal: strings are different\\n\\tDiff: Hello, [-w][+W]orld!\",\n\t\t},\n\t\t{\n\t\t\tname:        \"Different strings - complex\",\n\t\t\texpected:    \"The quick brown fox jumps over the lazy dog\",\n\t\t\tactual:      \"The quick brown cat jumps over the lazy dog\",\n\t\t\tshouldPass:  false,\n\t\t\texpectedMsg: \"error: uassert.Equal: strings are different\\n\\tDiff: The quick brown [-fox][+cat] jumps over the lazy dog\",\n\t\t},\n\t\t{\n\t\t\tname:        \"Different strings - prefix\",\n\t\t\texpected:    \"prefix_string\",\n\t\t\tactual:      \"string\",\n\t\t\tshouldPass:  false,\n\t\t\texpectedMsg: \"error: uassert.Equal: strings are different\\n\\tDiff: [-prefix_]string\",\n\t\t},\n\t\t{\n\t\t\tname:        \"Different strings - suffix\",\n\t\t\texpected:    \"string\",\n\t\t\tactual:      \"string_suffix\",\n\t\t\tshouldPass:  false,\n\t\t\texpectedMsg: \"error: uassert.Equal: strings are different\\n\\tDiff: string[+_suffix]\",\n\t\t},\n\t\t{\n\t\t\tname:        \"Empty string vs non-empty string\",\n\t\t\texpected:    \"\",\n\t\t\tactual:      \"non-empty\",\n\t\t\tshouldPass:  false,\n\t\t\texpectedMsg: \"error: uassert.Equal: strings are different\\n\\tDiff: [+non-empty]\",\n\t\t},\n\t\t{\n\t\t\tname:        \"Non-empty string vs empty string\",\n\t\t\texpected:    \"non-empty\",\n\t\t\tactual:      \"\",\n\t\t\tshouldPass:  false,\n\t\t\texpectedMsg: \"error: uassert.Equal: strings are different\\n\\tDiff: [-non-empty]\",\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tmockT := \u0026mockTestingT{}\n\t\t\tresult := uassert.Equal(mockT, tc.expected, tc.actual)\n\n\t\t\tif result != tc.shouldPass {\n\t\t\t\tt.Errorf(\"Expected Equal to return %v, but got %v\", tc.shouldPass, result)\n\t\t\t}\n\n\t\t\tif tc.shouldPass {\n\t\t\t\tmockT.empty(t)\n\t\t\t} else {\n\t\t\t\tmockT.equals(t, tc.expectedMsg)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNotEmpty(t *testing.T) {\n\tmockT := new(mockTestingT)\n\n\tcases := []struct {\n\t\tobj              any\n\t\texpectedNotEmpty bool\n\t}{\n\t\t// expected to be empty\n\t\t{\"\", false},\n\t\t{0, false},\n\t\t{int(0), false},\n\t\t{int32(0), false},\n\t\t{int64(0), false},\n\t\t{uint(0), false},\n\t\t{address(\"\"), false},\n\n\t\t// not expected to be empty\n\t\t{\"Hello World\", true},\n\t\t{1, true},\n\t\t{int32(1), true},\n\t\t{uint64(1), true},\n\t\t{address(\"g12345\"), true},\n\n\t\t// unsupported\n\t\t{nil, false},\n\t\t{myStruct{}, false},\n\t\t{\u0026myStruct{}, false},\n\t}\n\n\tfor _, c := range cases {\n\t\tname := fmt.Sprintf(\"NotEmpty(%v)\", c.obj)\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tres := uassert.NotEmpty(mockT, c.obj)\n\n\t\t\tif res != c.expectedNotEmpty {\n\t\t\t\tt.Errorf(\"%s should return %v: %s\", name, c.expectedNotEmpty, mockT.actualString())\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNil(t *testing.T) {\n\tmockT := new(mockTestingT)\n\tif !uassert.Nil(mockT, nil) {\n\t\tt.Error(\"Nil should return true\")\n\t}\n\tmockT.empty(t)\n\tif uassert.Nil(mockT, 0) {\n\t\tt.Error(\"Nil should return false\")\n\t}\n\tmockT.equals(t, \"error: should be nil\")\n\tif uassert.Nil(mockT, (*int)(nil)) {\n\t\tt.Error(\"Nil should return false\")\n\t}\n\tmockT.equals(t, \"error: should be nil\")\n}\n\nfunc TestNotNil(t *testing.T) {\n\tmockT := new(mockTestingT)\n\tif uassert.NotNil(mockT, nil) {\n\t\tt.Error(\"NotNil should return false\")\n\t}\n\tmockT.equals(t, \"error: should not be nil\")\n\tif !uassert.NotNil(mockT, 0) {\n\t\tt.Error(\"NotNil should return true\")\n\t}\n\tmockT.empty(t)\n\tif !uassert.NotNil(mockT, (*int)(nil)) {\n\t\tt.Error(\"NotNil should return true\")\n\t}\n\tmockT.empty(t)\n}\n\nfunc TestTypedNil(t *testing.T) {\n\tmockT := new(mockTestingT)\n\tif uassert.TypedNil(mockT, nil) {\n\t\tt.Error(\"TypedNil should return false\")\n\t}\n\tmockT.equals(t, \"error: should be typed-nil but got nil instead\")\n\tif uassert.TypedNil(mockT, 0) {\n\t\tt.Error(\"TypedNil should return false\")\n\t}\n\tmockT.equals(t, \"error: should be typed-nil\")\n\tif !uassert.TypedNil(mockT, (*int)(nil)) {\n\t\tt.Error(\"TypedNil should return true\")\n\t}\n\tmockT.empty(t)\n}\n\nfunc TestNotTypedNil(t *testing.T) {\n\tmockT := new(mockTestingT)\n\tif !uassert.NotTypedNil(mockT, nil) {\n\t\tt.Error(\"NotTypedNil should return true\")\n\t}\n\tmockT.empty(t)\n\tif !uassert.NotTypedNil(mockT, 0) {\n\t\tt.Error(\"NotTypedNil should return true\")\n\t}\n\tmockT.empty(t)\n\tif uassert.NotTypedNil(mockT, (*int)(nil)) {\n\t\tt.Error(\"NotTypedNil should return false\")\n\t}\n\tmockT.equals(t, \"error: should not be typed-nil\")\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"d4f+iiKthmSTFALWqjM+OixNgGYRJrmV5HVMV4ZyfWdk7uAzDWz9jUu8wsClw0v3MHcvkKdLeroTpDUFmcpoMg=="}],"memo":""}},{"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/v0/pager` - pagination helper for trees and lists.\n- `gno.land/p/nt/avl/v0/rotree` - 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":"node_test.gno","body":"package avl\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\tasc  bool\n\t}{\n\t\t{\"ascending\", true},\n\t\t{\"descending\", false},\n\t}\n\n\tfor _, tt := range tt {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t// use sl to insert the values, and reversed to match the values\n\t\t\t// we do this to ensure that the order of TraverseByOffset is independent\n\t\t\t// from the insertion order\n\t\t\tsl := strings.Split(testStrings, \"\\n\")\n\t\t\tsort.Strings(sl)\n\t\t\treversed := append([]string{}, sl...)\n\t\t\treverseSlice(reversed)\n\n\t\t\tif !tt.asc {\n\t\t\t\tsl, reversed = reversed, sl\n\t\t\t}\n\n\t\t\tr := NewNode(reversed[0], nil)\n\t\t\tfor _, v := range reversed[1:] {\n\t\t\t\tr, _ = r.Set(v, nil)\n\t\t\t}\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.asc, 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.asc, 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 TestTraverseByOffsetNegativeOffset(t *testing.T) {\n\t// a negative offset must be treated as 0, not silently drop the right\n\t// subtree. building {\"a\",\"b\",\"c\",\"d\"} yields a tree whose root has two\n\t// inner children, exercising the traverseByOffset delta computation.\n\tkeys := []string{\"a\", \"b\", \"c\", \"d\"}\n\tr := NewNode(keys[0], nil)\n\tfor _, k := range keys[1:] {\n\t\tr, _ = r.Set(k, nil)\n\t}\n\n\tfor _, offset := range []int{-1, -2, -100} {\n\t\tvar got []string\n\t\tr.TraverseByOffset(offset, len(keys), true, true, func(n *Node) bool {\n\t\t\tgot = append(got, n.Key())\n\t\t\treturn false\n\t\t})\n\t\tif !slicesEqual(keys, got) {\n\t\t\tt.Errorf(\"offset %d: want %v got %v\", offset, keys, got)\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\n\t\t\tt.Run(\"early termination\", func(t *testing.T) {\n\t\t\t\tif len(tt.input) == 0 {\n\t\t\t\t\treturn // Skip for empty tree\n\t\t\t\t}\n\n\t\t\t\tvar result []string\n\t\t\t\tvar count int\n\t\t\t\ttree.Iterate(\"\", \"\", func(n *Node) bool {\n\t\t\t\t\tcount++\n\t\t\t\t\tresult = append(result, n.Key())\n\t\t\t\t\treturn true // Stop after first item\n\t\t\t\t})\n\n\t\t\t\tif count != 1 {\n\t\t\t\t\tt.Errorf(\"Expected callback to be called exactly once, got %d calls\", count)\n\t\t\t\t}\n\t\t\t\tif len(result) != 1 {\n\t\t\t\t\tt.Errorf(\"Expected exactly one result, got %d items\", len(result))\n\t\t\t\t}\n\t\t\t\tif len(result) \u003e 0 \u0026\u0026 result[0] != tt.expected[0] {\n\t\t\t\t\tt.Errorf(\"Expected first item to be %v, got %v\", tt.expected[0], result[0])\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\", \"D\", \"E\"},\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\", \"D\", \"E\"},\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\", \"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\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 TestRemoveFromEmptyTree(t *testing.T) {\n\tvar tree *Node\n\tnewTree, _, val, removed := tree.Remove(\"NonExistent\")\n\tif newTree != nil {\n\t\tt.Errorf(\"Removing from an empty tree should still be nil tree.\")\n\t}\n\tif val != nil || removed {\n\t\tt.Errorf(\"Expected no value and removed=false when removing from empty tree.\")\n\t}\n}\n\nfunc TestBalanceAfterRemoval(t *testing.T) {\n\ttests := []struct {\n\t\tname            string\n\t\tinsertKeys      []string\n\t\tremoveKey       string\n\t\texpectedBalance int\n\t}{\n\t\t{\n\t\t\tname:            \"balance after removing right node\",\n\t\t\tinsertKeys:      []string{\"B\", \"A\", \"D\", \"C\", \"E\"},\n\t\t\tremoveKey:       \"E\",\n\t\t\texpectedBalance: 0,\n\t\t},\n\t\t{\n\t\t\tname:            \"balance after removing left node\",\n\t\t\tinsertKeys:      []string{\"D\", \"B\", \"E\", \"A\", \"C\"},\n\t\t\tremoveKey:       \"A\",\n\t\t\texpectedBalance: 0,\n\t\t},\n\t\t{\n\t\t\tname:            \"ensure no lean after removal\",\n\t\t\tinsertKeys:      []string{\"C\", \"B\", \"E\", \"A\", \"D\", \"F\"},\n\t\t\tremoveKey:       \"F\",\n\t\t\texpectedBalance: -1,\n\t\t},\n\t\t{\n\t\t\tname:            \"descending order insert, remove middle node\",\n\t\t\tinsertKeys:      []string{\"E\", \"D\", \"C\", \"B\", \"A\"},\n\t\t\tremoveKey:       \"C\",\n\t\t\texpectedBalance: 0,\n\t\t},\n\t\t{\n\t\t\tname:            \"ascending order insert, remove middle node\",\n\t\t\tinsertKeys:      []string{\"A\", \"B\", \"C\", \"D\", \"E\"},\n\t\t\tremoveKey:       \"C\",\n\t\t\texpectedBalance: 0,\n\t\t},\n\t\t{\n\t\t\tname:            \"duplicate key insert, remove the duplicated key\",\n\t\t\tinsertKeys:      []string{\"C\", \"B\", \"C\", \"A\", \"D\"},\n\t\t\tremoveKey:       \"C\",\n\t\t\texpectedBalance: 1,\n\t\t},\n\t\t{\n\t\t\tname:            \"complex rotation case\",\n\t\t\tinsertKeys:      []string{\"H\", \"B\", \"A\", \"C\", \"E\", \"D\", \"F\", \"G\"},\n\t\t\tremoveKey:       \"B\",\n\t\t\texpectedBalance: 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 tree *Node\n\t\t\tfor _, key := range tt.insertKeys {\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\tbalance := tree.calcBalance()\n\t\t\tif balance != tt.expectedBalance {\n\t\t\t\tt.Errorf(\"Expected balance factor %d, got %d\", tt.expectedBalance, balance)\n\t\t\t}\n\n\t\t\tif balance \u003c -1 || balance \u003e 1 {\n\t\t\t\tt.Errorf(\"Tree is unbalanced with factor %d\", balance)\n\t\t\t}\n\n\t\t\tif errMsg := checkSubtreeBalance(t, tree); errMsg != \"\" {\n\t\t\t\tt.Errorf(\"AVL property violation after removal: %s\", errMsg)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestBSTProperty(t *testing.T) {\n\tvar tree *Node\n\tkeys := []string{\"D\", \"B\", \"F\", \"A\", \"C\", \"E\", \"G\"}\n\tfor _, key := range keys {\n\t\ttree, _ = tree.Set(key, nil)\n\t}\n\n\tvar result []string\n\tinorderTraversal(t, tree, \u0026result)\n\n\tfor i := 1; i \u003c len(result); i++ {\n\t\tif result[i] \u003c result[i-1] {\n\t\t\tt.Errorf(\"BST property violated: %s \u003c %s (index %d)\",\n\t\t\t\tresult[i], result[i-1], i)\n\t\t}\n\t}\n}\n\n// inorderTraversal performs an inorder traversal of the tree and returns the keys in a list.\nfunc inorderTraversal(t *testing.T, node *Node, result *[]string) {\n\tt.Helper()\n\n\tif node == nil {\n\t\treturn\n\t}\n\t// leaf\n\tif node.height == 0 {\n\t\t*result = append(*result, node.key)\n\t\treturn\n\t}\n\tinorderTraversal(t, node.leftNode, result)\n\tinorderTraversal(t, node.rightNode, result)\n}\n\n// checkSubtreeBalance checks if all nodes under the given node satisfy the AVL tree conditions.\n// The balance factor of all nodes must be ∈ [-1, +1]\nfunc checkSubtreeBalance(t *testing.T, node *Node) string {\n\tt.Helper()\n\n\tif node == nil {\n\t\treturn \"\"\n\t}\n\n\tif node.IsLeaf() {\n\t\t// leaf node must be height=0, size=1\n\t\tif node.height != 0 {\n\t\t\treturn ufmt.Sprintf(\"Leaf node %s has height %d, expected 0\", node.Key(), node.height)\n\t\t}\n\t\tif node.size != 1 {\n\t\t\treturn ufmt.Sprintf(\"Leaf node %s has size %d, expected 1\", node.Key(), node.size)\n\t\t}\n\t\treturn \"\"\n\t}\n\n\t// check balance factor for current node\n\tbalanceFactor := node.calcBalance()\n\tif balanceFactor \u003c -1 || balanceFactor \u003e 1 {\n\t\treturn ufmt.Sprintf(\"Node %s is unbalanced: balanceFactor=%d\", node.Key(), balanceFactor)\n\t}\n\n\t// check height / size relationship for children\n\tleft, right := node.getLeftNode(), node.getRightNode()\n\texpectedHeight := maxInt8(left.height, right.height) + 1\n\tif node.height != expectedHeight {\n\t\treturn ufmt.Sprintf(\"Node %s has incorrect height %d, expected %d\", node.Key(), node.height, expectedHeight)\n\t}\n\texpectedSize := left.Size() + right.Size()\n\tif node.size != expectedSize {\n\t\treturn ufmt.Sprintf(\"Node %s has incorrect size %d, expected %d\", node.Key(), node.size, expectedSize)\n\t}\n\n\t// recursively check the left/right subtree\n\tif errMsg := checkSubtreeBalance(t, left); errMsg != \"\" {\n\t\treturn errMsg\n\t}\n\tif errMsg := checkSubtreeBalance(t, right); errMsg != \"\" {\n\t\treturn errMsg\n\t}\n\n\treturn \"\"\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[i] != w2[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\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"},{"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"},{"name":"tree_test.gno","body":"package avl\n\nimport \"testing\"\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 := tree.Get(\"key1\")\n\tif value != \"value1\" {\n\t\tt.Error(\"Expected Get to return value1\")\n\t}\n\n\tvalue = tree.Get(\"key2\")\n\tif value != nil {\n\t\tt.Error(\"Expected Get to return nil 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\nfunc TestTreeReverseIterateByOffsetVaried(t *testing.T) {\n\ttree := NewTree()\n\ttree.Set(\"a\", 1)\n\ttree.Set(\"b\", 2)\n\ttree.Set(\"c\", 3)\n\ttree.Set(\"d\", 4)\n\ttree.Set(\"e\", 5)\n\n\t// All keys in reverse: e d c b a\n\tcases := []struct {\n\t\toffset int\n\t\tlimit  int\n\t\twant   []string\n\t}{\n\t\t{0, 5, []string{\"e\", \"d\", \"c\", \"b\", \"a\"}},\n\t\t{0, 1, []string{\"e\"}},\n\t\t{0, 3, []string{\"e\", \"d\", \"c\"}},\n\t\t{1, 2, []string{\"d\", \"c\"}},\n\t\t{2, 2, []string{\"c\", \"b\"}},\n\t\t{3, 5, []string{\"b\", \"a\"}},\n\t\t{4, 1, []string{\"a\"}},\n\t\t{4, 10, []string{\"a\"}},\n\t\t{5, 1, nil},\n\t\t{0, 0, nil},\n\t\t{10, 1, nil},\n\t}\n\n\tfor _, tc := range cases {\n\t\tvar got []string\n\t\ttree.ReverseIterateByOffset(tc.offset, tc.limit, func(key string, value any) bool {\n\t\t\tgot = append(got, key)\n\t\t\treturn false\n\t\t})\n\t\tif !slicesEqual(got, tc.want) {\n\t\t\tt.Errorf(\"ReverseIterateByOffset(%d, %d): got %v, want %v\",\n\t\t\t\ttc.offset, tc.limit, got, tc.want)\n\t\t}\n\t}\n\n\t// Early termination: stop after 2 items from offset 1.\n\tvar got []string\n\ttree.ReverseIterateByOffset(1, 5, func(key string, value any) bool {\n\t\tgot = append(got, key)\n\t\treturn len(got) \u003e= 2\n\t})\n\twant := []string{\"d\", \"c\"}\n\tif !slicesEqual(got, want) {\n\t\tt.Errorf(\"ReverseIterateByOffset early stop: got %v, want %v\", got, want)\n\t}\n}\n"},{"name":"z_0_filetest.gno","body":"// PKGPATH: gno.land/r/test\npackage test\n\nimport (\n\t\"gno.land/p/nt/avl/v0\"\n)\n\nvar node *avl.Node\n\nfunc init() {\n\tnode = avl.NewNode(\"key0\", \"value0\")\n\t// node, _ = node.Set(\"key0\", \"value0\")\n}\n\nfunc main(cur realm) {\n\tvar updated bool\n\tnode, updated = node.Set(\"key1\", \"value1\")\n\t// println(node, updated)\n\tprintln(updated, node.Size())\n}\n\n// Output:\n// false 2\n"},{"name":"z_1_filetest.gno","body":"// PKGPATH: gno.land/r/test\npackage test\n\nimport (\n\t\"gno.land/p/nt/avl/v0\"\n)\n\nvar node *avl.Node\n\nfunc init() {\n\tnode = avl.NewNode(\"key0\", \"value0\")\n\tnode, _ = node.Set(\"key1\", \"value1\")\n}\n\nfunc main(cur realm) {\n\tvar updated bool\n\tnode, updated = node.Set(\"key2\", \"value2\")\n\t// println(node, updated)\n\tprintln(updated, node.Size())\n}\n\n// Output:\n// false 3\n"},{"name":"z_2_filetest.gno","body":"// PKGPATH: gno.land/r/test\npackage test\n\nimport (\n\t\"gno.land/p/nt/avl/v0\"\n)\n\nvar tree avl.Tree\n\nfunc init() {\n\ttree.Set(\"key0\", \"value0\")\n\ttree.Set(\"key1\", \"value1\")\n}\n\nfunc main(cur realm) {\n\tvar updated bool\n\tupdated = tree.Set(\"key2\", \"value2\")\n\tprintln(updated, tree.Size())\n}\n\n// Output:\n// false 3\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"IER6PrGJq2rxEC1F4ecX31+YB8y1pkF1YGKAQIBZhah3ZD8pJBOcy9/GER2j2eb5/RT37udl1X6K1hdT8IiK6A=="}],"memo":""}},{"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":"cford32_test.gno","body":"package cford32\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"math/rand\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestCompactRoundtrip(t *testing.T) {\n\tbuf := make([]byte, 13)\n\tprev := make([]byte, 13)\n\tfor i := uint64(0); i \u003c (1 \u003c\u003c 10); i++ {\n\t\tres := AppendCompact(i, buf[:0])\n\t\tback, err := Uint64(res)\n\t\ttestEqual(t, \"Uint64(%q) = (%d, %v), want %v\", string(res), back, err, nil)\n\t\ttestEqual(t, \"Uint64(%q) = %d, want %v\", string(res), back, i)\n\n\t\ttestEqual(t, \"bytes.Compare(prev, res) = %d, want %d\", bytes.Compare(prev, res), -1)\n\t\tprev, buf = res, prev\n\t}\n\tfor i := uint64(1\u003c\u003c34 - 1024); i \u003c (1\u003c\u003c34 + 1024); i++ {\n\t\tres := AppendCompact(i, buf[:0])\n\t\tback, err := Uint64(res)\n\t\t// println(string(res))\n\t\ttestEqual(t, \"Uint64(%q) = (%d, %v), want %v\", string(res), back, err, nil)\n\t\ttestEqual(t, \"Uint64(%q) = %d, want %v\", string(res), back, i)\n\n\t\ttestEqual(t, \"bytes.Compare(prev, res) = %d, want %d\", bytes.Compare(prev, res), -1)\n\t\tprev, buf = res, prev\n\t}\n\tfor i := uint64(1\u003c\u003c64 - 5000); i != 0; i++ {\n\t\tres := AppendCompact(i, buf[:0])\n\t\tback, err := Uint64(res)\n\t\ttestEqual(t, \"Uint64(%q) = (%d, %v), want %v\", string(res), back, err, nil)\n\t\ttestEqual(t, \"Uint64(%q) = %d, want %v\", string(res), back, i)\n\n\t\ttestEqual(t, \"bytes.Compare(prev, res) = %d, want %d\", bytes.Compare(prev, res), -1)\n\t\tprev, buf = res, prev\n\t}\n}\n\nfunc BenchmarkCompact(b *testing.B) {\n\tbuf := make([]byte, 13)\n\tfor i := 0; i \u003c b.N; i++ {\n\t\t_ = AppendCompact(uint64(i), buf[:0])\n\t}\n}\n\nfunc TestUint64(t *testing.T) {\n\ttt := []struct {\n\t\tval    string\n\t\toutput uint64\n\t\terr    string\n\t}{\n\t\t{\"0000001\", 1, \"\"},\n\t\t{\"OoOoOoL\", 1, \"\"},\n\t\t{\"OoUoOoL\", 0, CorruptInputError(2).Error()},\n\t\t{\"!123123\", 0, CorruptInputError(0).Error()},\n\t\t{\"Loooooo\", 1073741824, \"\"},\n\t\t{\"goooooo\", 0, CorruptInputError(0).Error()},\n\t\t{\"goooooooooooo\", 0, \"\"},\n\t\t{\"goooooooooolo\", 32, \"\"},\n\t\t{\"fzzzzzz\", (1 \u003c\u003c 34) - 1, \"\"},\n\t\t{\"g00000fzzzzzz\", (1 \u003c\u003c 34) - 1, \"\"},\n\t\t{\"g000000\", 0, CorruptInputError(0).Error()},\n\t\t{\"g00000g000000\", (1 \u003c\u003c 34), \"\"},\n\t}\n\n\tfor _, tc := range tt {\n\t\tt.Run(tc.val, func(t *testing.T) {\n\t\t\tres, err := Uint64([]byte(tc.val))\n\t\t\tif tc.err != \"\" {\n\t\t\t\t_ = uassert.Error(t, err) \u0026\u0026\n\t\t\t\t\tuassert.Equal(t, tc.err, err.Error())\n\t\t\t} else {\n\t\t\t\t_ = uassert.NoError(t, err) \u0026\u0026\n\t\t\t\t\tuassert.Equal(t, tc.output, res)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestRandomCompactRoundtrip(t *testing.T) {\n\tfor i := 0; i \u003c 1\u003c\u003c12; i++ {\n\t\tvalue := rand.Uint64()\n\t\tencoded := PutCompact(value)\n\t\tdecoded, err := Uint64(encoded)\n\t\tuassert.NoError(t, err)\n\t\tuassert.Equal(t, value, decoded)\n\t}\n}\n\ntype testpair struct {\n\tdecoded, encoded string\n}\n\nvar pairs = []testpair{\n\t{\"\", \"\"},\n\t{\"f\", \"CR\"},\n\t{\"fo\", \"CSQG\"},\n\t{\"foo\", \"CSQPY\"},\n\t{\"foob\", \"CSQPYRG\"},\n\t{\"fooba\", \"CSQPYRK1\"},\n\t{\"foobar\", \"CSQPYRK1E8\"},\n\n\t{\"sure.\", \"EDTQ4S9E\"},\n\t{\"sure\", \"EDTQ4S8\"},\n\t{\"sur\", \"EDTQ4\"},\n\t{\"su\", \"EDTG\"},\n\t{\"leasure.\", \"DHJP2WVNE9JJW\"},\n\t{\"easure.\", \"CNGQ6XBJCMQ0\"},\n\t{\"asure.\", \"C5SQAWK55R\"},\n}\n\nvar bigtest = testpair{\n\t\"Twas brillig, and the slithy toves\",\n\t\"AHVP2WS0C9S6JV3CD5KJR831DSJ20X38CMG76V39EHM7J83MDXV6AWR\",\n}\n\nfunc testEqual(t *testing.T, msg string, args ...any) bool {\n\tt.Helper()\n\tif args[len(args)-2] != args[len(args)-1] {\n\t\tt.Errorf(msg, args...)\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc TestEncode(t *testing.T) {\n\tfor _, p := range pairs {\n\t\tgot := EncodeToString([]byte(p.decoded))\n\t\ttestEqual(t, \"Encode(%q) = %q, want %q\", p.decoded, got, p.encoded)\n\t\tdst := AppendEncode([]byte(\"lead\"), []byte(p.decoded))\n\t\ttestEqual(t, `AppendEncode(\"lead\", %q) = %q, want %q`, p.decoded, string(dst), \"lead\"+p.encoded)\n\t}\n}\n\nfunc TestEncoder(t *testing.T) {\n\tfor _, p := range pairs {\n\t\tbb := \u0026strings.Builder{}\n\t\tencoder := NewEncoder(bb)\n\t\tencoder.Write([]byte(p.decoded))\n\t\tencoder.Close()\n\t\ttestEqual(t, \"Encode(%q) = %q, want %q\", p.decoded, bb.String(), p.encoded)\n\t}\n}\n\nfunc TestEncoderBuffering(t *testing.T) {\n\tinput := []byte(bigtest.decoded)\n\tfor bs := 1; bs \u003c= 12; bs++ {\n\t\tbb := \u0026strings.Builder{}\n\t\tencoder := NewEncoder(bb)\n\t\tfor pos := 0; pos \u003c len(input); pos += bs {\n\t\t\tend := pos + bs\n\t\t\tif end \u003e len(input) {\n\t\t\t\tend = len(input)\n\t\t\t}\n\t\t\tn, err := encoder.Write(input[pos:end])\n\t\t\ttestEqual(t, \"Write(%q) gave error %v, want %v\", input[pos:end], err, error(nil))\n\t\t\ttestEqual(t, \"Write(%q) gave length %v, want %v\", input[pos:end], n, end-pos)\n\t\t}\n\t\terr := encoder.Close()\n\t\ttestEqual(t, \"Close gave error %v, want %v\", err, error(nil))\n\t\ttestEqual(t, \"Encoding/%d of %q = %q, want %q\", bs, bigtest.decoded, bb.String(), bigtest.encoded)\n\t}\n}\n\nfunc TestDecode(t *testing.T) {\n\tfor _, p := range pairs {\n\t\tdbuf := make([]byte, DecodedLen(len(p.encoded)))\n\t\tcount, err := decode(dbuf, []byte(p.encoded))\n\t\ttestEqual(t, \"Decode(%q) = error %v, want %v\", p.encoded, err, error(nil))\n\t\ttestEqual(t, \"Decode(%q) = length %v, want %v\", p.encoded, count, len(p.decoded))\n\t\ttestEqual(t, \"Decode(%q) = %q, want %q\", p.encoded, string(dbuf[0:count]), p.decoded)\n\n\t\tdbuf, err = DecodeString(p.encoded)\n\t\ttestEqual(t, \"DecodeString(%q) = error %v, want %v\", p.encoded, err, error(nil))\n\t\ttestEqual(t, \"DecodeString(%q) = %q, want %q\", p.encoded, string(dbuf), p.decoded)\n\n\t\t// XXX: https://github.com/gnolang/gno/issues/1570\n\t\tdst, err := AppendDecode(append([]byte(nil), []byte(\"lead\")...), []byte(p.encoded))\n\t\ttestEqual(t, \"AppendDecode(%q) = error %v, want %v\", p.encoded, err, error(nil))\n\t\ttestEqual(t, `AppendDecode(\"lead\", %q) = %q, want %q`, p.encoded, string(dst), \"lead\"+p.decoded)\n\n\t\tdst2, err := AppendDecode(dst[:0:len(p.decoded)], []byte(p.encoded))\n\t\ttestEqual(t, \"AppendDecode(%q) = error %v, want %v\", p.encoded, err, error(nil))\n\t\ttestEqual(t, `AppendDecode(\"\", %q) = %q, want %q`, p.encoded, string(dst2), p.decoded)\n\t\t// XXX: https://github.com/gnolang/gno/issues/1569\n\t\t// old used \u0026dst2[0] != \u0026dst[0] as a check.\n\t\tif len(dst) \u003e 0 \u0026\u0026 len(dst2) \u003e 0 \u0026\u0026 cap(dst2) != len(p.decoded) {\n\t\t\tt.Errorf(\"unexpected capacity growth: got %d, want %d\", cap(dst2), len(p.decoded))\n\t\t}\n\t}\n}\n\n// A minimal variation on strings.Reader.\n// Here, we return a io.EOF immediately on Read if the read has reached the end\n// of the reader. It's used to simplify TestDecoder.\ntype stringReader struct {\n\ts string\n\ti int64\n}\n\nfunc (r *stringReader) Read(b []byte) (n int, err error) {\n\tif r.i \u003e= int64(len(r.s)) {\n\t\treturn 0, io.EOF\n\t}\n\tn = copy(b, r.s[r.i:])\n\tr.i += int64(n)\n\tif r.i \u003e= int64(len(r.s)) {\n\t\treturn n, io.EOF\n\t}\n\treturn\n}\n\nfunc TestDecoder(t *testing.T) {\n\tfor _, p := range pairs {\n\t\tdecoder := NewDecoder(\u0026stringReader{p.encoded, 0})\n\t\tdbuf := make([]byte, DecodedLen(len(p.encoded)))\n\t\tcount, err := decoder.Read(dbuf)\n\t\tif err != nil \u0026\u0026 err != io.EOF {\n\t\t\tt.Fatal(\"Read failed\", err)\n\t\t}\n\t\ttestEqual(t, \"Read from %q = length %v, want %v\", p.encoded, count, len(p.decoded))\n\t\ttestEqual(t, \"Decoding of %q = %q, want %q\", p.encoded, string(dbuf[0:count]), p.decoded)\n\t\tif err != io.EOF {\n\t\t\t_, err = decoder.Read(dbuf)\n\t\t}\n\t\ttestEqual(t, \"Read from %q = %v, want %v\", p.encoded, err, io.EOF)\n\t}\n}\n\ntype badReader struct {\n\tdata   []byte\n\terrs   []error\n\tcalled int\n\tlimit  int\n}\n\n// Populates p with data, returns a count of the bytes written and an\n// error.  The error returned is taken from badReader.errs, with each\n// invocation of Read returning the next error in this slice, or io.EOF,\n// if all errors from the slice have already been returned.  The\n// number of bytes returned is determined by the size of the input buffer\n// the test passes to decoder.Read and will be a multiple of 8, unless\n// badReader.limit is non zero.\nfunc (b *badReader) Read(p []byte) (int, error) {\n\tlim := len(p)\n\tif b.limit != 0 \u0026\u0026 b.limit \u003c lim {\n\t\tlim = b.limit\n\t}\n\tif len(b.data) \u003c lim {\n\t\tlim = len(b.data)\n\t}\n\tfor i := range p[:lim] {\n\t\tp[i] = b.data[i]\n\t}\n\tb.data = b.data[lim:]\n\terr := io.EOF\n\tif b.called \u003c len(b.errs) {\n\t\terr = b.errs[b.called]\n\t}\n\tb.called++\n\treturn lim, err\n}\n\n// TestIssue20044 tests that decoder.Read behaves correctly when the caller\n// supplied reader returns an error.\nfunc TestIssue20044(t *testing.T) {\n\tbadErr := errors.New(\"bad reader error\")\n\ttestCases := []struct {\n\t\tr       badReader\n\t\tres     string\n\t\terr     error\n\t\tdbuflen int\n\t}{\n\t\t// Check valid input data accompanied by an error is processed and the error is propagated.\n\t\t{\n\t\t\tr:   badReader{data: []byte(\"d1jprv3fexqq4v34\"), errs: []error{badErr}},\n\t\t\tres: \"helloworld\", err: badErr,\n\t\t},\n\t\t// Check a read error accompanied by input data consisting of newlines only is propagated.\n\t\t{\n\t\t\tr:   badReader{data: []byte(\"\\n\\n\\n\\n\\n\\n\\n\\n\"), errs: []error{badErr, nil}},\n\t\t\tres: \"\", err: badErr,\n\t\t},\n\t\t// Reader will be called twice.  The first time it will return 8 newline characters.  The\n\t\t// second time valid base32 encoded data and an error.  The data should be decoded\n\t\t// correctly and the error should be propagated.\n\t\t{\n\t\t\tr:   badReader{data: []byte(\"\\n\\n\\n\\n\\n\\n\\n\\nd1jprv3fexqq4v34\"), errs: []error{nil, badErr}},\n\t\t\tres: \"helloworld\", err: badErr, dbuflen: 8,\n\t\t},\n\t\t// Reader returns invalid input data (too short) and an error.  Verify the reader\n\t\t// error is returned.\n\t\t{\n\t\t\tr:   badReader{data: []byte(\"c\"), errs: []error{badErr}},\n\t\t\tres: \"\", err: badErr,\n\t\t},\n\t\t// Reader returns invalid input data (too short) but no error.  Verify io.ErrUnexpectedEOF\n\t\t// is returned.\n\t\t// NOTE(thehowl): I don't think this should applyto us?\n\t\t/* {\n\t\t\tr:   badReader{data: []byte(\"c\"), errs: []error{nil}},\n\t\t\tres: \"\", err: io.ErrUnexpectedEOF,\n\t\t},*/\n\t\t// Reader returns invalid input data and an error.  Verify the reader and not the\n\t\t// decoder error is returned.\n\t\t{\n\t\t\tr:   badReader{data: []byte(\"cu\"), errs: []error{badErr}},\n\t\t\tres: \"\", err: badErr,\n\t\t},\n\t\t// Reader returns valid data and io.EOF.  Check data is decoded and io.EOF is propagated.\n\t\t{\n\t\t\tr:   badReader{data: []byte(\"csqpyrk1\"), errs: []error{io.EOF}},\n\t\t\tres: \"fooba\", err: io.EOF,\n\t\t},\n\t\t// Check errors are properly reported when decoder.Read is called multiple times.\n\t\t// decoder.Read will be called 8 times, badReader.Read will be called twice, returning\n\t\t// valid data both times but an error on the second call.\n\t\t{\n\t\t\tr:   badReader{data: []byte(\"dhjp2wvne9jjwc9g\"), errs: []error{nil, badErr}},\n\t\t\tres: \"leasure.10\", err: badErr, dbuflen: 1,\n\t\t},\n\t\t// Check io.EOF is properly reported when decoder.Read is called multiple times.\n\t\t// decoder.Read will be called 8 times, badReader.Read will be called twice, returning\n\t\t// valid data both times but io.EOF on the second call.\n\t\t{\n\t\t\tr:   badReader{data: []byte(\"dhjp2wvne9jjw\"), errs: []error{nil, io.EOF}},\n\t\t\tres: \"leasure.\", err: io.EOF, dbuflen: 1,\n\t\t},\n\t\t// The following two test cases check that errors are propagated correctly when more than\n\t\t// 8 bytes are read at a time.\n\t\t{\n\t\t\tr:   badReader{data: []byte(\"dhjp2wvne9jjw\"), errs: []error{io.EOF}},\n\t\t\tres: \"leasure.\", err: io.EOF, dbuflen: 11,\n\t\t},\n\t\t{\n\t\t\tr:   badReader{data: []byte(\"dhjp2wvne9jjwc9g\"), errs: []error{badErr}},\n\t\t\tres: \"leasure.10\", err: badErr, dbuflen: 11,\n\t\t},\n\t\t// Check that errors are correctly propagated when the reader returns valid bytes in\n\t\t// groups that are not divisible by 8.  The first read will return 11 bytes and no\n\t\t// error.  The second will return 7 and an error.  The data should be decoded correctly\n\t\t// and the error should be propagated.\n\t\t// NOTE(thehowl): again, this is on the assumption that this is padded, and it's not.\n\t\t/* {\n\t\t\tr:   badReader{data: []byte(\"dhjp2wvne9jjw\"), errs: []error{nil, badErr}, limit: 11},\n\t\t\tres: \"leasure.\", err: badErr,\n\t\t}, */\n\t}\n\n\tfor idx, tc := range testCases {\n\t\tt.Run(fmt.Sprintf(\"%d-%s\", idx, string(tc.res)), func(t *testing.T) {\n\t\t\tinput := tc.r.data\n\t\t\tdecoder := NewDecoder(\u0026tc.r)\n\t\t\tvar dbuflen int\n\t\t\tif tc.dbuflen \u003e 0 {\n\t\t\t\tdbuflen = tc.dbuflen\n\t\t\t} else {\n\t\t\t\tdbuflen = DecodedLen(len(input))\n\t\t\t}\n\t\t\tdbuf := make([]byte, dbuflen)\n\t\t\tvar err error\n\t\t\tvar res []byte\n\t\t\tfor err == nil {\n\t\t\t\tvar n int\n\t\t\t\tn, err = decoder.Read(dbuf)\n\t\t\t\tif n \u003e 0 {\n\t\t\t\t\tres = append(res, dbuf[:n]...)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttestEqual(t, \"Decoding of %q = %q, want %q\", string(input), string(res), tc.res)\n\t\t\ttestEqual(t, \"Decoding of %q err = %v, expected %v\", string(input), err, tc.err)\n\t\t})\n\t}\n}\n\n// TestDecoderError verifies decode errors are propagated when there are no read\n// errors.\nfunc TestDecoderError(t *testing.T) {\n\tfor _, readErr := range []error{io.EOF, nil} {\n\t\tinput := \"ucsqpyrk1u\"\n\t\tdbuf := make([]byte, DecodedLen(len(input)))\n\t\tbr := badReader{data: []byte(input), errs: []error{readErr}}\n\t\tdecoder := NewDecoder(\u0026br)\n\t\tn, err := decoder.Read(dbuf)\n\t\ttestEqual(t, \"Read after EOF, n = %d, expected %d\", n, 0)\n\t\tif _, ok := err.(CorruptInputError); !ok {\n\t\t\tt.Errorf(\"Corrupt input error expected.  Found %T\", err)\n\t\t}\n\t}\n}\n\n// TestReaderEOF ensures decoder.Read behaves correctly when input data is\n// exhausted.\nfunc TestReaderEOF(t *testing.T) {\n\tfor _, readErr := range []error{io.EOF, nil} {\n\t\tinput := \"MZXW6YTB\"\n\t\tbr := badReader{data: []byte(input), errs: []error{nil, readErr}}\n\t\tdecoder := NewDecoder(\u0026br)\n\t\tdbuf := make([]byte, DecodedLen(len(input)))\n\t\tn, err := decoder.Read(dbuf)\n\t\ttestEqual(t, \"Decoding of %q err = %v, expected %v\", input, err, error(nil))\n\t\tn, err = decoder.Read(dbuf)\n\t\ttestEqual(t, \"Read after EOF, n = %d, expected %d\", n, 0)\n\t\ttestEqual(t, \"Read after EOF, err = %v, expected %v\", err, io.EOF)\n\t\tn, err = decoder.Read(dbuf)\n\t\ttestEqual(t, \"Read after EOF, n = %d, expected %d\", n, 0)\n\t\ttestEqual(t, \"Read after EOF, err = %v, expected %v\", err, io.EOF)\n\t}\n}\n\nfunc TestDecoderBuffering(t *testing.T) {\n\tfor bs := 1; bs \u003c= 12; bs++ {\n\t\tdecoder := NewDecoder(strings.NewReader(bigtest.encoded))\n\t\tbuf := make([]byte, len(bigtest.decoded)+12)\n\t\tvar total int\n\t\tvar n int\n\t\tvar err error\n\t\tfor total = 0; total \u003c len(bigtest.decoded) \u0026\u0026 err == nil; {\n\t\t\tn, err = decoder.Read(buf[total : total+bs])\n\t\t\ttotal += n\n\t\t}\n\t\tif err != nil \u0026\u0026 err != io.EOF {\n\t\t\tt.Errorf(\"Read from %q at pos %d = %d, unexpected error %v\", bigtest.encoded, total, n, err)\n\t\t}\n\t\ttestEqual(t, \"Decoding/%d of %q = %q, want %q\", bs, bigtest.encoded, string(buf[0:total]), bigtest.decoded)\n\t}\n}\n\nfunc TestDecodeCorrupt(t *testing.T) {\n\ttestCases := []struct {\n\t\tinput  string\n\t\toffset int // -1 means no corruption.\n\t}{\n\t\t{\"\", -1},\n\t\t{\"iIoOlL\", -1},\n\t\t{\"!!!!\", 0},\n\t\t{\"uxp10\", 0},\n\t\t{\"x===\", 1},\n\t\t{\"AA=A====\", 2},\n\t\t{\"AAA=AAAA\", 3},\n\t\t// Much fewer cases compared to Go as there are much fewer cases where input\n\t\t// can be \"corrupted\".\n\t}\n\tfor _, tc := range testCases {\n\t\tdbuf := make([]byte, DecodedLen(len(tc.input)))\n\t\t_, err := Decode(dbuf, []byte(tc.input))\n\t\tif tc.offset == -1 {\n\t\t\tif err != nil {\n\t\t\t\tt.Error(\"Decoder wrongly detected corruption in\", tc.input)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tswitch err := err.(type) {\n\t\tcase CorruptInputError:\n\t\t\ttestEqual(t, \"Corruption in %q at offset %v, want %v\", tc.input, int(err), tc.offset)\n\t\tdefault:\n\t\t\tt.Error(\"Decoder failed to detect corruption in\", tc)\n\t\t}\n\t}\n}\n\nfunc TestBig(t *testing.T) {\n\tn := 3*1000 + 1\n\traw := make([]byte, n)\n\tconst alpha = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\tfor i := 0; i \u003c n; i++ {\n\t\traw[i] = alpha[i%len(alpha)]\n\t}\n\tencoded := new(bytes.Buffer)\n\tw := NewEncoder(encoded)\n\tnn, err := w.Write(raw)\n\tif nn != n || err != nil {\n\t\tt.Fatalf(\"Encoder.Write(raw) = %d, %v want %d, nil\", nn, err, n)\n\t}\n\terr = w.Close()\n\tif err != nil {\n\t\tt.Fatalf(\"Encoder.Close() = %v want nil\", err)\n\t}\n\tdecoded, err := io.ReadAll(NewDecoder(encoded))\n\tif err != nil {\n\t\tt.Fatalf(\"io.ReadAll(NewDecoder(...)): %v\", err)\n\t}\n\n\tif !bytes.Equal(raw, decoded) {\n\t\tvar i int\n\t\tfor i = 0; i \u003c len(decoded) \u0026\u0026 i \u003c len(raw); i++ {\n\t\t\tif decoded[i] != raw[i] {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tt.Errorf(\"Decode(Encode(%d-byte string)) failed at offset %d\", n, i)\n\t}\n}\n\nfunc testStringEncoding(t *testing.T, expected string, examples []string) {\n\tfor _, e := range examples {\n\t\tbuf, err := DecodeString(e)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Decode(%q) failed: %v\", e, err)\n\t\t\tcontinue\n\t\t}\n\t\tif s := string(buf); s != expected {\n\t\t\tt.Errorf(\"Decode(%q) = %q, want %q\", e, s, expected)\n\t\t}\n\t}\n}\n\nfunc TestNewLineCharacters(t *testing.T) {\n\t// Each of these should decode to the string \"sure\", without errors.\n\texamples := []string{\n\t\t\"EDTQ4S8\",\n\t\t\"EDTQ4S8\\r\",\n\t\t\"EDTQ4S8\\n\",\n\t\t\"EDTQ4S8\\r\\n\",\n\t\t\"EDTQ4S\\r\\n8\",\n\t\t\"EDT\\rQ4S\\n8\",\n\t\t\"edt\\nq4s\\r8\",\n\t\t\"edt\\nq4s8\",\n\t\t\"EDTQ4S\\n8\",\n\t}\n\ttestStringEncoding(t, \"sure\", examples)\n}\n\nfunc BenchmarkEncode(b *testing.B) {\n\tdata := make([]byte, 8192)\n\tbuf := make([]byte, EncodedLen(len(data)))\n\tb.SetBytes(int64(len(data)))\n\tfor i := 0; i \u003c b.N; i++ {\n\t\tEncode(buf, data)\n\t}\n}\n\nfunc BenchmarkEncodeToString(b *testing.B) {\n\tdata := make([]byte, 8192)\n\tb.SetBytes(int64(len(data)))\n\tfor i := 0; i \u003c b.N; i++ {\n\t\tEncodeToString(data)\n\t}\n}\n\nfunc BenchmarkDecode(b *testing.B) {\n\tdata := make([]byte, EncodedLen(8192))\n\tEncode(data, make([]byte, 8192))\n\tbuf := make([]byte, 8192)\n\tb.SetBytes(int64(len(data)))\n\tfor i := 0; i \u003c b.N; i++ {\n\t\tDecode(buf, data)\n\t}\n}\n\nfunc BenchmarkDecodeString(b *testing.B) {\n\tdata := EncodeToString(make([]byte, 8192))\n\tb.SetBytes(int64(len(data)))\n\tfor i := 0; i \u003c b.N; i++ {\n\t\tDecodeString(data)\n\t}\n}\n\n/* TODO: rewrite without using goroutines\nfunc TestBufferedDecodingSameError(t *testing.T) {\n\ttestcases := []struct {\n\t\tprefix            string\n\t\tchunkCombinations [][]string\n\t\texpected          error\n\t}{\n\t\t// Normal case, this is valid input\n\t\t{\"helloworld\", [][]string{\n\t\t\t{\"D1JP\", \"RV3F\", \"EXQQ\", \"4V34\"},\n\t\t\t{\"D1JPRV3FEXQQ4V34\"},\n\t\t\t{\"D1J\", \"PRV\", \"3FE\", \"XQQ\", \"4V3\", \"4\"},\n\t\t\t{\"D1JPRV3FEXQQ4V\", \"34\"},\n\t\t}, nil},\n\n\t\t// Normal case, this is valid input\n\t\t{\"fooba\", [][]string{\n\t\t\t{\"CSQPYRK1\"},\n\t\t\t{\"CSQPYRK\", \"1\"},\n\t\t\t{\"CSQPYR\", \"K1\"},\n\t\t\t{\"CSQPY\", \"RK1\"},\n\t\t\t{\"CSQPY\", \"RK\", \"1\"},\n\t\t\t{\"CSQPY\", \"RK1\"},\n\t\t\t{\"CSQP\", \"YR\", \"K1\"},\n\t\t}, nil},\n\n\t\t// NOTE: many test cases have been removed as we don't return ErrUnexpectedEOF.\n\t}\n\n\tfor _, testcase := range testcases {\n\t\tfor _, chunks := range testcase.chunkCombinations {\n\t\t\tpr, pw := io.Pipe()\n\n\t\t\t// Write the encoded chunks into the pipe\n\t\t\tgo func() {\n\t\t\t\tfor _, chunk := range chunks {\n\t\t\t\t\tpw.Write([]byte(chunk))\n\t\t\t\t}\n\t\t\t\tpw.Close()\n\t\t\t}()\n\n\t\t\tdecoder := NewDecoder(pr)\n\t\t\tback, err := io.ReadAll(decoder)\n\n\t\t\tif err != testcase.expected {\n\t\t\t\tt.Errorf(\"Expected %v, got %v; case %s %+v\", testcase.expected, err, testcase.prefix, chunks)\n\t\t\t}\n\t\t\tif testcase.expected == nil {\n\t\t\t\ttestEqual(t, \"Decode from NewDecoder(chunkReader(%v)) = %q, want %q\", chunks, string(back), testcase.prefix)\n\t\t\t}\n\t\t}\n\t}\n}\n*/\n\nfunc TestEncodedLen(t *testing.T) {\n\ttype test struct {\n\t\tn    int\n\t\twant int64\n\t}\n\ttests := []test{\n\t\t{0, 0},\n\t\t{1, 2},\n\t\t{2, 4},\n\t\t{3, 5},\n\t\t{4, 7},\n\t\t{5, 8},\n\t\t{6, 10},\n\t\t{7, 12},\n\t\t{10, 16},\n\t\t{11, 18},\n\t}\n\t// check overflow\n\ttests = append(tests, test{(math.MaxInt-4)/8 + 1, 1844674407370955162})\n\ttests = append(tests, test{math.MaxInt/8*5 + 4, math.MaxInt})\n\tfor _, tt := range tests {\n\t\tif got := EncodedLen(tt.n); int64(got) != tt.want {\n\t\t\tt.Errorf(\"EncodedLen(%d): got %d, want %d\", tt.n, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestDecodedLen(t *testing.T) {\n\ttype test struct {\n\t\tn    int\n\t\twant int64\n\t}\n\ttests := []test{\n\t\t{0, 0},\n\t\t{2, 1},\n\t\t{4, 2},\n\t\t{5, 3},\n\t\t{7, 4},\n\t\t{8, 5},\n\t\t{10, 6},\n\t\t{12, 7},\n\t\t{16, 10},\n\t\t{18, 11},\n\t}\n\t// check overflow\n\ttests = append(tests, test{math.MaxInt/5 + 1, 1152921504606846976})\n\ttests = append(tests, test{math.MaxInt, 5764607523034234879})\n\tfor _, tt := range tests {\n\t\tif got := DecodedLen(tt.n); int64(got) != tt.want {\n\t\t\tt.Errorf(\"DecodedLen(%d): got %d, want %d\", tt.n, got, tt.want)\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 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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"QP+CKd6vvg/2UBcQ6qrOlk8MOy3G1NIl4kdRHx8Db4Ba0h3YoCL/KuzwPrQYOdhQpsp+xarCYYckyvBa5emWeA=="}],"memo":""}},{"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"},{"name":"seqid_test.gno","body":"package seqid\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestID(t *testing.T) {\n\tvar i ID\n\n\tfor j := 0; j \u003c 100; j++ {\n\t\ti.Next()\n\t}\n\tif i != 100 {\n\t\tt.Fatalf(\"invalid: wanted %d got %d\", 100, i)\n\t}\n}\n\nfunc TestID_Overflow(t *testing.T) {\n\ti := ID(maxID)\n\n\tdefer func() {\n\t\terr := recover()\n\t\tif !strings.Contains(fmt.Sprint(err), \"next ID overflows\") {\n\t\t\tt.Errorf(\"did not overflow\")\n\t\t}\n\t}()\n\n\ti.Next()\n}\n\nfunc TestID_Binary(cur realm, t *testing.T) {\n\tvar i ID\n\tprev := i.Binary()\n\n\tfor j := 0; j \u003c 1000; j++ {\n\t\tcur := i.Next().Binary()\n\t\tif cur \u003c= prev {\n\t\t\tt.Fatalf(\"cur %x \u003e prev %x\", cur, prev)\n\t\t}\n\t\tprev = cur\n\t}\n}\n\nfunc TestID_String(cur realm, t *testing.T) {\n\tvar i ID\n\tprev := i.String()\n\n\tfor j := 0; j \u003c 1000; j++ {\n\t\tcur := i.Next().String()\n\t\tif cur \u003c= prev {\n\t\t\tt.Fatalf(\"cur %s \u003e prev %s\", cur, prev)\n\t\t}\n\t\tprev = cur\n\t}\n\n\t// Test for when cford32 switches over to the long encoding.\n\ti = 1\u003c\u003c34 - 512\n\tfor j := 0; j \u003c 1024; j++ {\n\t\tcur := i.Next().String()\n\t\t// println(cur)\n\t\tif cur \u003c= prev {\n\t\t\tt.Fatalf(\"cur %s \u003e prev %s\", cur, prev)\n\t\t}\n\t\tprev = cur\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"lcFQXLNJOisKBGtfHzLn+XWRm3EnP/+fNl3hXZFTrTEs5JERgQfdHTIm2hkTphaMokkA85bLQvuXw5D/2A098Q=="}],"memo":""}},{"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"},{"name":"urequire_test.gno","body":"package urequire\n\nimport \"testing\"\n\nfunc TestPackage(t *testing.T) {\n\tEqual(t, 42, 42)\n\n\t// XXX: find a way to unit test this package thoroughly,\n\t// especially the t.FailNow() behavior on assertion failure.\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"8ljsIPKtDfsDxkSZaIiqNYI/MUe2hboplrR+Lb2j04YawU8L09H5v33lIY09PUPVZFCWUfsIUbu43zLwOzGHWg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"grc20","path":"gno.land/p/demo/tokens/grc20","files":[{"name":"caller_teller_sub_realm_filetest.gno","body":"// PKGPATH: gno.land/r/demo/grc20subrealm\n\n// A frame-relative teller must keep working when the token's OWN realm\n// operates under an identity minted by its own cur.Sub(). The sub's synthesized\n// pkgpath is \"\u003chost\u003e#vault\", which is not origRealm verbatim, so a raw string\n// comparison would refuse the token's own realm — a false positive that would\n// break the one property the home binding promises unconditionally.\npackage grc20subrealm\n\nimport (\n\t\"chain\"\n\n\t\"gno.land/p/demo/tokens/grc20\"\n)\n\nvar (\n\ttoken  *grc20.Token\n\tledger *grc20.PrivateLedger\n\tteller grc20.Teller\n)\n\nfunc init(cur realm) {\n\ttoken, ledger = grc20.NewToken(\"SubRealm\", \"SUBR\", 4, 0, cur)\n\tteller = ledger.CallerTeller()\n}\n\nfunc main(cur realm) {\n\tpayer := cur.Previous().Address() // whom the frame-relative teller debits\n\tbob := chain.PackageAddress(\"bob\")\n\tledger.Mint(payer, 1_000)\n\n\t// Control: the primary identity moves the caller's funds.\n\tif err := teller.Transfer(0, cur, bob, 100); err != nil {\n\t\tpanic(\"primary identity rejected: \" + err.Error())\n\t}\n\n\t// Same realm, same teller, under this realm's own \"vault\" sub identity.\n\tif err := teller.Transfer(0, cur.Sub(\"vault\"), bob, 100); err != nil {\n\t\tpanic(\"own sub identity rejected: \" + err.Error())\n\t}\n\n\tif got := token.BalanceOf(bob); got != 200 {\n\t\tpanic(\"unexpected bob balance\")\n\t}\n\n\t// The mirror image: a token CREATED from a sub frame must still be usable\n\t// from its host realm. origRealm drops the subpath at construction, so the\n\t// token belongs to the host rather than being stranded in the sub.\n\tsubTok, subLedger := grc20.NewToken(\"FromSub\", \"FSUB\", 4, 1, cur.Sub(\"vault\"))\n\tsubTeller := subLedger.CallerTeller()\n\tsubLedger.Mint(payer, 500)\n\tif err := subTeller.Transfer(0, cur, bob, 50); err != nil {\n\t\tpanic(\"host realm rejected for a sub-created token: \" + err.Error())\n\t}\n\tif got := subTok.BalanceOf(bob); got != 50 {\n\t\tpanic(\"unexpected bob balance on the sub-created token\")\n\t}\n\n\tprintln(\"ok\")\n}\n\n// Output:\n// ok\n"},{"name":"event_provenance_filetest.gno","body":"// PKGPATH: gno.land/r/demo/grc20provenance\n\n// This filetest is the reference for how an indexer attributes a grc20 event to\n// the realm that issued the token. It is the cross-realm counterpart to\n// newtoken_event_filetest.gno, which covers the within-realm duplicate signal.\n//\n// Two fields matter, and neither is sufficient alone:\n//\n//   - pkg_path is stamped by the VM from the package whose code calls\n//     chain.Emit. Every genuine grc20 event therefore carries\n//     gno.land/p/demo/tokens/grc20 — a constant, so it identifies the library\n//     but never the token.\n//   - the \"token\" attribute carries Token.ID(), whose leading component is\n//     rlm.PkgPath() captured under IsCurrent() in NewToken. A realm cannot\n//     produce a Token whose id claims a different realm.\n//\n// Chained, they are sufficient: pkg_path proves the event came from grc20's\n// code, and grc20's code only ever writes an IsCurrent-verified realm prefix\n// into \"token\". So for any event bearing grc20's pkg_path, the realm prefix in\n// \"token\" is unforgeable.\n//\n// The realm below is an impostor trying to pass its own transfers off as\n// another realm's token, by both routes available to it, and failing at both.\npackage grc20provenance\n\nimport (\n\t\"chain\"\n\n\t\"gno.land/p/demo/tokens/grc20\"\n)\n\n// Stand-in for a token issued and registered by some other realm. Written as a\n// literal rather than imported: a filetest under a /p/ package that imports an\n// /r/ realm which itself imports that /p/ package forms a genesis dependency\n// cycle (grc20 -\u003e realm -\u003e grc20), which breaks package loading chain-wide.\nconst canonical = \"gno.land/r/demo/canonicaltoken.FOO.0000000\"\n\nfunc main(cur realm) {\n\tprintln(\"canonical id:\", canonical)\n\n\t// Route 1: ask grc20 for a token using the canonical token's own\n\t// name/symbol/decimals/id. NewToken derives the id prefix from the live\n\t// crossing frame, so the id names *this* realm. No argument changes that.\n\timpostor, impostorLedger := grc20.NewToken(\"Foo\", \"FOO\", 4, 0, cur)\n\tprintln(\"impostor id: \", impostor.ID())\n\tprintln(\"impostor claims canonical id:\", impostor.ID() == canonical)\n\n\t// A genuine grc20 event from the impostor. It carries grc20's pkg_path —\n\t// identical to the canonical token's events — but the \"token\" prefix is\n\t// this realm, so an indexer attributes it here.\n\timpostorLedger.Mint(cur.Address(), 999_999)\n\n\t// Route 2: skip grc20 and hand-emit an event carrying the canonical id.\n\t// The attributes are fully attacker-chosen, but pkg_path is not: the VM\n\t// stamps this realm. An indexer that accepts Transfer only from grc20's\n\t// pkg_path drops this event.\n\tchain.Emit(\n\t\t\"Transfer\",\n\t\t\"token\", canonical,\n\t\t\"from\", \"\",\n\t\t\"to\", cur.Address().String(),\n\t\t\"value\", \"999999\",\n\t)\n}\n\n// Output:\n// canonical id: gno.land/r/demo/canonicaltoken.FOO.0000000\n// impostor id:  gno.land/r/demo/grc20provenance.FOO.0000000\n// impostor claims canonical id: false\n\n// Events:\n// [\n//   {\n//     \"type\": \"NewToken\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/grc20provenance.FOO.0000000\"\n//       },\n//       {\n//         \"key\": \"name\",\n//         \"value\": \"Foo\"\n//       },\n//       {\n//         \"key\": \"symbol\",\n//         \"value\": \"FOO\"\n//       },\n//       {\n//         \"key\": \"decimals\",\n//         \"value\": \"4\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/p/demo/tokens/grc20\"\n//   },\n//   {\n//     \"type\": \"Transfer\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/grc20provenance.FOO.0000000\"\n//       },\n//       {\n//         \"key\": \"from\",\n//         \"value\": \"\"\n//       },\n//       {\n//         \"key\": \"to\",\n//         \"value\": \"g1vz4y807zq7p3s63dmyng9g80l58nmuc3lgmfjs\"\n//       },\n//       {\n//         \"key\": \"value\",\n//         \"value\": \"999999\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/p/demo/tokens/grc20\"\n//   },\n//   {\n//     \"type\": \"Transfer\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/canonicaltoken.FOO.0000000\"\n//       },\n//       {\n//         \"key\": \"from\",\n//         \"value\": \"\"\n//       },\n//       {\n//         \"key\": \"to\",\n//         \"value\": \"g1vz4y807zq7p3s63dmyng9g80l58nmuc3lgmfjs\"\n//       },\n//       {\n//         \"key\": \"value\",\n//         \"value\": \"999999\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/r/demo/grc20provenance\"\n//   }\n// ]\n"},{"name":"examples_test.gno","body":"package grc20\n\n// XXX: write Examples\n\nfunc ExampleInit()                            {}\nfunc ExampleExposeBankForMaketxRunOrImports() {}\nfunc ExampleCustomTellerImpl()                {}\nfunc ExampleAllowance()                       {}\nfunc ExampleRealmBanker()                     {}\nfunc ExamplePreviousRealmBanker()             {}\nfunc ExampleAccountBanker()                   {}\nfunc ExampleTransfer()                        {}\nfunc ExampleApprove()                         {}\nfunc ExampleTransferFrom()                    {}\nfunc ExampleMint()                            {}\nfunc ExampleBurn()                            {}\n\n// ...\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/tokens/grc20\"\ngno = \"0.9\"\n"},{"name":"mock.gno","body":"package grc20\n\n// XXX: func Mock(t *Token)\n"},{"name":"newtoken_event_filetest.gno","body":"// PKGPATH: gno.land/r/demo/grc20dupsignal\n\n// This filetest is the reference for the detection rule the NewToken event\n// enables. The realm below reuses seqid 0 twice, so both tokens end up with the\n// same Token.ID() and their Transfer events are indistinguishable — the\n// long-standing event-provenance ambiguity.\n//\n// What changes is that the ambiguity is now *announced*. Two NewToken events\n// carry the same \"token\" value, which is a complete signal: NewToken is the only\n// way a Token can exist (Token's fields are unexported), so an indexer watching\n// this event sees every token that will ever emit. On the second duplicate\n// announcement it should flag the realm and stop trusting its token events.\npackage grc20dupsignal\n\nimport (\n\t\"gno.land/p/demo/tokens/grc20\"\n)\n\nfunc main(cur realm) {\n\tfirst, firstLedger := grc20.NewToken(\"Same\", \"DUP\", 6, 0, cur)\n\tsecond, secondLedger := grc20.NewToken(\"Same\", \"DUP\", 6, 0, cur)\n\n\tprintln(\"same id:\", first.ID() == second.ID())\n\n\t// Two independent ledgers, one identifier: these Transfers cannot be\n\t// attributed to either object from the event stream alone.\n\tfirstLedger.Mint(cur.Address(), 1)\n\tsecondLedger.Mint(cur.Address(), 999999)\n}\n\n// Output:\n// same id: true\n\n// Events:\n// [\n//   {\n//     \"type\": \"NewToken\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/grc20dupsignal.DUP.0000000\"\n//       },\n//       {\n//         \"key\": \"name\",\n//         \"value\": \"Same\"\n//       },\n//       {\n//         \"key\": \"symbol\",\n//         \"value\": \"DUP\"\n//       },\n//       {\n//         \"key\": \"decimals\",\n//         \"value\": \"6\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/p/demo/tokens/grc20\"\n//   },\n//   {\n//     \"type\": \"NewToken\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/grc20dupsignal.DUP.0000000\"\n//       },\n//       {\n//         \"key\": \"name\",\n//         \"value\": \"Same\"\n//       },\n//       {\n//         \"key\": \"symbol\",\n//         \"value\": \"DUP\"\n//       },\n//       {\n//         \"key\": \"decimals\",\n//         \"value\": \"6\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/p/demo/tokens/grc20\"\n//   },\n//   {\n//     \"type\": \"Transfer\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/grc20dupsignal.DUP.0000000\"\n//       },\n//       {\n//         \"key\": \"from\",\n//         \"value\": \"\"\n//       },\n//       {\n//         \"key\": \"to\",\n//         \"value\": \"g1k29lxz0d8gx7m94n032ulum875p7gg0kduus5m\"\n//       },\n//       {\n//         \"key\": \"value\",\n//         \"value\": \"1\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/p/demo/tokens/grc20\"\n//   },\n//   {\n//     \"type\": \"Transfer\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/grc20dupsignal.DUP.0000000\"\n//       },\n//       {\n//         \"key\": \"from\",\n//         \"value\": \"\"\n//       },\n//       {\n//         \"key\": \"to\",\n//         \"value\": \"g1k29lxz0d8gx7m94n032ulum875p7gg0kduus5m\"\n//       },\n//       {\n//         \"key\": \"value\",\n//         \"value\": \"999999\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/p/demo/tokens/grc20\"\n//   }\n// ]\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":"tellers_test.gno","body":"package grc20\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/ufmt/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc TestCallerTellerImpl(cur realm, t *testing.T) {\n\ttok, ledger := newTestToken(\"Dummy\", \"DUMMY\", 4, 0, cur)\n\tteller := ledger.CallerTeller()\n\turequire.False(t, tok == nil)\n\tvar _ Teller = teller\n}\n\n// The sub-realm case (guardHome must not lock out the token's own realm when it\n// operates under an identity minted by its own cur.Sub()) needs a real realm\n// frame, since cur.Sub() refuses to mint from a p/ package. It lives in\n// filetests/caller_teller_sub_realm_filetest.gno.\n\n// evilWrap embeds Teller; the seal-marker pattern (if we had one) would be\n// satisfied via promotion, but IsCanonicalTeller rejects it because *evilWrap\n// is nominally distinct from *fnTeller.\ntype evilWrap struct {\n\tTeller\n}\n\nfunc TestIsCanonicalTeller(cur realm, t *testing.T) {\n\t_, ledger := newTestToken(\"Dummy\", \"DUMMY\", 4, 0, cur)\n\tlegit := ledger.CallerTeller()\n\n\tuassert.True(t, IsCanonicalTeller(legit),\n\t\t\"canonical *fnTeller from CallerTeller must pass\")\n\n\tevil := \u0026evilWrap{Teller: legit}\n\tuassert.False(t, IsCanonicalTeller(evil),\n\t\t\"foreign type embedding a canonical Teller must be rejected\")\n}\n\nfunc TestTeller(cur realm, t *testing.T) {\n\tvar (\n\t\talice = testutils.TestAddress(\"alice\")\n\t\tbob   = testutils.TestAddress(\"bob\")\n\t\tcarl  = testutils.TestAddress(\"carl\")\n\t)\n\n\ttoken, ledger := newTestToken(\"Dummy\", \"DUMMY\", 6, 0, cur)\n\n\tcheckBalances := func(aliceEB, bobEB, carlEB int64) {\n\t\tt.Helper()\n\t\texp := ufmt.Sprintf(\"alice=%d bob=%d carl=%d\", aliceEB, bobEB, carlEB)\n\t\taliceGB := token.BalanceOf(alice)\n\t\tbobGB := token.BalanceOf(bob)\n\t\tcarlGB := token.BalanceOf(carl)\n\t\tgot := ufmt.Sprintf(\"alice=%d bob=%d carl=%d\", aliceGB, bobGB, carlGB)\n\t\tuassert.Equal(t, got, exp, \"invalid balances\")\n\t}\n\tcheckAllowances := func(abEB, acEB, baEB, bcEB, caEB, cbEB int64) {\n\t\tt.Helper()\n\t\texp := ufmt.Sprintf(\"ab=%d ac=%d ba=%d bc=%d ca=%d cb=%s\", abEB, acEB, baEB, bcEB, caEB, cbEB)\n\t\tabGB := token.Allowance(alice, bob)\n\t\tacGB := token.Allowance(alice, carl)\n\t\tbaGB := token.Allowance(bob, alice)\n\t\tbcGB := token.Allowance(bob, carl)\n\t\tcaGB := token.Allowance(carl, alice)\n\t\tcbGB := token.Allowance(carl, bob)\n\t\tgot := ufmt.Sprintf(\"ab=%d ac=%d ba=%d bc=%d ca=%d cb=%s\", abGB, acGB, baGB, bcGB, caGB, cbGB)\n\t\tuassert.Equal(t, got, exp, \"invalid allowances\")\n\t}\n\n\tcheckBalances(0, 0, 0)\n\tcheckAllowances(0, 0, 0, 0, 0, 0)\n\n\turequire.NoError(t, ledger.Mint(alice, 1000))\n\turequire.NoError(t, ledger.Mint(alice, 100))\n\tcheckBalances(1100, 0, 0)\n\tcheckAllowances(0, 0, 0, 0, 0, 0)\n\n\turequire.NoError(t, ledger.Approve(alice, bob, 99999999))\n\tcheckBalances(1100, 0, 0)\n\tcheckAllowances(99999999, 0, 0, 0, 0, 0)\n\n\turequire.NoError(t, ledger.Approve(alice, bob, 400))\n\tcheckBalances(1100, 0, 0)\n\tcheckAllowances(400, 0, 0, 0, 0, 0)\n\n\turequire.Error(t, ledger.TransferFrom(alice, bob, carl, 100000000))\n\tcheckBalances(1100, 0, 0)\n\tcheckAllowances(400, 0, 0, 0, 0, 0)\n\n\turequire.NoError(t, ledger.TransferFrom(alice, bob, carl, 100))\n\tcheckBalances(1000, 0, 100)\n\tcheckAllowances(300, 0, 0, 0, 0, 0)\n\n\turequire.Error(t, ledger.SpendAllowance(alice, bob, 2000000))\n\tcheckBalances(1000, 0, 100)\n\tcheckAllowances(300, 0, 0, 0, 0, 0)\n\n\turequire.NoError(t, ledger.SpendAllowance(alice, bob, 100))\n\tcheckBalances(1000, 0, 100)\n\tcheckAllowances(200, 0, 0, 0, 0, 0)\n}\n\nfunc TestCallerTeller(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\tcarl := testutils.TestAddress(\"carl\")\n\n\ttoken, ledger := newTestToken(\"Dummy\", \"DUMMY\", 6, 0, cur)\n\tteller := ledger.CallerTeller()\n\n\tcheckBalances := func(aliceEB, bobEB, carlEB int64) {\n\t\tt.Helper()\n\t\texp := ufmt.Sprintf(\"alice=%d bob=%d carl=%d\", aliceEB, bobEB, carlEB)\n\t\taliceGB := token.BalanceOf(alice)\n\t\tbobGB := token.BalanceOf(bob)\n\t\tcarlGB := token.BalanceOf(carl)\n\t\tgot := ufmt.Sprintf(\"alice=%d bob=%d carl=%d\", aliceGB, bobGB, carlGB)\n\t\tuassert.Equal(t, got, exp, \"invalid balances\")\n\t}\n\tcheckAllowances := func(abEB, acEB, baEB, bcEB, caEB, cbEB int64) {\n\t\tt.Helper()\n\t\texp := ufmt.Sprintf(\"ab=%d ac=%d ba=%d bc=%d ca=%d cb=%s\", abEB, acEB, baEB, bcEB, caEB, cbEB)\n\t\tabGB := token.Allowance(alice, bob)\n\t\tacGB := token.Allowance(alice, carl)\n\t\tbaGB := token.Allowance(bob, alice)\n\t\tbcGB := token.Allowance(bob, carl)\n\t\tcaGB := token.Allowance(carl, alice)\n\t\tcbGB := token.Allowance(carl, bob)\n\t\tgot := ufmt.Sprintf(\"ab=%d ac=%d ba=%d bc=%d ca=%d cb=%s\", abGB, acGB, baGB, bcGB, caGB, cbGB)\n\t\tuassert.Equal(t, got, exp, \"invalid allowances\")\n\t}\n\n\turequire.NoError(t, ledger.Mint(alice, 1000))\n\tcheckBalances(1000, 0, 0)\n\tcheckAllowances(0, 0, 0, 0, 0, 0)\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tfunc(cur realm) { urequire.NoError(t, teller.Approve(0, cur, bob, 600)) }(cross(cur))\n\tcheckBalances(1000, 0, 0)\n\tcheckAllowances(600, 0, 0, 0, 0, 0)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tfunc(cur realm) { urequire.Error(t, teller.TransferFrom(0, cur, alice, carl, 700)) }(cross(cur))\n\tcheckBalances(1000, 0, 0)\n\tcheckAllowances(600, 0, 0, 0, 0, 0)\n\tfunc(cur realm) { urequire.NoError(t, teller.TransferFrom(0, cur, alice, carl, 400)) }(cross(cur))\n\tcheckBalances(600, 0, 400)\n\tcheckAllowances(200, 0, 0, 0, 0, 0)\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 — becomes the Token's\n// origRealm. Token.ID() returns origRealm + \".\" + 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 Token.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 original realm, 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 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":"token_identity_filetest.gno","body":"// PKGPATH: gno.land/r/demo/grc20identity\n\npackage grc20identity\n\nimport (\n\t\"chain\"\n\n\t\"gno.land/p/demo/tokens/grc20\"\n\t\"gno.land/p/nt/seqid/v0\"\n)\n\nvar nextTokenID seqid.ID\n\nfunc main(cur realm) {\n\tfirst, firstLedger := newToken(cur)\n\tsecond, secondLedger := newToken(cur)\n\n\tif first.ID() != \"gno.land/r/demo/grc20identity.DUP.0000001\" {\n\t\tpanic(\"unexpected first token ID: \" + first.ID())\n\t}\n\tif second.ID() != \"gno.land/r/demo/grc20identity.DUP.0000002\" {\n\t\tpanic(\"unexpected second token ID: \" + second.ID())\n\t}\n\n\tholder := chain.PackageAddress(\"holder\")\n\tspender := chain.PackageAddress(\"spender\")\n\tfirstLedger.Mint(holder, 1)\n\tfirstLedger.Approve(holder, spender, 1)\n\tsecondLedger.Mint(holder, 2)\n\tsecondLedger.Approve(holder, spender, 2)\n}\n\nfunc newToken(cur realm) (*grc20.Token, *grc20.PrivateLedger) {\n\treturn grc20.NewToken(\"Same\", \"DUP\", 6, nextTokenID.Next(), cur)\n}\n\n// Events:\n// [\n//   {\n//     \"type\": \"NewToken\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/grc20identity.DUP.0000001\"\n//       },\n//       {\n//         \"key\": \"name\",\n//         \"value\": \"Same\"\n//       },\n//       {\n//         \"key\": \"symbol\",\n//         \"value\": \"DUP\"\n//       },\n//       {\n//         \"key\": \"decimals\",\n//         \"value\": \"6\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/p/demo/tokens/grc20\"\n//   },\n//   {\n//     \"type\": \"NewToken\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/grc20identity.DUP.0000002\"\n//       },\n//       {\n//         \"key\": \"name\",\n//         \"value\": \"Same\"\n//       },\n//       {\n//         \"key\": \"symbol\",\n//         \"value\": \"DUP\"\n//       },\n//       {\n//         \"key\": \"decimals\",\n//         \"value\": \"6\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/p/demo/tokens/grc20\"\n//   },\n//   {\n//     \"type\": \"Transfer\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/grc20identity.DUP.0000001\"\n//       },\n//       {\n//         \"key\": \"from\",\n//         \"value\": \"\"\n//       },\n//       {\n//         \"key\": \"to\",\n//         \"value\": \"g18rwjsdf0kcy673ta0q4ujwvsncz4k2a8gcv94t\"\n//       },\n//       {\n//         \"key\": \"value\",\n//         \"value\": \"1\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/p/demo/tokens/grc20\"\n//   },\n//   {\n//     \"type\": \"Approval\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/grc20identity.DUP.0000001\"\n//       },\n//       {\n//         \"key\": \"owner\",\n//         \"value\": \"g18rwjsdf0kcy673ta0q4ujwvsncz4k2a8gcv94t\"\n//       },\n//       {\n//         \"key\": \"spender\",\n//         \"value\": \"g148tp8xkvvk3l73lmxywpdlsxgdujjlclx7wfyg\"\n//       },\n//       {\n//         \"key\": \"value\",\n//         \"value\": \"1\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/p/demo/tokens/grc20\"\n//   },\n//   {\n//     \"type\": \"Transfer\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/grc20identity.DUP.0000002\"\n//       },\n//       {\n//         \"key\": \"from\",\n//         \"value\": \"\"\n//       },\n//       {\n//         \"key\": \"to\",\n//         \"value\": \"g18rwjsdf0kcy673ta0q4ujwvsncz4k2a8gcv94t\"\n//       },\n//       {\n//         \"key\": \"value\",\n//         \"value\": \"2\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/p/demo/tokens/grc20\"\n//   },\n//   {\n//     \"type\": \"Approval\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/grc20identity.DUP.0000002\"\n//       },\n//       {\n//         \"key\": \"owner\",\n//         \"value\": \"g18rwjsdf0kcy673ta0q4ujwvsncz4k2a8gcv94t\"\n//       },\n//       {\n//         \"key\": \"spender\",\n//         \"value\": \"g148tp8xkvvk3l73lmxywpdlsxgdujjlclx7wfyg\"\n//       },\n//       {\n//         \"key\": \"value\",\n//         \"value\": \"2\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/p/demo/tokens/grc20\"\n//   }\n// ]\n"},{"name":"token_test.gno","body":"package grc20\n\nimport (\n\t\"errors\"\n\t\"math\"\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/ufmt/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\n// newTestToken constructs a Token. The IIFE same-realm cross\n// promotes the test's EOA-origin cur into a fresh /p/grc20\n// CodeRealm cur so NewToken's IsCurrent + non-empty rlm.PkgPath()\n// checks pass.\nfunc newTestToken(name, symbol string, decimals int, id seqid.ID, rlm realm) (tok *Token, adm *PrivateLedger) {\n\tfunc(cur realm) {\n\t\ttok, adm = NewToken(name, symbol, decimals, id, cur)\n\t}(cross(rlm))\n\treturn\n}\n\nfunc TestTestImpl(cur realm, t *testing.T) {\n\tbank, _ := newTestToken(\"Dummy\", \"DUMMY\", 4, 0, cur)\n\turequire.False(t, bank == nil, \"dummy should not be nil\")\n}\n\nfunc TestNewTokenAllowsDuplicateSymbolInSameRealm(cur realm, t *testing.T) {\n\tholder := testutils.TestAddress(\"holder\")\n\n\tfirst, firstLedger := newTestToken(\"Same\", \"DUP\", 6, 1, cur)\n\tsecond, secondLedger := newTestToken(\"Same\", \"DUP\", 6, 2, cur)\n\n\turequire.True(t, first.ID() != second.ID(), \"duplicate symbols should not force duplicate IDs\")\n\n\turequire.NoError(t, firstLedger.Mint(holder, 11))\n\turequire.NoError(t, secondLedger.Mint(holder, 22))\n\turequire.Equal(t, int64(11), first.BalanceOf(holder))\n\turequire.Equal(t, int64(22), second.BalanceOf(holder))\n}\n\nfunc TestNewTokenValidation(cur realm, t *testing.T) {\n\t// Wrap NewToken to satisfy IsCurrent and pkgPath requirements,\n\t// then validate name, symbol, and decimals.\n\tmustPanic := func(name, sym string, dec int, want error, label string) {\n\t\tt.Helper()\n\t\t// newTestToken wraps NewToken in cross(...), so the panic from\n\t\t// NewToken's validators crosses a realm boundary — use revive()\n\t\t// (defer-recover doesn't see cross-realm panics).\n\t\tr := revive(func() {\n\t\t\tnewTestToken(name, sym, dec, 0, cur)\n\t\t})\n\t\tif r == nil {\n\t\t\tt.Errorf(\"%s: expected panic, got none\", label)\n\t\t\treturn\n\t\t}\n\t\tif r != want {\n\t\t\tt.Errorf(\"%s: expected %v, got %v\", label, want, r)\n\t\t}\n\t}\n\n\t// Empty name / symbol.\n\tmustPanic(\"\", \"OK\", 4, ErrInvalidName, \"empty name\")\n\tmustPanic(\"Name\", \"\", 4, ErrInvalidSymbol, \"empty symbol\")\n\n\t// Length caps.\n\tmustPanic(strings.Repeat(\"a\", MaxNameLen+1), \"OK\", 4, ErrInvalidName, \"name too long\")\n\tmustPanic(\"Name\", strings.Repeat(\"A\", MaxSymbolLen+1), 4, ErrInvalidSymbol, \"symbol too long\")\n\n\t// Name control characters.\n\tmustPanic(\"bad\\x01name\", \"OK\", 4, ErrInvalidName, \"name with control char\")\n\tmustPanic(\"bad\\nname\", \"OK\", 4, ErrInvalidName, \"name with newline\")\n\n\t// Symbol charset — disallowed delimiters and whitespace.\n\tmustPanic(\"Name\", \"BA.D\", 4, ErrInvalidSymbol, \"symbol with dot\")\n\tmustPanic(\"Name\", \"BA/D\", 4, ErrInvalidSymbol, \"symbol with slash\")\n\tmustPanic(\"Name\", \"BA D\", 4, ErrInvalidSymbol, \"symbol with space\")\n\tmustPanic(\"Name\", \"BA\\\"D\", 4, ErrInvalidSymbol, \"symbol with quote\")\n\n\t// Decimals out of range.\n\tmustPanic(\"Name\", \"OK\", -1, ErrInvalidDecimals, \"negative decimals\")\n\tmustPanic(\"Name\", \"OK\", MaxDecimals+1, ErrInvalidDecimals, \"decimals over cap\")\n\n\t// Boundary positives — should NOT panic.\n\ttok, _ := newTestToken(strings.Repeat(\"a\", MaxNameLen), strings.Repeat(\"A\", MaxSymbolLen), MaxDecimals, 0, cur)\n\turequire.True(t, tok != nil, \"boundary name+symbol+decimals should succeed\")\n\n\t// UTF-8 name with non-ASCII is allowed.\n\ttok2, _ := newTestToken(\"Доллар\", \"RUB\", 2, 0, cur)\n\turequire.True(t, tok2 != nil, \"UTF-8 name should be allowed\")\n}\n\nfunc TestToken(cur realm, t *testing.T) {\n\tvar (\n\t\talice = testutils.TestAddress(\"alice\")\n\t\tbob   = testutils.TestAddress(\"bob\")\n\t\tcarl  = testutils.TestAddress(\"carl\")\n\t)\n\n\tbank, adm := newTestToken(\"Dummy\", \"DUMMY\", 6, 0, cur)\n\n\tcheckBalances := func(aliceEB, bobEB, carlEB int64) {\n\t\tt.Helper()\n\t\texp := ufmt.Sprintf(\"alice=%d bob=%d carl=%d\", aliceEB, bobEB, carlEB)\n\t\taliceGB := bank.BalanceOf(alice)\n\t\tbobGB := bank.BalanceOf(bob)\n\t\tcarlGB := bank.BalanceOf(carl)\n\t\tgot := ufmt.Sprintf(\"alice=%d bob=%d carl=%d\", aliceGB, bobGB, carlGB)\n\t\tuassert.Equal(t, got, exp, \"invalid balances\")\n\t}\n\tcheckAllowances := func(abEB, acEB, baEB, bcEB, caEB, cbEB int64) {\n\t\tt.Helper()\n\t\texp := ufmt.Sprintf(\"ab=%d ac=%d ba=%d bc=%d ca=%d cb=%s\", abEB, acEB, baEB, bcEB, caEB, cbEB)\n\t\tabGB := bank.Allowance(alice, bob)\n\t\tacGB := bank.Allowance(alice, carl)\n\t\tbaGB := bank.Allowance(bob, alice)\n\t\tbcGB := bank.Allowance(bob, carl)\n\t\tcaGB := bank.Allowance(carl, alice)\n\t\tcbGB := bank.Allowance(carl, bob)\n\t\tgot := ufmt.Sprintf(\"ab=%d ac=%d ba=%d bc=%d ca=%d cb=%s\", abGB, acGB, baGB, bcGB, caGB, cbGB)\n\t\tuassert.Equal(t, got, exp, \"invalid allowances\")\n\t}\n\n\tcheckBalances(0, 0, 0)\n\tcheckAllowances(0, 0, 0, 0, 0, 0)\n\n\turequire.NoError(t, adm.Mint(alice, 1000))\n\turequire.NoError(t, adm.Mint(alice, 100))\n\tcheckBalances(1100, 0, 0)\n\tcheckAllowances(0, 0, 0, 0, 0, 0)\n\n\turequire.NoError(t, adm.Approve(alice, bob, 99999999))\n\tcheckBalances(1100, 0, 0)\n\tcheckAllowances(99999999, 0, 0, 0, 0, 0)\n\n\turequire.NoError(t, adm.Approve(alice, bob, 400))\n\tcheckBalances(1100, 0, 0)\n\tcheckAllowances(400, 0, 0, 0, 0, 0)\n\n\turequire.Error(t, adm.TransferFrom(alice, bob, carl, 100000000))\n\tcheckBalances(1100, 0, 0)\n\tcheckAllowances(400, 0, 0, 0, 0, 0)\n\n\turequire.NoError(t, adm.TransferFrom(alice, bob, carl, 100))\n\tcheckBalances(1000, 0, 100)\n\tcheckAllowances(300, 0, 0, 0, 0, 0)\n\n\turequire.Error(t, adm.SpendAllowance(alice, bob, 2000000))\n\tcheckBalances(1000, 0, 100)\n\tcheckAllowances(300, 0, 0, 0, 0, 0)\n\n\turequire.NoError(t, adm.SpendAllowance(alice, bob, 100))\n\tcheckBalances(1000, 0, 100)\n\tcheckAllowances(200, 0, 0, 0, 0, 0)\n}\n\nfunc TestMintOverflow(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\ttok, adm := newTestToken(\"Dummy\", \"DUMMY\", 6, 0, cur)\n\n\tsafeValue := int64(1 \u003c\u003c 62)\n\turequire.NoError(t, adm.Mint(alice, safeValue))\n\turequire.Equal(t, tok.BalanceOf(alice), safeValue)\n\n\terr := adm.Mint(bob, safeValue)\n\tuassert.Error(t, err, \"expected ErrMintOverflow\")\n}\n\nfunc TestTransferFromAtomicity(cur realm, t *testing.T) {\n\tvar (\n\t\towner   = testutils.TestAddress(\"owner\")\n\t\tspender = testutils.TestAddress(\"spender\")\n\n\t\tinvalidRecipient = address(\"\")\n\t\trecipient        = testutils.TestAddress(\"to\")\n\t)\n\n\ttoken, admin := newTestToken(\"Test\", \"TEST\", 6, 0, cur)\n\n\t// owner has 100 tokens, spender has 50 allowance\n\tinitialBalance := int64(100)\n\tinitialAllowance := int64(50)\n\n\turequire.NoError(t, admin.Mint(owner, initialBalance))\n\turequire.NoError(t, admin.Approve(owner, spender, initialAllowance))\n\n\t// transfer to an invalid address to force a transfer failure\n\ttransferAmount := int64(30)\n\terr := admin.TransferFrom(owner, spender, invalidRecipient, transferAmount)\n\tuassert.Error(t, err, \"transfer should fail due to invalid address\")\n\n\townerBalance := token.BalanceOf(owner)\n\tuassert.Equal(t, ownerBalance, initialBalance, \"owner balance should remain unchanged\")\n\n\t// check if allowance was incorrectly reduced\n\tremainingAllowance := token.Allowance(owner, spender)\n\tuassert.Equal(t, remainingAllowance, initialAllowance,\n\t\t\"allowance should not be reduced when transfer fails\")\n\n\t// transfer all tokens\n\tadmin.Transfer(owner, recipient, 100)\n\tremainingBalance := token.BalanceOf(owner)\n\tuassert.Equal(t, remainingBalance, int64(0),\n\t\t\"balance should be zero\")\n\n\terr = admin.TransferFrom(owner, spender, recipient, transferAmount)\n\tuassert.Error(t, err, \"transfer should fail due to insufficient balance\")\n}\n\nfunc TestMintUntilOverflow(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\ttok, adm := newTestToken(\"Dummy\", \"DUMMY\", 6, 0, cur)\n\n\ttests := []struct {\n\t\tname           string\n\t\taddr           address\n\t\tamount         int64\n\t\texpectedError  error\n\t\texpectedSupply int64\n\t\tdescription    string\n\t}{\n\t\t{\n\t\t\tname:           \"mint negative value\",\n\t\t\taddr:           alice,\n\t\t\tamount:         -1,\n\t\t\texpectedError:  ErrInvalidAmount,\n\t\t\texpectedSupply: 0,\n\t\t\tdescription:    \"minting a negative number should fail with ErrInvalidAmount\",\n\t\t},\n\t\t{\n\t\t\tname:           \"mint MaxInt64\",\n\t\t\taddr:           alice,\n\t\t\tamount:         math.MaxInt64 - 1000,\n\t\t\texpectedError:  nil,\n\t\t\texpectedSupply: math.MaxInt64 - 1000,\n\t\t\tdescription:    \"minting almost MaxInt64 should succeed\",\n\t\t},\n\t\t{\n\t\t\tname:           \"mint small value\",\n\t\t\taddr:           bob,\n\t\t\tamount:         1000,\n\t\t\texpectedError:  nil,\n\t\t\texpectedSupply: math.MaxInt64,\n\t\t\tdescription:    \"minting a small value when close to MaxInt64 should succeed\",\n\t\t},\n\t\t{\n\t\t\tname:           \"mint value that would exceed MaxInt64\",\n\t\t\taddr:           bob,\n\t\t\tamount:         1,\n\t\t\texpectedError:  ErrMintOverflow,\n\t\t\texpectedSupply: math.MaxInt64,\n\t\t\tdescription:    \"minting any value when at MaxInt64 should fail with ErrMintOverflow\",\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 := adm.Mint(tt.addr, tt.amount)\n\n\t\t\tif tt.expectedError != nil {\n\t\t\t\tuassert.Error(t, err, tt.description)\n\t\t\t\tif !errors.Is(err, tt.expectedError) {\n\t\t\t\t\tt.Errorf(\"expected error %v, got %v\", tt.expectedError, err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tuassert.NoError(t, err, tt.description)\n\t\t\t}\n\n\t\t\ttotalSupply := tok.TotalSupply()\n\t\t\tuassert.Equal(t, totalSupply, tt.expectedSupply, \"totalSupply should match expected value\")\n\t\t})\n\t}\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"BNg23sfs/sdgnFHH8QlCKUd/57EJ5hqJgBK9S+ZbHG10EiDsOW8wBFCLVR2zRUjMsM9scdlHPc8kThnFFVFBIw=="}],"memo":""}},{"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"},{"name":"sanitize_test.gno","body":"package sanitize\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestStripBidiAndZeroWidthRe(t *testing.T) {\n\t// Re-export sanity check.\n\tif got := StripBidiAndZeroWidth(\"a\\u200Bb\"); got != \"ab\" {\n\t\tt.Errorf(\"re-export StripBidiAndZeroWidth failed: got %q\", got)\n\t}\n}\n\nfunc TestNormalizeBreaksRe(t *testing.T) {\n\tif got := NormalizeBreaks(\"a\\r\\nb\"); got != \"a\\nb\" {\n\t\tt.Errorf(\"re-export NormalizeBreaks failed: got %q\", got)\n\t}\n}\n\nfunc TestInlineText(t *testing.T) {\n\tcases := []struct{ in, want string }{\n\t\t{\"plain\", \"plain\"},\n\t\t{\"a*b\", `a\\*b`},\n\t\t{\"a|b\", \"a|b\"},                    // | NOT escaped\n\t\t{\"a=b\", \"a=b\"},                    // = NOT escaped\n\t\t{\"line1\\nline2\", \"line1 line2\"},   // newline folded\n\t\t{\"line1\\r\\nline2\", \"line1 line2\"}, // CRLF normalized then folded\n\t\t{\"a\\u2028b\", \"a b\"},               // U+2028 folded\n\t\t{\"a\\u0085b\", \"a b\"},               // NEL folded\n\t\t{\"a\\u200Bb\", \"ab\"},                // ZWSP stripped\n\t\t{\"hello *world*\", `hello \\*world\\*`},\n\t}\n\tfor _, c := range cases {\n\t\tif got := InlineText(c.in); got != c.want {\n\t\t\tt.Errorf(\"InlineText(%q) = %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestBlock(t *testing.T) {\n\t// Block wraps every non-empty output with \"\\n\\n\" — CM §4.8 blank\n\t// lines — on BOTH sides, so user content is paragraph-isolated\n\t// from any realm chrome that precedes OR follows it. Bounds CM\n\t// §4.6 HTML block types 6/7 (`\u003cdiv\u003e`, `\u003ctable\u003e`, …) which are not\n\t// escaped in any mode and would otherwise consume appended chrome.\n\tcases := []struct{ in, want string }{\n\t\t{\"hello world\\n\", \"\\n\\nhello world\\n\\n\"},\n\t\t{\"# heading\\n\", \"\\n\\n\\\\# heading\\n\\n\"},\n\t\t{\"\u003e quote\\n\", \"\\n\\n\\\\\u003e quote\\n\\n\"},\n\t\t{\"| a | b |\\n\", \"\\n\\n\\\\| a | b |\\n\\n\"}, // GFM table-row escaped in strict mode\n\t\t// CM §4.6 HTML block types 1-5 — escaped (blank-line-NON-terminating).\n\t\t{\"\u003cscript\u003ex\u003c/script\u003e\\n\", \"\\n\\n\\\\\u003cscript\u003ex\u003c/script\u003e\\n\\n\"},\n\t\t{\"\u003c!-- comment --\u003e\\n\", \"\\n\\n\\\\\u003c!-- comment --\u003e\\n\\n\"},\n\t\t{\"\u003c?php x ?\u003e\\n\", \"\\n\\n\\\\\u003c?php x ?\u003e\\n\\n\"},\n\t\t{\"\u003c!DOCTYPE html\u003e\\n\", \"\\n\\n\\\\\u003c!DOCTYPE html\u003e\\n\\n\"},\n\t\t{\"```\\ncode\\n\", \"\\n\\n```\\ncode\\n```\\n\\n\"}, // fence auto-close at EOF\n\t\t{\"[x](\u0026#x6a;avascript:alert)\\n\", \"\\n\\n[x](%26#x6a;avascript:alert)\\n\\n\"},\n\t\t{\"[x](\u0026#0000152;avascript:alert)\\n\", \"\\n\\n[x](%26#0000152;avascript:alert)\\n\\n\"}, // octal reference\n\t\t// A renderer unescapes `\\#` before resolving references, so this\n\t\t// reaches it as `\u0026#x6a;` unless the `\u0026` is encoded here.\n\t\t{\"[x](\u0026\\\\#x6a;avascript:alert)\\n\", \"\\n\\n[x](%26\\\\#x6a;avascript:alert)\\n\\n\"},\n\t\t// A renderer resolves numeric references before named ones, over\n\t\t// the same buffer, so `\u0026#38;colon;` reaches the named pass as\n\t\t// `\u0026colon;` and resolves to `:`.\n\t\t{\"[x](javascript\u0026#38;colon;alert)\\n\", \"\\n\\n[x](javascript%26#38;colon;alert)\\n\\n\"},\n\t\t{\"[x](?x=1\u0026y=2)\\n\", \"\\n\\n[x](?x=1\u0026y=2)\\n\\n\"},\n\t\t// Empty / strip-to-empty inputs short-circuit (no stray blank line).\n\t\t{\"[x]: y\\n\", \"\"},\n\t\t{\"\", \"\"},\n\t}\n\tfor _, c := range cases {\n\t\tgot := Block(c.in)\n\t\tif got != c.want {\n\t\t\tt.Errorf(\"Block(%q) = %q, want %q\", c.in, got, c.want)\n\t\t}\n\t\t// Idempotency: Block(Block(in)) must be byte-identical to\n\t\t// Block(in) for every input in the table.\n\t\ttwice := Block(got)\n\t\tif twice != got {\n\t\t\tt.Errorf(\"Block not idempotent for %q: Block(once)=%q, Block(twice)=%q\", c.in, got, twice)\n\t\t}\n\t}\n}\n\nfunc TestBlockRich(t *testing.T) {\n\t// BlockRich wraps every non-empty output with \"\\n\\n\" — CM §4.8\n\t// blank lines — on BOTH sides, so user content is paragraph-\n\t// isolated from any realm chrome that precedes OR follows it.\n\tcases := []struct{ in, want string }{\n\t\t// Block-level markdown that Block escapes — preserved by BlockRich.\n\t\t{\"hello world\\n\", \"\\n\\nhello world\\n\\n\"},\n\t\t{\"# heading\\n\", \"\\n\\n# heading\\n\\n\"},\n\t\t{\"\u003e quote\\n\", \"\\n\\n\u003e quote\\n\\n\"},\n\t\t{\"- item\\n\", \"\\n\\n- item\\n\\n\"},\n\t\t{\"1. item\\n\", \"\\n\\n1. item\\n\\n\"},\n\t\t{\"---\\n\", \"\\n\\n\\\\---\\n\\n\"},                       // first-line setext-h2 → escaped by qualifying-setext pre-pass\n\t\t{\"***\\n\", \"\\n\\n***\\n\\n\"},                         // thematic break NOT setext-h2 — preserved\n\t\t{\"text\\n===\\n\", \"\\n\\ntext\\n===\\n\\n\"},             // deeper setext preserved (user-authored above)\n\t\t{\"body\\n===\\nmore\\n\", \"\\n\\nbody\\n===\\nmore\\n\\n\"}, // cross-paragraph backward attack: realm `chrome\\n\\nbody\\n===\\nmore` keeps realm in its own paragraph\n\t\t// GFM tables PRESERVED in Rich mode.\n\t\t{\"| a | b |\\n\", \"\\n\\n| a | b |\\n\\n\"},\n\t\t{\"| H |\\n|---|\\n| a |\\n\", \"\\n\\n| H |\\n|---|\\n| a |\\n\\n\"}, // full table renders as \u003ctable\u003e\n\t\t// Realm-binding defenses STILL ON.\n\t\t{\"\u003cgno-card\u003e\\n\", \"\\n\\n\\\\\u003cgno-card\u003e\\n\\n\"},\n\t\t// CM §4.6 HTML block types 1-5 — escaped in Rich mode too\n\t\t// (defense is mode-independent).\n\t\t{\"\u003cscript\u003ex\u003c/script\u003e\\n\", \"\\n\\n\\\\\u003cscript\u003ex\u003c/script\u003e\\n\\n\"},\n\t\t{\"\u003c!-- comment --\u003e\\n\", \"\\n\\n\\\\\u003c!-- comment --\u003e\\n\\n\"},\n\t\t{\"\u003c?php x ?\u003e\\n\", \"\\n\\n\\\\\u003c?php x ?\u003e\\n\\n\"},\n\t\t{\"\u003c!DOCTYPE html\u003e\\n\", \"\\n\\n\\\\\u003c!DOCTYPE html\u003e\\n\\n\"},\n\t\t{\"[t][l]\\n\", \"\\n\\n\\\\[t\\\\]\\\\[l\\\\]\\n\\n\"},\n\t\t{\"[^name]\\n\", \"\\n\\n\\\\[^name\\\\]\\n\\n\"},\n\t\t// LRD-only input strips to nothing; empty-after-escape short-\n\t\t// circuits to \"\" so realm concatenation doesn't leak a stray\n\t\t// blank line.\n\t\t{\"[x]: y\\n\", \"\"},\n\t\t{\"\", \"\"}, // empty input → empty output, no stray blank line\n\t\t{\"```\\ncode\\n\", \"\\n\\n```\\ncode\\n```\\n\\n\"},\n\t\t{\"[x](javascript\u0026colon;alert)\\n\", \"\\n\\n[x](javascript%26colon;alert)\\n\\n\"},\n\t\t// `\\;` on a named reference — unescaped to `\u0026colon;` by a renderer.\n\t\t{\"[x](javascript\u0026colon\\\\;alert)\\n\", \"\\n\\n[x](javascript%26colon\\\\;alert)\\n\\n\"},\n\t\t// Numeric reference feeding the named pass — see TestBlock.\n\t\t{\"[x](javascript\u0026#x26;colon;alert)\\n\", \"\\n\\n[x](javascript%26#x26;colon;alert)\\n\\n\"},\n\t\t{\"[x](/r/boards$help\u0026func=DeleteThread\u0026boardID=2)\\n\", \"\\n\\n[x](/r/boards$help\u0026func=DeleteThread\u0026boardID=2)\\n\\n\"},\n\t}\n\tfor _, c := range cases {\n\t\tgot := BlockRich(c.in)\n\t\tif got != c.want {\n\t\t\tt.Errorf(\"BlockRich(%q) = %q, want %q\", c.in, got, c.want)\n\t\t}\n\t\t// Idempotency: BlockRich(BlockRich(in)) must be byte-identical\n\t\t// to BlockRich(in) for every input in the table.\n\t\ttwice := BlockRich(got)\n\t\tif twice != got {\n\t\t\tt.Errorf(\"BlockRich not idempotent for %q: BlockRich(once)=%q, BlockRich(twice)=%q\", c.in, got, twice)\n\t\t}\n\t}\n}\n\nfunc TestBlockRich_LeadingBlankLineGuaranteed(t *testing.T) {\n\t// Every non-empty result begins with \"\\n\\n\" so `chrome +\n\t// BlockRich(user)` cannot place the user's first line in the same\n\t// paragraph as the realm's last line (which would let a deeper\n\t// `===` or `|---|` in user content retroactively promote realm\n\t// chrome).\n\tfor _, in := range []string{\"x\", \"x\\n\", \"# h\", \"- i\\n- j\", \"| a |\\n|---|\\n| 1 |\"} {\n\t\tgot := BlockRich(in)\n\t\tif got == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif !strings.HasPrefix(got, \"\\n\\n\") {\n\t\t\tt.Errorf(\"BlockRich(%q) = %q; expected leading '\\\\n\\\\n'\", in, got)\n\t\t}\n\t}\n}\n\nfunc TestBlockRich_TrailingBlankLineGuaranteed(t *testing.T) {\n\t// Every non-empty result ends with \"\\n\\n\" so `BlockRich(user) +\n\t// chrome` cannot extend user's last paragraph into the realm's\n\t// next line (CM §5.2 lazy continuation, or a realm-supplied\n\t// `|---|` row retroactively promoting user's last line into a\n\t// `\u003cthead\u003e` header).\n\tfor _, in := range []string{\"x\", \"x\\n\", \"# h\", \"- i\\n- j\", \"| H |\\n|---|\\n| a |\"} {\n\t\tgot := BlockRich(in)\n\t\tif got == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif !strings.HasSuffix(got, \"\\n\\n\") {\n\t\t\tt.Errorf(\"BlockRich(%q) = %q; expected trailing '\\\\n\\\\n'\", in, got)\n\t\t}\n\t}\n}\n\nfunc TestBlockquoteRich(t *testing.T) {\n\t// BlockquoteRich strips BlockRich's leading \"\\n\", line-prefixes\n\t// each remaining line with \"\u003e \", and emits \"\\n\" on both ends:\n\t// leading \"\\n\" prevents `chrome + BlockquoteRich(user)` from\n\t// landing the first `\u003e` mid-line; trailing \"\\n\\n\" (blank line)\n\t// prevents `BlockquoteRich(user) + chrome` from pulling chrome\n\t// into the quote via CM §5.2 lazy continuation.\n\tcases := []struct{ name, in, want string }{\n\t\t{\"plain text\", \"hello world\\n\", \"\\n\u003e hello world\\n\\n\"},\n\t\t{\"atx heading preserved\", \"# heading\\n\", \"\\n\u003e # heading\\n\\n\"},\n\t\t{\"nested blockquote\", \"\u003e nested\\n\", \"\\n\u003e \u003e nested\\n\\n\"},\n\t\t{\"list item preserved\", \"- item\\n\", \"\\n\u003e - item\\n\\n\"},\n\t\t{\"ordered list preserved\", \"1. item\\n\", \"\\n\u003e 1. item\\n\\n\"},\n\t\t{\"first-line setext escaped\", \"---\\n\", \"\\n\u003e \\\\---\\n\\n\"},\n\t\t{\"deeper setext preserved\", \"text\\n===\\n\", \"\\n\u003e text\\n\u003e ===\\n\\n\"},\n\t\t{\"thematic break asterisks preserved\", \"***\\n\", \"\\n\u003e ***\\n\\n\"},\n\t\t// Realm-binding defenses still on.\n\t\t{\"gno extension escaped\", \"\u003cgno-card\u003e\\n\", \"\\n\u003e \\\\\u003cgno-card\u003e\\n\\n\"},\n\t\t{\"ref-link use escaped\", \"[t][l]\\n\", \"\\n\u003e \\\\[t\\\\]\\\\[l\\\\]\\n\\n\"},\n\t\t{\"footnote escaped\", \"[^name]\\n\", \"\\n\u003e \\\\[^name\\\\]\\n\\n\"},\n\t\t// LRDs are stripped by BlockRich entirely; trimming the\n\t\t// resulting bare \"\\n\" leaves empty input and the helper\n\t\t// returns \"\" without emitting a blockquote.\n\t\t{\"lrd alone strips to empty\", \"[x]: y\\n\", \"\"},\n\t\t// Code fence autoclose at EOF lands inside the quote.\n\t\t{\"unclosed fence autoclosed\", \"```\\ncode\\n\", \"\\n\u003e ```\\n\u003e code\\n\u003e ```\\n\\n\"},\n\t\t// Multi-paragraph preserves the inner blank line (rendered\n\t\t// as a quoted blank line `\u003e \\n`).\n\t\t{\"multi-paragraph preserves blank\", \"a\\n\\nb\\n\", \"\\n\u003e a\\n\u003e \\n\u003e b\\n\\n\"},\n\t\t// Empty / blank-only input collapses cleanly to \"\".\n\t\t{\"empty input\", \"\", \"\"},\n\t\t// CRLF normalized through BlockRich.\n\t\t{\"crlf normalized\", \"a\\r\\nb\\n\", \"\\n\u003e a\\n\u003e b\\n\\n\"},\n\t\t// NUL replaced with U+FFFD by BlockRich.\n\t\t{\"nul replaced\", \"x\\x00y\\n\", \"\\n\u003e x\\uFFFDy\\n\\n\"},\n\t\t// Multiple trailing newlines collapse to the single trailing\n\t\t// blank line shape — output never ends with more than `\\n\\n`.\n\t\t{\"multiple trailing newlines collapse\", \"foo\\n\\n\\n\", \"\\n\u003e foo\\n\\n\"},\n\t\t// Internal tabs are preserved (BlockRich does not touch them).\n\t\t{\"internal tab preserved\", \"a\\tb\\n\", \"\\n\u003e a\\tb\\n\\n\"},\n\t\t// Whitespace-only input still yields a blockquote (the user\n\t\t// wrote literal spaces). The line-prefix loop emits `\u003e ` plus\n\t\t// the original two spaces.\n\t\t{\"whitespace-only input\", \"  \", \"\\n\u003e   \\n\\n\"},\n\t}\n\tfor _, c := range cases {\n\t\tgot := BlockquoteRich(c.in)\n\t\tif got != c.want {\n\t\t\tt.Errorf(\"%s: BlockquoteRich(%q) = %q, want %q\", c.name, c.in, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestBlockquoteRich_DoubleWrapNestsQuote(t *testing.T) {\n\t// Not idempotent: calling twice nests the quote one level\n\t// deeper. The aggressive TrimRight in BlockquoteRich also\n\t// collapses the inner trailing blank line, so the second pass\n\t// produces a clean `\u003e \u003e foo` nesting (no `\u003e ` quoted blank in\n\t// the middle) plus the outer trailing blank line.\n\tonce := BlockquoteRich(\"foo\\n\")\n\ttwice := BlockquoteRich(once)\n\tif want := \"\\n\u003e \u003e foo\\n\\n\"; twice != want {\n\t\tt.Errorf(\"BlockquoteRich(BlockquoteRich(%q)) = %q, want %q\", \"foo\\n\", twice, want)\n\t}\n}\n\nfunc TestBlockquoteRich_LeadingNewlineGuaranteed(t *testing.T) {\n\t// Every non-empty result starts with \"\\n\" so realm concatenation\n\t// like `chrome + BlockquoteRich(user)` doesn't place `\u003e` mid-line.\n\tfor _, in := range []string{\"x\", \"x\\n\", \"# h\", \"- i\\n- j\"} {\n\t\tgot := BlockquoteRich(in)\n\t\tif got == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif got[0] != '\\n' {\n\t\t\tt.Errorf(\"BlockquoteRich(%q) = %q; expected leading '\\\\n'\", in, got)\n\t\t}\n\t}\n}\n\nfunc TestBlockquoteRich_TrailingBlankLineGuaranteed(t *testing.T) {\n\t// Every non-empty result ends with \"\\n\\n\" so realm concatenation\n\t// like `BlockquoteRich(user) + \"more text\"` doesn't pull \"more\n\t// text\" into the quote via CM §5.2 lazy continuation.\n\tfor _, in := range []string{\"x\", \"x\\n\", \"# h\", \"- i\\n- j\", \"para\\n\\nmore\"} {\n\t\tgot := BlockquoteRich(in)\n\t\tif got == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif !strings.HasSuffix(got, \"\\n\\n\") {\n\t\t\tt.Errorf(\"BlockquoteRich(%q) = %q; expected trailing '\\\\n\\\\n'\", in, got)\n\t\t}\n\t}\n}\n\nfunc TestBlockquoteRich_NoStrayEmptyQuotedLine(t *testing.T) {\n\t// BlockRich's own leading \"\\n\" must be stripped before\n\t// line-prefixing — otherwise the output would start with a\n\t// useless `\u003e \\n` empty quoted line.\n\tgot := BlockquoteRich(\"foo\\n\")\n\tif strings.HasPrefix(got, \"\\n\u003e \\n\") {\n\t\tt.Errorf(\"BlockquoteRich leaked BlockRich's leading '\\\\n' as `\u003e \\\\n`: %q\", got)\n\t}\n}\n\nfunc TestNeuterLeadingSetextIfQualifying(t *testing.T) {\n\tcases := []struct{ name, in, want string }{\n\t\t{\"leading-setext-h1\", \"===\\nbody\\n\", \"\\\\===\\nbody\\n\"},\n\t\t{\"leading-setext-h2\", \"---\\nbody\\n\", \"\\\\---\\nbody\\n\"},\n\t\t{\"leading-setext-indented\", \"   ===\\nbody\\n\", \"   \\\\===\\nbody\\n\"},\n\t\t{\"leading-setext-indented-4\", \"    ===\\nbody\\n\", \"    ===\\nbody\\n\"}, // indented code\n\t\t{\"leading-setext-trailing-ws\", \"===   \\nbody\\n\", \"\\\\===   \\nbody\\n\"},\n\t\t{\"leading-setext-mixed-chars\", \"=-=-\\nbody\\n\", \"=-=-\\nbody\\n\"},         // mixed; not setext\n\t\t{\"leading-setext-has-content\", \"=== text\\nbody\\n\", \"=== text\\nbody\\n\"}, // mixed content\n\t\t{\"setext-deeper-untouched\", \"title\\n===\\nfoo\\n\", \"title\\n===\\nfoo\\n\"},\n\t\t{\"leading-thematic-asterisk\", \"***\\nbody\\n\", \"***\\nbody\\n\"}, // not setext, untouched\n\t\t{\"leading-thematic-underscore\", \"___\\nbody\\n\", \"___\\nbody\\n\"},\n\t\t{\"leading-blank-then-setext\", \"\\n===\\nbody\\n\", \"\\n\\\\===\\nbody\\n\"},\n\t\t{\"leading-blank-ws-then-setext\", \"   \\n===\\nbody\\n\", \"   \\n\\\\===\\nbody\\n\"},\n\t\t{\"text-first\", \"hello\\n===\\n\", \"hello\\n===\\n\"}, // text before === — user-authored\n\t\t{\"empty\", \"\", \"\"},\n\t\t{\"all-blank\", \"   \\n\\n\", \"   \\n\\n\"},\n\t\t{\"only-equals\", \"===\", \"\\\\===\"},\n\t}\n\tfor _, c := range cases {\n\t\tif got := neuterLeadingSetextIfQualifying(c.in); got != c.want {\n\t\t\tt.Errorf(\"%s: neuterLeadingSetextIfQualifying(%q) = %q, want %q\", c.name, c.in, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestLinkTitle(t *testing.T) {\n\tcases := []struct{ in, want string }{\n\t\t{`he said \"hi\"`, `he said \\\"hi\\\"`},\n\t\t{`it's nice`, `it\\'s nice`},\n\t\t{\"line1\\nline2\", \"line1 line2\"},\n\t}\n\tfor _, c := range cases {\n\t\tif got := LinkTitle(c.in); got != c.want {\n\t\t\tt.Errorf(\"LinkTitle(%q) = %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestTableCell(t *testing.T) {\n\tcases := []struct{ in, want string }{\n\t\t{\"plain cell\", \"plain cell\"},\n\t\t{\"a|b\", `a\\|b`},\n\t\t{\"a\\tb\", \"a b\"},\n\t\t{\"a*b|c\", `a\\*b\\|c`},\n\t}\n\tfor _, c := range cases {\n\t\tif got := TableCell(c.in); got != c.want {\n\t\t\tt.Errorf(\"TableCell(%q) = %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestHTMLEscape(t *testing.T) {\n\tcases := []struct{ in, want string }{\n\t\t{\"plain\", \"plain\"},\n\t\t{\"\u003cscript\u003e\", \"\u0026lt;script\u0026gt;\"},\n\t\t{`a \u0026 b`, \"a \u0026amp; b\"},\n\t\t{`\"quoted\"`, \"\u0026#34;quoted\u0026#34;\"},\n\t}\n\tfor _, c := range cases {\n\t\tif got := HTMLEscape(c.in); got != c.want {\n\t\t\tt.Errorf(\"HTMLEscape(%q) = %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestURL(t *testing.T) {\n\tcases := []struct{ in, want string }{\n\t\t{\"https://example.com/x\", \"https://example.com/x\"},\n\t\t{\"http://example.com\", \"http://example.com\"},\n\t\t{\"mailto:a@b.com\", \"mailto:a@b.com\"},\n\t\t{\"mailto:a@b.com?body=phish\", \"\"},            // any query is a prefill-phishing vector\n\t\t{\"mailto:a@b.com?BODY=phish\", \"\"},            // header name case is irrelevant\n\t\t{\"mailto:a@b.com?Body=phish\", \"\"},            // mixed case\n\t\t{\"mailto:a@b.com?%62ody=phish\", \"\"},          // percent-encoded header (%62 == b)\n\t\t{\"mailto:a@b.com?subject=hi\u0026body=phish\", \"\"}, // body as second param\n\t\t{\"mailto:a@b.com?subject=hi\u0026BODY=phish\", \"\"}, // mixed case second param\n\t\t{\"mailto:a@b.com?subject=hello\", \"\"},         // subject alone still rejected\n\t\t{\"mailto:a@b.com?cc=x@y.com\", \"\"},            // cc rejected\n\t\t{\"mailto:a@b.com?bcc=x@y.com\", \"\"},           // bcc rejected\n\t\t{\"mailto:a@b.com?\", \"\"},                      // bare trailing query marker rejected\n\t\t{\"mailto:a@b.com\u0026#x3f;body=phish\", \"\"},       // hex char-ref ? — renderer decodes to ?body=\n\t\t{\"mailto:a@b.com\u0026#63;body=phish\", \"\"},        // decimal char-ref ? — same bypass\n\t\t{\"mailto:a@b.com\u0026quest;body=phish\", \"\"},      // named char-ref ? — same bypass\n\t\t{\"mailto:a@b.com\u0026body=phish\", \"\"},            // bare \u0026 gateway rejected\n\t\t{\"//evil.com\", \"\"},                           // protocol-relative rejected\n\t\t{\"javascript:alert(1)\", \"\"},                  // bad scheme\n\t\t{\"/r/foo\", \"/r/foo\"},                         // relative\n\t\t{\"./local\", \"./local\"},\n\t\t{\"#section\", \"#section\"}, // fragment-only\n\t\t{\"\", \"\"},\n\t\t{\"   \", \"\"},\n\t\t{\"https://a.com/path with space\", \"https://a.com/path%20with%20space\"},\n\t}\n\tfor _, c := range cases {\n\t\tif got := URL(c.in); got != c.want {\n\t\t\tt.Errorf(\"URL(%q) = %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestImageURL(t *testing.T) {\n\tcases := []struct{ in, want string }{\n\t\t{\"https://example.com/img.png\", \"https://example.com/img.png\"},\n\t\t{\"mailto:a@b.com\", \"\"}, // mailto rejected for images\n\t\t{\"data:image/svg+xml,\u003csvg/\u003e\", \"data:image/svg+xml,%3Csvg/%3E\"},\n\t\t{\"data:image/png;base64,XXX\", \"data:image/png;base64,XXX\"},\n\t\t{\"data:text/html,\u003cscript\u003e\", \"\"}, // bad data subset\n\t\t{\"javascript:alert(1)\", \"\"},\n\t\t{\"\", \"\"},\n\t}\n\tfor _, c := range cases {\n\t\tif got := ImageURL(c.in); got != c.want {\n\t\t\tt.Errorf(\"ImageURL(%q) = %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestUserName(t *testing.T) {\n\tcases := []struct{ in, want string }{\n\t\t{\"alice\", \"alice\"},\n\t\t{\"alice123\", \"alice123\"},\n\t\t{\"alice_bob-cat\", \"alice_bob-cat\"},\n\t\t{\"Alice\", \"\"},  // uppercase first\n\t\t{\"1alice\", \"\"}, // digit first\n\t\t{\"\", \"\"},\n\t\t{\"a\\u200Blice\", \"alice\"}, // bidi stripped, then matches\n\t}\n\tfor _, c := range cases {\n\t\tif got := UserName(c.in); got != c.want {\n\t\t\tt.Errorf(\"UserName(%q) = %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestBechString(t *testing.T) {\n\taddrG := \"g1abc123def456ghi789jkl012mno345p\"\n\tcases := []struct {\n\t\ts, prefix string\n\t\twant      string\n\t}{\n\t\t{addrG, \"g\", addrG},\n\t\t{addrG, \"\", addrG},  // any prefix\n\t\t{addrG, \"gpub\", \"\"}, // wrong prefix\n\t\t{\"gpub1abc123def456ghijklmn\", \"gpub\", \"gpub1abc123def456ghijklmn\"},\n\t\t{\"gpub1abc123def456ghijklmn\", \"\", \"gpub1abc123def456ghijklmn\"},\n\t\t{\"b1xyz789abc123def456\", \"\", \"b1xyz789abc123def456\"}, // any-prefix mode allows b1...\n\t\t{\"g1ABC\", \"g\", \"\"}, // uppercase rejected\n\t\t{\"x\", \"g\", \"\"},\n\t\t{\"\", \"g\", \"\"},\n\t}\n\tfor _, c := range cases {\n\t\tif got := BechString(c.s, c.prefix); got != c.want {\n\t\t\tt.Errorf(\"BechString(%q,%q) = %q, want %q\", c.s, c.prefix, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestFootnoteLabel(t *testing.T) {\n\tcases := []struct{ in, want string }{\n\t\t{\"note1\", \"note1\"},\n\t\t{\"Note_A-1\", \"Note_A-1\"},\n\t\t{\"with space\", \"\"},\n\t\t{\"\", \"\"},\n\t}\n\tfor _, c := range cases {\n\t\tif got := FootnoteLabel(c.in); got != c.want {\n\t\t\tt.Errorf(\"FootnoteLabel(%q) = %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestLanguageName(t *testing.T) {\n\tcases := []struct{ in, want string }{\n\t\t{\"go\", \"go\"},\n\t\t{\"c++\", \"c++\"},\n\t\t{\"python3\", \"python3\"},\n\t\t{\"objective-c\", \"objective-c\"},\n\t\t{\"with space\", \"\"},\n\t\t{\"\", \"\"},\n\t}\n\tfor _, c := range cases {\n\t\tif got := LanguageName(c.in); got != c.want {\n\t\t\tt.Errorf(\"LanguageName(%q) = %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestNestedPrefix(t *testing.T) {\n\tcases := []struct{ in, want string }{\n\t\t{\"\", \"\"},\n\t\t{\"  \", \"  \"},\n\t\t{\"\\t\", \"\\t\"},\n\t\t{\"\u003e \", \"\u003e \"},\n\t\t{\"\u003e \u003e \", \"\u003e \u003e \"},\n\t\t{\"## \", \"\"}, // markdown-active prefix rejected\n\t\t{\"- \", \"\"},\n\t}\n\tfor _, c := range cases {\n\t\tif got := NestedPrefix(c.in); got != c.want {\n\t\t\tt.Errorf(\"NestedPrefix(%q) = %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestCodeFence(t *testing.T) {\n\tif got := CodeFence(\"```\", 3); got != \"````\" {\n\t\tt.Errorf(\"CodeFence: got %q, want %q\", got, \"````\")\n\t}\n\tif got := CodeFence(\"\", 3); got != \"```\" {\n\t\tt.Errorf(\"CodeFence empty: got %q, want %q\", got, \"```\")\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"HY39VWY8fcf5Zw7H54jOU1QTZIhFm0oDcON8K2NwRmZzyatwAXF6149NsRlBUJRaO3hiGfqAAWCUDkibWlEPeQ=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1manfred47kzduec920z88wfr64ylksmdcedlf5","package":{"name":"md","path":"gno.land/p/moul/md","files":[{"name":"example_test.gno","body":"package md\n\nimport \"strings\"\n\nfunc ExampleHeaders() {\n\tprintln(H1(\"Header 1\"))\n\tprintln(H2(\"Header 2\"))\n\tprintln(H3(\"Header 3\"))\n\tprintln(H4(\"Header 4\"))\n\tprintln(H5(\"Header 5\"))\n\tprintln(H6(\"Header 6\"))\n\n\t// Output:\n\t// # Header 1\n\t//\n\t// ## Header 2\n\t//\n\t// ### Header 3\n\t//\n\t// #### Header 4\n\t//\n\t// ##### Header 5\n\t//\n\t// ###### Header 6\n}\n\nfunc ExampleStyles() {\n\tprintln(Bold(\"bold\"))\n\tprintln(Italic(\"italic\"))\n\tprintln(Strikethrough(\"strikethrough\"))\n\n\t// Output:\n\t// **bold**\n\t// *italic*\n\t// ~~strikethrough~~\n}\n\nfunc ExampleLists() {\n\tprintln(BulletList([]string{\n\t\t\"Item 1\",\n\t\t\"Item 2\\nMore details for item 2\",\n\t}))\n\tprintln(OrderedList([]string{\"Step 1\", \"Step 2\"}))\n\tprintln(TodoList([]string{\"Task 1\", \"Task 2\\nSubtask 2\"}, []bool{true, false}))\n\tprintln(Nested(BulletList([]string{\"Parent Item\", OrderedList([]string{\"Child 1\", \"Child 2\"})}), \"  \"))\n\n\t// Output:\n\t// - Item 1\n\t// - Item 2\n\t//   More details for item 2\n\t//\n\t// 1. Step 1\n\t// 2. Step 2\n\t//\n\t// - [x] Task 1\n\t// - [ ] Task 2\n\t//   Subtask 2\n\t//\n\t//   - Parent Item\n\t//   - 1. Child 1\n\t//     2. Child 2\n}\n\nfunc ExampleBlocks() {\n\tprint(Paragraph(\"This is a paragraph.\"))\n\t// Blockquote adds multiple newlines which Output doesn't allow, so trim\n\tprintln(strings.TrimSpace(Blockquote(\"This is a blockquote\\nSpanning multiple lines\")))\n\n\t// Output:\n\t// This is a paragraph.\n\t//\n\t// \u003e This is a blockquote\n\t// \u003e Spanning multiple lines\n}\n\nfunc ExampleCode() {\n\tprintln(InlineCode(\"inline `code`\"))\n\tprintln(CodeBlock(\"line1\\nline2\"))\n\tprintln(LanguageCodeBlock(\"go\", \"func main() {\\nprintln(\\\"Hello, world!\\\")\\n}\"))\n\tprintln(HorizontalRule())\n\n\t// Output:\n\t// `` inline `code` ``\n\t// ```\n\t// line1\n\t// line2\n\t// ```\n\t//\n\t// ```go\n\t// func main() {\n\t// println(\"Hello, world!\")\n\t// }\n\t// ```\n\t//\n\t// ---\n}\n\nfunc ExampleReferences() {\n\tprintln(Link(\"Gno\", \"http://gno.land\"))\n\tprintln(Image(\"Alt Text\", \"http://example.com/image.png\"))\n\tprintln(InlineImageWithLink(\"Alt Text\", \"http://example.com/image.png\", \"http://example.com\"))\n\tprintln(FootnoteDefinition(\"ref\", \"This is a footnote\"))\n\t// LinkReferenceDefinition adds multiple newlines which Output doesn't allow, so trim\n\tprintln(strings.TrimSpace(LinkReferenceDefinition(\"r-example\", \"/r/example\", \"\")))\n\n\t// Output:\n\t//\n\t// [Gno](http://gno.land)\n\t// ![Alt Text](http://example.com/image.png)\n\t// [![Alt Text](http://example.com/image.png)](http://example.com)\n\t// [^ref]:\n\t//     This is a footnote\n\t//\n\t// [r-example]: /r/example\n}\n\nfunc ExampleColumns() {\n\tprintln(\"4 columns in one gno-columns tag:\")\n\tprintln(Columns([]string{\n\t\t\"Column1\\ncontent1\",\n\t\t\"Column2\\ncontent2\",\n\t\t\"Column3\\ncontent3\",\n\t\t\"Column4\\ncontent4\",\n\t}, true))\n\n\t// Should be automatically placed in multiple column tags\n\tprintln(\"3 cols per row without padding:\")\n\tprintln(ColumnsN([]string{\n\t\t\"Row1Column1\\ncontent1\",\n\t\t\"Row1Column2\\ncontent2\",\n\t\t\"Row1Column3\\ncontent3\",\n\t\t\"Row2Column1\\ncontent1\",\n\t\t\"Row2Column2\\ncontent2\",\n\t\t\"Row2Column3\\ncontent3\",\n\t\t\"Row3Column1\\ncontent1\",\n\t\t\"Row3Column2\\ncontent2\",\n\t\t\"Row3Column3\\ncontent3\",\n\t}, 3, false))\n\n\t// Should be padded, up to 4 cols\n\tprintln(\"2 padded to 4:\")\n\tprintln(ColumnsN([]string{\n\t\t\"Column1\\ncontent1\",\n\t\t\"Column2\\ncontent2\",\n\t}, 4, true))\n\n\t// Output:\n\t// 4 columns in one gno-columns tag:\n\t// \u003cgno-columns\u003e\n\t// Column1\n\t// content1\n\t// \u003cgno-columns-sep\u003e\n\t// Column2\n\t// content2\n\t// \u003cgno-columns-sep\u003e\n\t// Column3\n\t// content3\n\t// \u003cgno-columns-sep\u003e\n\t// Column4\n\t// content4\n\t// \u003c/gno-columns\u003e\n\t//\n\t// 3 cols per row without padding:\n\t// \u003cgno-columns\u003e\n\t// Row1Column1\n\t// content1\n\t// \u003cgno-columns-sep\u003e\n\t// Row1Column2\n\t// content2\n\t// \u003cgno-columns-sep\u003e\n\t// Row1Column3\n\t// content3\n\t// \u003c/gno-columns\u003e\n\t// \u003cgno-columns\u003e\n\t// Row2Column1\n\t// content1\n\t// \u003cgno-columns-sep\u003e\n\t// Row2Column2\n\t// content2\n\t// \u003cgno-columns-sep\u003e\n\t// Row2Column3\n\t// content3\n\t// \u003c/gno-columns\u003e\n\t// \u003cgno-columns\u003e\n\t// Row3Column1\n\t// content1\n\t// \u003cgno-columns-sep\u003e\n\t// Row3Column2\n\t// content2\n\t// \u003cgno-columns-sep\u003e\n\t// Row3Column3\n\t// content3\n\t// \u003c/gno-columns\u003e\n\t//\n\t// 2 padded to 4:\n\t// \u003cgno-columns\u003e\n\t// Column1\n\t// content1\n\t// \u003cgno-columns-sep\u003e\n\t// Column2\n\t// content2\n\t// \u003cgno-columns-sep\u003e\n\t//\n\t// \u003cgno-columns-sep\u003e\n\t//\n\t// \u003c/gno-columns\u003e\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/md\"\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"},{"name":"md_test.gno","body":"package md_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/md\"\n)\n\nfunc TestHelpers(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tfunction func() string\n\t\texpected string\n\t}{\n\t\t{\"Bold\", func() string { return md.Bold(\"foo\") }, \"**foo**\"},\n\t\t{\"Italic\", func() string { return md.Italic(\"foo\") }, \"*foo*\"},\n\t\t{\"Strikethrough\", func() string { return md.Strikethrough(\"foo\") }, \"~~foo~~\"},\n\t\t{\"H1\", func() string { return md.H1(\"foo\") }, \"# foo\\n\"},\n\t\t{\"HorizontalRule\", md.HorizontalRule, \"---\\n\"},\n\t\t{\"InlineCode\", func() string { return md.InlineCode(\"foo\") }, \"`foo`\"},\n\t\t{\"CodeBlock\", func() string { return md.CodeBlock(\"foo\") }, \"```\\nfoo\\n```\\n\"},\n\t\t{\"LanguageCodeBlock\", func() string { return md.LanguageCodeBlock(\"go\", \"foo\") }, \"```go\\nfoo\\n```\\n\"},\n\t\t{\"Link\", func() string { return md.Link(\"foo\", \"http://example.com\") }, \"[foo](http://example.com)\"},\n\t\t{\"UserLink\", func() string { return md.UserLink(\"moul\") }, \"[@moul](/u/moul)\"},\n\t\t{\"Image\", func() string { return md.Image(\"foo\", \"http://example.com\") }, \"![foo](http://example.com)\"},\n\t\t{\"InlineImageWithLink\", func() string {\n\t\t\treturn md.InlineImageWithLink(\"alt\", \"http://img.example.com/x.png\", \"http://link.example.com\")\n\t\t}, \"[![alt](http://img.example.com/x.png)](http://link.example.com)\"},\n\t\t{\"FootnoteDefinition\", func() string { return md.FootnoteDefinition(\"foo\", \"bar\") }, \"[^foo]:\\n    bar\\n\"},\n\t\t{\"LinkReferenceDefinition\", func() string {\n\t\t\treturn md.LinkReferenceDefinition(\"foo\", \"http://example.com\", \"\")\n\t\t}, \"\\n\\n[foo]: http://example.com\\n\\n\"},\n\t\t{\"Paragraph\", func() string { return md.Paragraph(\"foo\") }, \"foo\\n\\n\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := tt.function()\n\t\t\tif result != tt.expected {\n\t\t\t\tt.Errorf(\"%s() = %q, want %q\", tt.name, result, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestLists(t *testing.T) {\n\tt.Run(\"BulletList\", func(t *testing.T) {\n\t\titems := []string{\"foo\", \"bar\"}\n\t\texpected := \"- foo\\n- bar\\n\"\n\t\tresult := md.BulletList(items)\n\t\tif result != expected {\n\t\t\tt.Errorf(\"BulletList(%q) = %q, want %q\", items, result, expected)\n\t\t}\n\t})\n\n\tt.Run(\"OrderedList\", func(t *testing.T) {\n\t\titems := []string{\"foo\", \"bar\"}\n\t\texpected := \"1. foo\\n2. bar\\n\"\n\t\tresult := md.OrderedList(items)\n\t\tif result != expected {\n\t\t\tt.Errorf(\"OrderedList(%q) = %q, want %q\", items, result, expected)\n\t\t}\n\t})\n\n\tt.Run(\"TodoList\", func(t *testing.T) {\n\t\titems := []string{\"foo\", \"bar\\nmore bar\"}\n\t\tdone := []bool{true, false}\n\t\texpected := \"- [x] foo\\n- [ ] bar\\n  more bar\\n\"\n\t\tresult := md.TodoList(items, done)\n\t\tif result != expected {\n\t\t\tt.Errorf(\"TodoList(%q, %q) = %q, want %q\", items, done, result, expected)\n\t\t}\n\t})\n}\n\nfunc TestUserLink(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    string\n\t\texpected string\n\t}{\n\t\t{\"username\", \"moul\", \"[@moul](/u/moul)\"},\n\t\t// \"g1blah\" data part is too short for a bech32 address (min 6\n\t\t// chars after \"1\"); UserLink validates as a username instead.\n\t\t{\"short g1-prefixed string treated as username\", \"g1blah\", \"[@g1blah](/u/g1blah)\"},\n\t\t// \"user_name\" is a valid username (charset includes _ and -);\n\t\t// the validator returns it verbatim, so no markdown escape of _.\n\t\t{\"username with underscore\", \"user_name\", \"[@user_name](/u/user_name)\"},\n\t\t// \"g1abc123\" has a 6-char data part — valid bech32 shape.\n\t\t{\"address with 6-char data\", \"g1abc123\", \"[g1abc123](/u/g1abc123)\"},\n\t\t// invalid identifier (spaces, uppercase, etc.) → empty.\n\t\t{\"rejected: spaces\", \"hello world\", \"\"},\n\t\t{\"rejected: uppercase first char\", \"Alice\", \"\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := md.UserLink(tt.input)\n\t\t\tif result != tt.expected {\n\t\t\t\tt.Errorf(\"UserLink(%q) = %q, want %q\", tt.input, result, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNested(t *testing.T) {\n\tt.Run(\"Nested Single Level\", func(t *testing.T) {\n\t\tcontent := \"- foo\\n- bar\"\n\t\texpected := \"  - foo\\n  - bar\"\n\t\tresult := md.Nested(content, \"  \")\n\t\tif result != expected {\n\t\t\tt.Errorf(\"Nested(%q) = %q, want %q\", content, result, expected)\n\t\t}\n\t})\n\n\tt.Run(\"Nested Double Level\", func(t *testing.T) {\n\t\tcontent := \"  - foo\\n  - bar\"\n\t\texpected := \"    - foo\\n    - bar\"\n\t\tresult := md.Nested(content, \"  \")\n\t\tif result != expected {\n\t\t\tt.Errorf(\"Nested(%q) = %q, want %q\", content, result, expected)\n\t\t}\n\t})\n}\n\nfunc TestColumns(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    []string\n\t\tpadded   bool\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"no columns\",\n\t\t\tinput:    []string{},\n\t\t\tpadded:   false,\n\t\t\texpected: \"\",\n\t\t},\n\t\t{\n\t\t\tname:     \"no columns padded\",\n\t\t\tinput:    []string{},\n\t\t\tpadded:   true,\n\t\t\texpected: \"\",\n\t\t},\n\t\t{\n\t\t\tname:   \"one column\",\n\t\t\tinput:  []string{\"Column 1\"},\n\t\t\tpadded: false,\n\t\t\texpected: `\u003cgno-columns\u003e\nColumn 1\n\u003c/gno-columns\u003e\n`,\n\t\t},\n\t\t{\n\t\t\tname:   \"one column padded\",\n\t\t\tinput:  []string{\"Column 1\"},\n\t\t\tpadded: true,\n\t\t\texpected: `\u003cgno-columns\u003e\nColumn 1\n\u003cgno-columns-sep\u003e\n\n\u003cgno-columns-sep\u003e\n\n\u003cgno-columns-sep\u003e\n\n\u003c/gno-columns\u003e\n`,\n\t\t},\n\t\t{\n\t\t\tname:   \"two columns\",\n\t\t\tinput:  []string{\"Column 1\", \"Column 2\"},\n\t\t\tpadded: false,\n\t\t\texpected: `\u003cgno-columns\u003e\nColumn 1\n\u003cgno-columns-sep\u003e\nColumn 2\n\u003c/gno-columns\u003e\n`,\n\t\t},\n\t\t{\n\t\t\tname:   \"two columns padded\",\n\t\t\tinput:  []string{\"Column 1\", \"Column 2\"},\n\t\t\tpadded: true,\n\t\t\texpected: `\u003cgno-columns\u003e\nColumn 1\n\u003cgno-columns-sep\u003e\nColumn 2\n\u003cgno-columns-sep\u003e\n\n\u003cgno-columns-sep\u003e\n\n\u003c/gno-columns\u003e\n`,\n\t\t},\n\t\t{\n\t\t\tname:   \"four columns\",\n\t\t\tinput:  []string{\"A\", \"B\", \"C\", \"D\"},\n\t\t\tpadded: false,\n\t\t\texpected: `\u003cgno-columns\u003e\nA\n\u003cgno-columns-sep\u003e\nB\n\u003cgno-columns-sep\u003e\nC\n\u003cgno-columns-sep\u003e\nD\n\u003c/gno-columns\u003e\n`,\n\t\t},\n\t\t{\n\t\t\tname:   \"four columns padded\",\n\t\t\tinput:  []string{\"A\", \"B\", \"C\", \"D\"},\n\t\t\tpadded: true,\n\t\t\texpected: `\u003cgno-columns\u003e\nA\n\u003cgno-columns-sep\u003e\nB\n\u003cgno-columns-sep\u003e\nC\n\u003cgno-columns-sep\u003e\nD\n\u003c/gno-columns\u003e\n`,\n\t\t},\n\t\t{\n\t\t\tname:   \"more than four columns\",\n\t\t\tinput:  []string{\"1\", \"2\", \"3\", \"4\", \"5\"},\n\t\t\tpadded: false,\n\t\t\texpected: `\u003cgno-columns\u003e\n1\n\u003cgno-columns-sep\u003e\n2\n\u003cgno-columns-sep\u003e\n3\n\u003cgno-columns-sep\u003e\n4\n\u003cgno-columns-sep\u003e\n5\n\u003c/gno-columns\u003e\n`,\n\t\t},\n\t\t{\n\t\t\tname:   \"more than four columns padded\",\n\t\t\tinput:  []string{\"1\", \"2\", \"3\", \"4\", \"5\"},\n\t\t\tpadded: true,\n\t\t\texpected: `\u003cgno-columns\u003e\n1\n\u003cgno-columns-sep\u003e\n2\n\u003cgno-columns-sep\u003e\n3\n\u003cgno-columns-sep\u003e\n4\n\u003cgno-columns-sep\u003e\n5\n\u003cgno-columns-sep\u003e\n\n\u003cgno-columns-sep\u003e\n\n\u003cgno-columns-sep\u003e\n\n\u003c/gno-columns\u003e\n`,\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 := md.Columns(tt.input, tt.padded)\n\t\t\tif result != tt.expected {\n\t\t\t\tt.Errorf(\"Columns(%v, %v) =\\n%q\\nwant:\\n%q\", tt.input, tt.padded, result, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestColumnsN(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\tcontent    []string\n\t\tcolsPerRow int\n\t\tpadded     bool\n\t\texpected   string\n\t}{\n\t\t{\n\t\t\tname:       \"empty input\",\n\t\t\tcontent:    []string{},\n\t\t\tcolsPerRow: 2,\n\t\t\tpadded:     false,\n\t\t\texpected:   \"\",\n\t\t},\n\t\t{\n\t\t\tname:       \"colsPerRow \u003c= 0\",\n\t\t\tcontent:    []string{\"A\", \"B\", \"C\"},\n\t\t\tcolsPerRow: 0,\n\t\t\tpadded:     false,\n\t\t\texpected: `\u003cgno-columns\u003e\nA\n\u003cgno-columns-sep\u003e\nB\n\u003cgno-columns-sep\u003e\nC\n\u003c/gno-columns\u003e\n`,\n\t\t},\n\t\t{\n\t\t\tname:       \"exact full row, no padding\",\n\t\t\tcontent:    []string{\"A\", \"B\"},\n\t\t\tcolsPerRow: 2,\n\t\t\tpadded:     false,\n\t\t\texpected: `\u003cgno-columns\u003e\nA\n\u003cgno-columns-sep\u003e\nB\n\u003c/gno-columns\u003e\n`,\n\t\t},\n\t\t{\n\t\t\tname:       \"partial last row, no padding\",\n\t\t\tcontent:    []string{\"A\", \"B\", \"C\"},\n\t\t\tcolsPerRow: 2,\n\t\t\tpadded:     false,\n\t\t\texpected: `\u003cgno-columns\u003e\nA\n\u003cgno-columns-sep\u003e\nB\n\u003c/gno-columns\u003e\n\u003cgno-columns\u003e\nC\n\u003c/gno-columns\u003e\n`,\n\t\t},\n\t\t{\n\t\t\tname:       \"partial last row, with padding\",\n\t\t\tcontent:    []string{\"A\", \"B\", \"C\"},\n\t\t\tcolsPerRow: 2,\n\t\t\tpadded:     true,\n\t\t\texpected: `\u003cgno-columns\u003e\nA\n\u003cgno-columns-sep\u003e\nB\n\u003c/gno-columns\u003e\n\u003cgno-columns\u003e\nC\n\u003cgno-columns-sep\u003e\n\n\u003c/gno-columns\u003e\n`,\n\t\t},\n\t\t{\n\t\t\tname:       \"padded with more empty cells\",\n\t\t\tcontent:    []string{\"X\"},\n\t\t\tcolsPerRow: 3,\n\t\t\tpadded:     true,\n\t\t\texpected: `\u003cgno-columns\u003e\nX\n\u003cgno-columns-sep\u003e\n\n\u003cgno-columns-sep\u003e\n\n\u003c/gno-columns\u003e\n`,\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 := md.ColumnsN(tt.content, tt.colsPerRow, tt.padded)\n\t\t\tif result != tt.expected {\n\t\t\t\tt.Errorf(\"ColumnsN(%v, %d, %v) =\\n%q\\nwant:\\n%q\", tt.content, tt.colsPerRow, tt.padded, result, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"BVwMAkRLOUi743XCHVasKzuGcwjWpyuEPgfec6U0QBZQmDnite7OnqdLHDE7EN7tS1bS1WhrP01rQGmiS/rhpQ=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"rotree","path":"gno.land/p/nt/avl/v0/rotree","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/avl/v0/rotree\"\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"},{"name":"rotree_test.gno","body":"package rotree\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\nfunc TestExample(t *testing.T) {\n\t// User represents our internal data structure\n\ttype User struct {\n\t\tID       string\n\t\tName     string\n\t\tBalance  int\n\t\tInternal string // sensitive internal data\n\t}\n\n\t// Create and populate the original tree with user pointers\n\ttree := avl.NewTree()\n\ttree.Set(\"alice\", \u0026User{\n\t\tID:       \"1\",\n\t\tName:     \"Alice\",\n\t\tBalance:  100,\n\t\tInternal: \"sensitive_data_1\",\n\t})\n\ttree.Set(\"bob\", \u0026User{\n\t\tID:       \"2\",\n\t\tName:     \"Bob\",\n\t\tBalance:  200,\n\t\tInternal: \"sensitive_data_2\",\n\t})\n\n\t// Define a makeEntrySafeFn that:\n\t// 1. Creates a defensive copy of the User struct\n\t// 2. Omits sensitive internal data\n\tmakeEntrySafeFn := func(v any) any {\n\t\toriginalUser := v.(*User)\n\t\treturn \u0026User{\n\t\t\tID:       originalUser.ID,\n\t\t\tName:     originalUser.Name,\n\t\t\tBalance:  originalUser.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\troTree := Wrap(tree, makeEntrySafeFn)\n\n\t// Test retrieving and verifying a user\n\tt.Run(\"Get User\", func(t *testing.T) {\n\t\t// Get user from read-only tree\n\t\tvalue := roTree.Get(\"alice\")\n\t\tif value == nil {\n\t\t\tt.Fatal(\"User 'alice' not found\")\n\t\t}\n\n\t\tuser := value.(*User)\n\n\t\t// Verify user data is correct\n\t\tif user.Name != \"Alice\" || user.Balance != 100 {\n\t\t\tt.Errorf(\"Unexpected user data: got name=%s balance=%d\", user.Name, user.Balance)\n\t\t}\n\n\t\t// Verify sensitive data is not exposed\n\t\tif user.Internal != \"\" {\n\t\t\tt.Error(\"Sensitive data should not be exposed\")\n\t\t}\n\n\t\t// Verify it's a different instance than the original\n\t\toriginalValue := tree.Get(\"alice\")\n\t\toriginalUser := originalValue.(*User)\n\t\tif user == originalUser {\n\t\t\tt.Error(\"Read-only tree should return a copy, not the original pointer\")\n\t\t}\n\t})\n\n\t// Test iterating over users\n\tt.Run(\"Iterate Users\", func(t *testing.T) {\n\t\tcount := 0\n\t\troTree.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\t\tuser := value.(*User)\n\t\t\t// Verify each user has empty Internal field\n\t\t\tif user.Internal != \"\" {\n\t\t\t\tt.Error(\"Sensitive data exposed during iteration\")\n\t\t\t}\n\t\t\tcount++\n\t\t\treturn false\n\t\t})\n\n\t\tif count != 2 {\n\t\t\tt.Errorf(\"Expected 2 users, got %d\", count)\n\t\t}\n\t})\n\n\t// Verify that modifications to the returned user don't affect the original\n\tt.Run(\"Modification Safety\", func(t *testing.T) {\n\t\tvalue := roTree.Get(\"alice\")\n\t\tuser := value.(*User)\n\n\t\t// Try to modify the returned user\n\t\tuser.Balance = 999\n\t\tuser.Internal = \"hacked\"\n\n\t\t// Verify original is unchanged\n\t\toriginalValue := tree.Get(\"alice\")\n\t\toriginalUser := originalValue.(*User)\n\t\tif originalUser.Balance != 100 || originalUser.Internal != \"sensitive_data_1\" {\n\t\t\tt.Error(\"Original user data was modified\")\n\t\t}\n\t})\n}\n\nfunc TestReadOnlyTree(t *testing.T) {\n\t// Example of a makeEntrySafeFn that appends \"_readonly\" to demonstrate transformation\n\tmakeEntrySafeFn := func(value any) any {\n\t\treturn value.(string) + \"_readonly\"\n\t}\n\n\ttree := avl.NewTree()\n\ttree.Set(\"key1\", \"value1\")\n\ttree.Set(\"key2\", \"value2\")\n\ttree.Set(\"key3\", \"value3\")\n\n\troTree := Wrap(tree, makeEntrySafeFn)\n\n\ttests := []struct {\n\t\tname     string\n\t\tkey      string\n\t\texpected any\n\t}{\n\t\t{\"ExistingKey1\", \"key1\", \"value1_readonly\"},\n\t\t{\"ExistingKey2\", \"key2\", \"value2_readonly\"},\n\t\t{\"NonExistingKey\", \"key4\", nil},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvalue := roTree.Get(tt.key)\n\t\t\tif value != tt.expected {\n\t\t\t\tt.Errorf(\"For key %s, expected %v, got %v\", tt.key, tt.expected, value)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Add example tests showing different makeEntrySafeFn implementations\nfunc TestMakeEntrySafeFnVariants(t *testing.T) {\n\ttree := avl.NewTree()\n\ttree.Set(\"slice\", []int{1, 2, 3})\n\ttree.Set(\"map\", map[string]int{\"a\": 1})\n\n\ttests := []struct {\n\t\tname            string\n\t\tmakeEntrySafeFn func(any) any\n\t\tkey             string\n\t\tvalidate        func(t *testing.T, value any)\n\t}{\n\t\t{\n\t\t\tname: \"Defensive Copy Slice\",\n\t\t\tmakeEntrySafeFn: func(v any) any {\n\t\t\t\toriginal := v.([]int)\n\t\t\t\treturn append([]int{}, original...)\n\t\t\t},\n\t\t\tkey: \"slice\",\n\t\t\tvalidate: func(t *testing.T, value any) {\n\t\t\t\tslice := value.([]int)\n\t\t\t\t// Modify the returned slice\n\t\t\t\tslice[0] = 999\n\t\t\t\t// Verify original is unchanged\n\t\t\t\toriginalValue := tree.Get(\"slice\")\n\t\t\t\toriginal := originalValue.([]int)\n\t\t\t\tif original[0] != 1 {\n\t\t\t\t\tt.Error(\"Original slice was modified\")\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t// Add more test cases for different makeEntrySafeFn implementations\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\troTree := Wrap(tree, tt.makeEntrySafeFn)\n\t\t\tvalue := roTree.Get(tt.key)\n\t\t\tif value == nil {\n\t\t\t\tt.Fatal(\"Key not found\")\n\t\t\t}\n\t\t\ttt.validate(t, value)\n\t\t})\n\t}\n}\n\nfunc TestNilMakeEntrySafeFn(t *testing.T) {\n\t// Create a tree with some test data\n\ttree := avl.NewTree()\n\toriginalValue := []int{1, 2, 3}\n\ttree.Set(\"test\", originalValue)\n\n\t// Create a ReadOnlyTree with nil makeEntrySafeFn\n\troTree := Wrap(tree, nil)\n\n\t// Test that we get back the original value\n\tvalue := roTree.Get(\"test\")\n\tif value == nil {\n\t\tt.Fatal(\"Key not found\")\n\t}\n\n\t// Verify it's the exact same slice (not a copy)\n\tretrievedSlice := value.([]int)\n\tif \u0026retrievedSlice[0] != \u0026originalValue[0] {\n\t\tt.Error(\"Expected to get back the original slice reference\")\n\t}\n\n\t// Test through iteration as well\n\troTree.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\tretrievedSlice := value.([]int)\n\t\tif \u0026retrievedSlice[0] != \u0026originalValue[0] {\n\t\t\tt.Error(\"Expected to get back the original slice reference in iteration\")\n\t\t}\n\t\treturn false\n\t})\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"zwqgQuKRVRIhIRTGgv4T0dhsXukKxgYxzEVbNIU5ve0eN18qkK4SP/6hVJQ4lIhJMhw+8kT+TygtrTh4bfH8Nw=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"pager","path":"gno.land/p/nt/avl/v0/pager","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/avl/v0/pager\"\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/v0/rotree\"\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"},{"name":"pager_test.gno","body":"package pager\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc TestPager_GetPage(t *testing.T) {\n\t// Create a new AVL tree and populate it with some key-value pairs.\n\ttree := avl.NewTree()\n\ttree.Set(\"a\", 1)\n\ttree.Set(\"b\", 2)\n\ttree.Set(\"c\", 3)\n\ttree.Set(\"d\", 4)\n\ttree.Set(\"e\", 5)\n\n\tt.Run(\"normal ordering\", func(t *testing.T) {\n\t\t// Create a new pager.\n\t\tpager := NewPager(tree, 10, false)\n\n\t\t// Define test cases.\n\t\ttests := []struct {\n\t\t\tpageNumber int\n\t\t\tpageSize   int\n\t\t\texpected   []Item\n\t\t}{\n\t\t\t{1, 2, []Item{{Key: \"a\", Value: 1}, {Key: \"b\", Value: 2}}},\n\t\t\t{2, 2, []Item{{Key: \"c\", Value: 3}, {Key: \"d\", Value: 4}}},\n\t\t\t{3, 2, []Item{{Key: \"e\", Value: 5}}},\n\t\t\t{1, 3, []Item{{Key: \"a\", Value: 1}, {Key: \"b\", Value: 2}, {Key: \"c\", Value: 3}}},\n\t\t\t{2, 3, []Item{{Key: \"d\", Value: 4}, {Key: \"e\", Value: 5}}},\n\t\t\t{1, 5, []Item{{Key: \"a\", Value: 1}, {Key: \"b\", Value: 2}, {Key: \"c\", Value: 3}, {Key: \"d\", Value: 4}, {Key: \"e\", Value: 5}}},\n\t\t\t{2, 5, []Item{}},\n\t\t}\n\n\t\tfor _, tt := range tests {\n\t\t\tpage := pager.GetPageWithSize(tt.pageNumber, tt.pageSize)\n\n\t\t\tuassert.Equal(t, len(tt.expected), len(page.Items))\n\n\t\t\tfor i, item := range page.Items {\n\t\t\t\tuassert.Equal(t, tt.expected[i].Key, item.Key)\n\t\t\t\tuassert.Equal(t, tt.expected[i].Value, item.Value)\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"reversed ordering\", func(t *testing.T) {\n\t\t// Create a new pager.\n\t\tpager := NewPager(tree, 10, true)\n\n\t\t// Define test cases.\n\t\ttests := []struct {\n\t\t\tpageNumber int\n\t\t\tpageSize   int\n\t\t\texpected   []Item\n\t\t}{\n\t\t\t{1, 2, []Item{{Key: \"e\", Value: 5}, {Key: \"d\", Value: 4}}},\n\t\t\t{2, 2, []Item{{Key: \"c\", Value: 3}, {Key: \"b\", Value: 2}}},\n\t\t\t{3, 2, []Item{{Key: \"a\", Value: 1}}},\n\t\t\t{1, 3, []Item{{Key: \"e\", Value: 5}, {Key: \"d\", Value: 4}, {Key: \"c\", Value: 3}}},\n\t\t\t{2, 3, []Item{{Key: \"b\", Value: 2}, {Key: \"a\", Value: 1}}},\n\t\t\t{1, 5, []Item{{Key: \"e\", Value: 5}, {Key: \"d\", Value: 4}, {Key: \"c\", Value: 3}, {Key: \"b\", Value: 2}, {Key: \"a\", Value: 1}}},\n\t\t\t{2, 5, []Item{}},\n\t\t}\n\n\t\tfor _, tt := range tests {\n\t\t\tpage := pager.GetPageWithSize(tt.pageNumber, tt.pageSize)\n\n\t\t\tuassert.Equal(t, len(tt.expected), len(page.Items))\n\n\t\t\tfor i, item := range page.Items {\n\t\t\t\tuassert.Equal(t, tt.expected[i].Key, item.Key)\n\t\t\t\tuassert.Equal(t, tt.expected[i].Value, item.Value)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestPager_GetPageByPath(t *testing.T) {\n\t// Create a new AVL tree and populate it with some key-value pairs.\n\ttree := avl.NewTree()\n\tfor i := 0; i \u003c 50; i++ {\n\t\ttree.Set(ufmt.Sprintf(\"key%d\", i), i)\n\t}\n\n\t// Create a new pager.\n\tpager := NewPager(tree, 10, false)\n\n\t// Define test cases.\n\ttests := []struct {\n\t\trawURL       string\n\t\texpectedPage int\n\t\texpectedSize int\n\t}{\n\t\t{\"/r/foo:bar/baz?size=10\u0026page=1\", 1, 10},\n\t\t{\"/r/foo:bar/baz?size=10\u0026page=2\", 2, 10},\n\t\t{\"/r/foo:bar/baz?page=3\", 3, pager.DefaultPageSize},\n\t\t{\"/r/foo:bar/baz?size=20\", 1, 20},\n\t\t{\"/r/foo:bar/baz\", 1, pager.DefaultPageSize},\n\t}\n\n\tfor _, tt := range tests {\n\t\tpage, err := pager.GetPageByPath(tt.rawURL)\n\t\turequire.NoError(t, err, ufmt.Sprintf(\"GetPageByPath(%s) returned error: %v\", tt.rawURL, err))\n\n\t\tuassert.Equal(t, tt.expectedPage, page.PageNumber)\n\t\tuassert.Equal(t, tt.expectedSize, page.PageSize)\n\t}\n}\n\nfunc TestPage_Picker(t *testing.T) {\n\t// Create a new AVL tree and populate it with some key-value pairs.\n\ttree := avl.NewTree()\n\ttree.Set(\"a\", 1)\n\ttree.Set(\"b\", 2)\n\ttree.Set(\"c\", 3)\n\ttree.Set(\"d\", 4)\n\ttree.Set(\"e\", 5)\n\n\t// Create a new pager.\n\tpager := NewPager(tree, 10, false)\n\n\t// Define test cases.\n\ttests := []struct {\n\t\tpageNumber int\n\t\tpageSize   int\n\t\tpath       string\n\t\texpected   string\n\t}{\n\t\t{1, 2, \"/test\", \"**1** | [2](?page=2) | [3](?page=3)\"},\n\t\t{2, 2, \"/test\", \"[1](?page=1) | **2** | [3](?page=3)\"},\n\t\t{3, 2, \"/test\", \"[1](?page=1) | [2](?page=2) | **3**\"},\n\t\t{1, 2, \"/test?foo=bar\", \"**1** | [2](?page=2\u0026foo=bar) | [3](?page=3\u0026foo=bar)\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tpage := pager.GetPageWithSize(tt.pageNumber, tt.pageSize)\n\n\t\tui := page.Picker(tt.path)\n\t\tuassert.Equal(t, tt.expected, ui)\n\t}\n}\n\nfunc TestPager_UI_WithManyPages(t *testing.T) {\n\t// Create a new AVL tree and populate it with many key-value pairs.\n\ttree := avl.NewTree()\n\tfor i := 0; i \u003c 100; i++ {\n\t\ttree.Set(ufmt.Sprintf(\"key%d\", i), i)\n\t}\n\n\t// Create a new pager.\n\tpager := NewPager(tree, 10, false)\n\n\t// Define test cases for a large number of pages.\n\ttests := []struct {\n\t\tpageNumber int\n\t\tpageSize   int\n\t\tpath       string\n\t\texpected   string\n\t}{\n\t\t{1, 10, \"/test\", \"**1** | [2](?page=2) | [3](?page=3) | … | [10](?page=10)\"},\n\t\t{2, 10, \"/test\", \"[1](?page=1) | **2** | [3](?page=3) | [4](?page=4) | … | [10](?page=10)\"},\n\t\t{3, 10, \"/test\", \"[1](?page=1) | [2](?page=2) | **3** | [4](?page=4) | [5](?page=5) | … | [10](?page=10)\"},\n\t\t{4, 10, \"/test\", \"[1](?page=1) | [2](?page=2) | [3](?page=3) | **4** | [5](?page=5) | [6](?page=6) | … | [10](?page=10)\"},\n\t\t{5, 10, \"/test\", \"[1](?page=1) | … | [3](?page=3) | [4](?page=4) | **5** | [6](?page=6) | [7](?page=7) | … | [10](?page=10)\"},\n\t\t{6, 10, \"/test\", \"[1](?page=1) | … | [4](?page=4) | [5](?page=5) | **6** | [7](?page=7) | [8](?page=8) | … | [10](?page=10)\"},\n\t\t{7, 10, \"/test\", \"[1](?page=1) | … | [5](?page=5) | [6](?page=6) | **7** | [8](?page=8) | [9](?page=9) | [10](?page=10)\"},\n\t\t{8, 10, \"/test\", \"[1](?page=1) | … | [6](?page=6) | [7](?page=7) | **8** | [9](?page=9) | [10](?page=10)\"},\n\t\t{9, 10, \"/test\", \"[1](?page=1) | … | [7](?page=7) | [8](?page=8) | **9** | [10](?page=10)\"},\n\t\t{10, 10, \"/test\", \"[1](?page=1) | … | [8](?page=8) | [9](?page=9) | **10**\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tpage := pager.GetPageWithSize(tt.pageNumber, tt.pageSize)\n\n\t\tui := page.Picker(tt.path)\n\t\tuassert.Equal(t, tt.expected, ui)\n\t}\n}\n\nfunc TestPager_ParseQuery(t *testing.T) {\n\t// Create a new AVL tree and populate it with some key-value pairs.\n\ttree := avl.NewTree()\n\ttree.Set(\"a\", 1)\n\ttree.Set(\"b\", 2)\n\ttree.Set(\"c\", 3)\n\ttree.Set(\"d\", 4)\n\ttree.Set(\"e\", 5)\n\n\t// Create a new pager.\n\tpager := NewPager(tree, 10, false)\n\n\t// Define test cases.\n\ttests := []struct {\n\t\trawURL        string\n\t\texpectedPage  int\n\t\texpectedSize  int\n\t\texpectedError bool\n\t}{\n\t\t{\"/r/foo:bar/baz?size=2\u0026page=1\", 1, 2, false},\n\t\t{\"/r/foo:bar/baz?size=3\u0026page=2\", 2, 3, false},\n\t\t{\"/r/foo:bar/baz?size=5\u0026page=3\", 3, 5, false},\n\t\t{\"/r/foo:bar/baz?page=2\", 2, pager.DefaultPageSize, false},\n\t\t{\"/r/foo:bar/baz?size=3\", 1, 3, false},\n\t\t{\"/r/foo:bar/baz\", 1, pager.DefaultPageSize, false},\n\t\t{\"/r/foo:bar/baz?size=0\u0026page=0\", 1, pager.DefaultPageSize, false},\n\t}\n\n\tfor _, tt := range tests {\n\t\tpage, size, err := pager.ParseQuery(tt.rawURL)\n\t\tif tt.expectedError {\n\t\t\tuassert.Error(t, err, ufmt.Sprintf(\"ParseQuery(%s) expected error but got none\", tt.rawURL))\n\t\t} else {\n\t\t\turequire.NoError(t, err, ufmt.Sprintf(\"ParseQuery(%s) returned error: %v\", tt.rawURL, err))\n\t\t\tuassert.Equal(t, tt.expectedPage, page, ufmt.Sprintf(\"ParseQuery(%s) returned page %d, expected %d\", tt.rawURL, page, tt.expectedPage))\n\t\t\tuassert.Equal(t, tt.expectedSize, size, ufmt.Sprintf(\"ParseQuery(%s) returned size %d, expected %d\", tt.rawURL, size, tt.expectedSize))\n\t\t}\n\t}\n}\n\nfunc TestPage_PickerQueryParamPreservation(t *testing.T) {\n\ttree := avl.NewTree()\n\tfor i := 1; i \u003c= 6; i++ {\n\t\ttree.Set(ufmt.Sprintf(\"key%d\", i), i)\n\t}\n\n\tpager := NewPager(tree, 2, false)\n\n\ttests := []struct {\n\t\tname       string\n\t\tpageNumber int\n\t\tpath       string\n\t\texpected   string\n\t}{\n\t\t{\n\t\t\tname:       \"single query param\",\n\t\t\tpageNumber: 1,\n\t\t\tpath:       \"/test?foo=bar\",\n\t\t\texpected:   \"**1** | [2](?page=2\u0026foo=bar) | [3](?page=3\u0026foo=bar)\",\n\t\t},\n\t\t{\n\t\t\tname:       \"multiple query params\",\n\t\t\tpageNumber: 2,\n\t\t\tpath:       \"/test?foo=bar\u0026baz=qux\",\n\t\t\texpected:   \"[1](?page=1\u0026baz=qux\u0026foo=bar) | **2** | [3](?page=3\u0026baz=qux\u0026foo=bar)\",\n\t\t},\n\t\t{\n\t\t\tname:       \"overwrite existing page param\",\n\t\t\tpageNumber: 1,\n\t\t\tpath:       \"/test?param1=value1\u0026page=999\u0026param2=value2\",\n\t\t\texpected:   \"**1** | [2](?page=2\u0026param1=value1\u0026param2=value2) | [3](?page=3\u0026param1=value1\u0026param2=value2)\",\n\t\t},\n\t\t{\n\t\t\tname:       \"empty query string\",\n\t\t\tpageNumber: 2,\n\t\t\tpath:       \"/test\",\n\t\t\texpected:   \"[1](?page=1) | **2** | [3](?page=3)\",\n\t\t},\n\t\t{\n\t\t\tname:       \"query string with only page param\",\n\t\t\tpageNumber: 2,\n\t\t\tpath:       \"/test?page=2\",\n\t\t\texpected:   \"[1](?page=1) | **2** | [3](?page=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\tpage := pager.GetPageWithSize(tt.pageNumber, 2)\n\t\t\tresult := page.Picker(tt.path)\n\t\t\tif result != tt.expected {\n\t\t\t\tt.Errorf(\"\\nwant: %s\\ngot:  %s\", tt.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n"},{"name":"z_filetest.gno","body":"package main\n\nimport (\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/avl/v0/pager\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nfunc main() {\n\t// Create a new AVL tree and populate it with some key-value pairs.\n\tvar id seqid.ID\n\ttree := avl.NewTree()\n\tfor i := 0; i \u003c 42; i++ {\n\t\ttree.Set(id.Next().String(), i)\n\t}\n\n\t// Create a new pager.\n\tpager := pager.NewPager(tree, 7, false)\n\n\tfor pn := -1; pn \u003c 8; pn++ {\n\t\tpage := pager.GetPage(pn)\n\n\t\tprintln(ufmt.Sprintf(\"## Page %d of %d\", page.PageNumber, page.TotalPages))\n\t\tfor idx, item := range page.Items {\n\t\t\tprintln(ufmt.Sprintf(\"- idx=%d key=%s value=%d\", idx, item.Key, item.Value))\n\t\t}\n\t\tprintln(page.Picker(\"/\"))\n\t\tprintln()\n\t}\n}\n\n// Output:\n// ## Page 0 of 6\n// _0_ | [1](?page=1) | [2](?page=2) | … | [6](?page=6)\n//\n// ## Page 0 of 6\n// _0_ | [1](?page=1) | [2](?page=2) | … | [6](?page=6)\n//\n// ## Page 1 of 6\n// - idx=0 key=0000001 value=0\n// - idx=1 key=0000002 value=1\n// - idx=2 key=0000003 value=2\n// - idx=3 key=0000004 value=3\n// - idx=4 key=0000005 value=4\n// - idx=5 key=0000006 value=5\n// - idx=6 key=0000007 value=6\n// **1** | [2](?page=2) | [3](?page=3) | … | [6](?page=6)\n//\n// ## Page 2 of 6\n// - idx=0 key=0000008 value=7\n// - idx=1 key=0000009 value=8\n// - idx=2 key=000000a value=9\n// - idx=3 key=000000b value=10\n// - idx=4 key=000000c value=11\n// - idx=5 key=000000d value=12\n// - idx=6 key=000000e value=13\n// [1](?page=1) | **2** | [3](?page=3) | [4](?page=4) | … | [6](?page=6)\n//\n// ## Page 3 of 6\n// - idx=0 key=000000f value=14\n// - idx=1 key=000000g value=15\n// - idx=2 key=000000h value=16\n// - idx=3 key=000000j value=17\n// - idx=4 key=000000k value=18\n// - idx=5 key=000000m value=19\n// - idx=6 key=000000n value=20\n// [1](?page=1) | [2](?page=2) | **3** | [4](?page=4) | [5](?page=5) | [6](?page=6)\n//\n// ## Page 4 of 6\n// - idx=0 key=000000p value=21\n// - idx=1 key=000000q value=22\n// - idx=2 key=000000r value=23\n// - idx=3 key=000000s value=24\n// - idx=4 key=000000t value=25\n// - idx=5 key=000000v value=26\n// - idx=6 key=000000w value=27\n// [1](?page=1) | [2](?page=2) | [3](?page=3) | **4** | [5](?page=5) | [6](?page=6)\n//\n// ## Page 5 of 6\n// - idx=0 key=000000x value=28\n// - idx=1 key=000000y value=29\n// - idx=2 key=000000z value=30\n// - idx=3 key=0000010 value=31\n// - idx=4 key=0000011 value=32\n// - idx=5 key=0000012 value=33\n// - idx=6 key=0000013 value=34\n// [1](?page=1) | … | [3](?page=3) | [4](?page=4) | **5** | [6](?page=6)\n//\n// ## Page 6 of 6\n// - idx=0 key=0000014 value=35\n// - idx=1 key=0000015 value=36\n// - idx=2 key=0000016 value=37\n// - idx=3 key=0000017 value=38\n// - idx=4 key=0000018 value=39\n// - idx=5 key=0000019 value=40\n// - idx=6 key=000001a value=41\n// [1](?page=1) | … | [4](?page=4) | [5](?page=5) | **6**\n//\n// ## Page 7 of 6\n// [1](?page=1) | … | [5](?page=5) | [6](?page=6) | _7_\n//\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"lXim2vHvjRFbZzNHm4JJfV9rAoTmUwyG8icxhlR+HR1Il2tZsfIe4Tvz7rEGDCxR/8i0sRUIL8bhGKzDY+rgGQ=="}],"memo":""}},{"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":"request_test.gno","body":"package mux\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 TestRequest_GetVar(t *testing.T) {\n\tcases := []struct {\n\t\thandlerPath    string\n\t\treqPath        string\n\t\tgetVarKey      string\n\t\texpectedOutput string\n\t}{\n\n\t\t{\"users/{id}\", \"users/123\", \"id\", \"123\"},\n\t\t{\"users/123\", \"users/123\", \"id\", \"\"},\n\t\t{\"users/{id}\", \"users/123\", \"nonexistent\", \"\"},\n\t\t{\"users/{userId}/posts/{postId}\", \"users/123/posts/456\", \"userId\", \"123\"},\n\t\t{\"users/{userId}/posts/{postId}\", \"users/123/posts/456\", \"postId\", \"456\"},\n\n\t\t// Wildcards\n\t\t{\"*\", \"users/123\", \"*\", \"users/123\"},\n\t\t{\"*\", \"users/123/posts/456\", \"*\", \"users/123/posts/456\"},\n\t\t{\"*\", \"users/123/posts/456/comments/789\", \"*\", \"users/123/posts/456/comments/789\"},\n\t\t{\"users/*\", \"users/john/posts\", \"*\", \"john/posts\"},\n\t\t{\"users/*/comments\", \"users/jane/comments\", \"*\", \"jane/comments\"},\n\t\t{\"api/*/posts/*\", \"api/v1/posts/123\", \"*\", \"v1/posts/123\"},\n\n\t\t// wildcards and parameters\n\t\t{\"api/{version}/*\", \"api/v1/user/settings\", \"version\", \"v1\"},\n\t}\n\tfor _, tt := range cases {\n\t\tname := ufmt.Sprintf(\"%s-%s\", tt.handlerPath, tt.reqPath)\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\treq := \u0026Request{\n\t\t\t\tHandlerPath: tt.handlerPath,\n\t\t\t\tPath:        tt.reqPath,\n\t\t\t}\n\t\t\toutput := req.GetVar(tt.getVarKey)\n\t\t\tuassert.Equal(t, tt.expectedOutput, output,\n\t\t\t\t\"handler: %q, path: %q, key: %q\",\n\t\t\t\ttt.handlerPath, tt.reqPath, tt.getVarKey)\n\t\t})\n\t}\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"},{"name":"router_test.gno","body":"package mux\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestRouter_Render(t *testing.T) {\n\tcases := []struct {\n\t\tlabel          string\n\t\tpath           string\n\t\texpectedOutput string\n\t\tsetupHandler   func(t *testing.T, r *Router)\n\t}{\n\t\t{\n\t\t\tlabel:          \"route with named parameter\",\n\t\t\tpath:           \"hello/Alice\",\n\t\t\texpectedOutput: \"Hello, Alice!\",\n\t\t\tsetupHandler: func(t *testing.T, r *Router) {\n\t\t\t\tr.HandleFunc(\"hello/{name}\", func(rw *ResponseWriter, req *Request) {\n\t\t\t\t\tname := req.GetVar(\"name\")\n\t\t\t\t\tuassert.Equal(t, \"Alice\", name)\n\t\t\t\t\trw.Write(\"Hello, \" + name + \"!\")\n\t\t\t\t})\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tlabel:          \"static route\",\n\t\t\tpath:           \"hi\",\n\t\t\texpectedOutput: \"Hi, earth!\",\n\t\t\tsetupHandler: func(t *testing.T, r *Router) {\n\t\t\t\tr.HandleFunc(\"hi\", func(rw *ResponseWriter, req *Request) {\n\t\t\t\t\tuassert.Equal(t, req.Path, \"hi\")\n\t\t\t\t\trw.Write(\"Hi, earth!\")\n\t\t\t\t})\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tlabel:          \"route with named parameter and query string\",\n\t\t\tpath:           \"hello/foo/bar?foo=bar\u0026baz\",\n\t\t\texpectedOutput: \"foo bar\",\n\t\t\tsetupHandler: func(t *testing.T, r *Router) {\n\t\t\t\tr.HandleFunc(\"hello/{key}/{val}\", func(rw *ResponseWriter, req *Request) {\n\t\t\t\t\tkey := req.GetVar(\"key\")\n\t\t\t\t\tval := req.GetVar(\"val\")\n\t\t\t\t\tuassert.Equal(t, \"foo\", key)\n\t\t\t\t\tuassert.Equal(t, \"bar\", val)\n\t\t\t\t\tuassert.Equal(t, \"hello/foo/bar?foo=bar\u0026baz\", req.RawPath)\n\t\t\t\t\tuassert.Equal(t, \"hello/foo/bar\", req.Path)\n\t\t\t\t\tuassert.Equal(t, \"bar\", req.Query.Get(\"foo\"))\n\t\t\t\t\tuassert.Empty(t, req.Query.Get(\"baz\"))\n\t\t\t\t\trw.Write(key + \" \" + val)\n\t\t\t\t})\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// TODO: finalize how router should behave with double slash in path.\n\t\t\tlabel:          \"double slash in nested route\",\n\t\t\tpath:           \"a/foo//\",\n\t\t\texpectedOutput: \"test foo\",\n\t\t\tsetupHandler: func(t *testing.T, r *Router) {\n\t\t\t\tr.HandleFunc(\"a/{key}\", func(rw *ResponseWriter, req *Request) {\n\t\t\t\t\t// Assert not called\n\t\t\t\t\tuassert.False(t, true, \"unexpected handler called\")\n\t\t\t\t})\n\n\t\t\t\tr.HandleFunc(\"a/{key}/{val}/\", func(rw *ResponseWriter, req *Request) {\n\t\t\t\t\tkey := req.GetVar(\"key\")\n\t\t\t\t\tval := req.GetVar(\"val\")\n\t\t\t\t\tuassert.Equal(t, key, \"foo\")\n\t\t\t\t\tuassert.Empty(t, val)\n\t\t\t\t\trw.Write(\"test \" + key)\n\t\t\t\t})\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tlabel:          \"wildcard in route\",\n\t\t\tpath:           \"hello/Alice/Bob\",\n\t\t\texpectedOutput: \"Matched: Alice/Bob\",\n\t\t\tsetupHandler: func(t *testing.T, r *Router) {\n\t\t\t\tr.HandleFunc(\"hello/*\", func(rw *ResponseWriter, req *Request) {\n\t\t\t\t\tpath := req.GetVar(\"*\")\n\t\t\t\t\tuassert.Equal(t, \"Alice/Bob\", path)\n\t\t\t\t\tuassert.Equal(t, \"hello/Alice/Bob\", req.Path)\n\t\t\t\t\trw.Write(\"Matched: \" + path)\n\t\t\t\t})\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tlabel:          \"wildcard in route with query string\",\n\t\t\tpath:           \"hello/Alice/Bob?foo=bar\",\n\t\t\texpectedOutput: \"Matched: Alice/Bob\",\n\t\t\tsetupHandler: func(t *testing.T, r *Router) {\n\t\t\t\tr.HandleFunc(\"hello/*\", func(rw *ResponseWriter, req *Request) {\n\t\t\t\t\tpath := req.GetVar(\"*\")\n\t\t\t\t\tuassert.Equal(t, \"Alice/Bob\", path)\n\t\t\t\t\tuassert.Equal(t, \"hello/Alice/Bob?foo=bar\", req.RawPath)\n\t\t\t\t\tuassert.Equal(t, \"hello/Alice/Bob\", req.Path)\n\t\t\t\t\tuassert.Equal(t, \"bar\", req.Query.Get(\"foo\"))\n\t\t\t\t\trw.Write(\"Matched: \" + path)\n\t\t\t\t})\n\t\t\t},\n\t\t},\n\t\t// TODO: {\"hello\", \"Hello, world!\"},\n\t\t// TODO: hello/, /hello, hello//Alice, hello/Alice/, hello/Alice/Bob, etc\n\t}\n\tfor _, tt := range cases {\n\t\tt.Run(tt.label, func(t *testing.T) {\n\t\t\trouter := NewRouter()\n\t\t\ttt.setupHandler(t, router)\n\t\t\toutput := router.Render(tt.path)\n\t\t\tif output != tt.expectedOutput {\n\t\t\t\tt.Errorf(\"Expected output %q, but got %q\", tt.expectedOutput, output)\n\t\t\t}\n\t\t})\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"DE7cw4UAjs7PE9kDndpi0/8wsdBCFPD7Zb976rlq4LU5jOjLEcImTzQ8le49aTkDrvqevukMkWP28WG/qP2ccg=="}],"memo":""}},{"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"},{"name":"ownable_test.gno","body":"package ownable\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\")\n\tbob   = testutils.TestAddress(\"bob\")\n)\n\nfunc TestNewWithAddress(cur realm, t *testing.T) {\n\to := NewWithAddress(alice)\n\n\tgot := o.Owner()\n\tuassert.Equal(t, got, alice)\n}\n\nfunc TestTransferOwnership(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\to := NewWithAddress(alice)\n\tfunc(cur realm) {\n\t\terr := o.TransferOwnership(0, cur, bob)\n\t\turequire.NoError(t, err)\n\t}(cross(cur))\n\n\tgot := o.Owner()\n\tuassert.Equal(t, got, bob)\n}\n\nfunc TestTransferOwnershipUnauthorized(cur realm, t *testing.T) {\n\to := NewWithAddress(alice)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tfunc(cur realm) {\n\t\tuassert.ErrorContains(t, o.TransferOwnership(0, cur, bob), ErrUnauthorized.Error())\n\t}(cross(cur))\n}\n\nfunc TestDropOwnership(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\to := NewWithAddress(alice)\n\tfunc(cur realm) {\n\t\terr := o.DropOwnership(0, cur)\n\t\turequire.NoError(t, err, \"DropOwnership failed\")\n\t}(cross(cur))\n\n\towner := o.Owner()\n\tuassert.Empty(t, owner, \"owner should be empty\")\n}\n\nfunc TestDropOwnershipUnauthorized(cur realm, t *testing.T) {\n\to := NewWithAddress(alice)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tfunc(cur realm) {\n\t\tuassert.ErrorContains(t, o.DropOwnership(0, cur), ErrUnauthorized.Error())\n\t}(cross(cur))\n}\n\nfunc TestOwnedBy(cur realm, t *testing.T) {\n\to := NewWithAddress(alice)\n\tuassert.True(t, o.OwnedBy(alice))\n\tuassert.False(t, o.OwnedBy(bob))\n}\n\nfunc TestAssertOwnedBy(cur realm, t *testing.T) {\n\to := NewWithAddress(alice)\n\n\t// Should not panic.\n\to.AssertOwnedBy(alice)\n\n\tuassert.PanicsWithMessage(t, cur, ErrUnauthorized.Error(), func() {\n\t\to.AssertOwnedBy(bob)\n\t})\n}\n\nfunc TestErrInvalidAddress(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\to := NewWithAddress(alice)\n\tfunc(cur realm) {\n\t\terr := o.TransferOwnership(0, cur, \"\")\n\t\tuassert.ErrorContains(t, err, ErrInvalidAddress.Error())\n\n\t\terr = o.TransferOwnership(0, cur, \"10000000001000000000100000000010000000001000000000\")\n\t\tuassert.ErrorContains(t, err, ErrInvalidAddress.Error())\n\t}(cross(cur))\n}\n\nfunc TestNilReceiver(cur realm, t *testing.T) {\n\tvar o *Ownable\n\n\towner := o.Owner()\n\tif owner != address(\"\") {\n\t\tt.Errorf(\"expected empty address but got %v\", owner)\n\t}\n\n\tisOwner := o.OwnedBy(alice)\n\tuassert.False(t, isOwner)\n\n\tdefer func() {\n\t\tr := recover()\n\t\tif r == nil {\n\t\t\tt.Error(\"expected panic but got none\")\n\t\t}\n\t\tif r != ErrUnauthorized {\n\t\t\tt.Errorf(\"expected ErrUnauthorized but got %v\", r)\n\t\t}\n\t}()\n\to.AssertOwnedBy(alice)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"jGlCBy8R92O7d1J34ks7Nnc6aK4evsgglZi7FWYy8YpyL7P2UK7OpAVsq9U6FB3zrguFk2UXyuAhWwNjMGlH3w=="}],"memo":""}},{"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":"fqname_test.gno","body":"package fqname\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\tinput           string\n\t\texpectedPkgPath string\n\t\texpectedName    string\n\t}{\n\t\t{\"gno.land/p/nt/avl/v0.Tree\", \"gno.land/p/nt/avl/v0\", \"Tree\"},\n\t\t{\"gno.land/p/nt/avl/v0\", \"gno.land/p/nt/avl/v0\", \"\"},\n\t\t{\"gno.land/p/nt/avl/v0.Tree.Node\", \"gno.land/p/nt/avl/v0\", \"Tree.Node\"},\n\t\t{\"gno.land/p/nt/avl/v0/nested.Package.Func\", \"gno.land/p/nt/avl/v0/nested\", \"Package.Func\"},\n\t\t{\"path/filepath.Split\", \"path/filepath\", \"Split\"},\n\t\t{\"path.Split\", \"path\", \"Split\"},\n\t\t{\"path/filepath\", \"path/filepath\", \"\"},\n\t\t{\"path\", \"path\", \"\"},\n\t\t{\"\", \"\", \"\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tpkgpath, name := Parse(tt.input)\n\t\tuassert.Equal(t, tt.expectedPkgPath, pkgpath, \"Package path did not match\")\n\t\tuassert.Equal(t, tt.expectedName, name, \"Name did not match\")\n\t}\n}\n\nfunc TestConstruct(t *testing.T) {\n\ttests := []struct {\n\t\tpkgpath  string\n\t\tname     string\n\t\texpected string\n\t}{\n\t\t{\"gno.land/r/demo/foo20\", \"Token\", \"gno.land/r/demo/foo20.Token\"},\n\t\t{\"gno.land/r/demo/foo20\", \"\", \"gno.land/r/demo/foo20\"},\n\t\t{\"path\", \"\", \"path\"},\n\t\t{\"path\", \"Split\", \"path.Split\"},\n\t\t{\"path/filepath\", \"\", \"path/filepath\"},\n\t\t{\"path/filepath\", \"Split\", \"path/filepath.Split\"},\n\t\t{\"\", \"JustName\", \".JustName\"},\n\t\t{\"\", \"\", \"\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tresult := Construct(tt.pkgpath, tt.name)\n\t\tuassert.Equal(t, tt.expected, result, \"Constructed FQName did not match expected\")\n\t}\n}\n\nfunc TestRenderLink(t *testing.T) {\n\ttests := []struct {\n\t\tpkgPath  string\n\t\tslug     string\n\t\texpected string\n\t}{\n\t\t{\"gno.land/p/nt/avl/v0\", \"Tree\", \"[gno.land/p/nt/avl/v0](/p/nt/avl/v0).Tree\"},\n\t\t{\"gno.land/p/nt/avl/v0\", \"\", \"[gno.land/p/nt/avl/v0](/p/nt/avl/v0)\"},\n\t\t{\"github.com/a/b\", \"C\", \"github.com/a/b.C\"},\n\t\t{\"example.com/pkg\", \"Func\", \"example.com/pkg.Func\"},\n\t\t{\"gno.land/r/demo/foo20\", \"Token\", \"[gno.land/r/demo/foo20](/r/demo/foo20).Token\"},\n\t\t{\"gno.land/r/demo/foo20\", \"\", \"[gno.land/r/demo/foo20](/r/demo/foo20)\"},\n\t\t{\"\", \"\", \"\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tresult := RenderLink(tt.pkgPath, tt.slug)\n\t\tuassert.Equal(t, tt.expected, result, \"Rendered link did not match expected\")\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/fqname/v0\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"6/f9L9T1YqAJqLWmGI+v5X0ZliXCrSbAwFEcD0lDUidSZveR9E650aR2+w+qvPJBVXhlc+eH0/xlyuTiCr3JhQ=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"grc20reg","path":"gno.land/r/demo/defi/grc20reg","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/demo/defi/grc20reg\"\ngno = \"0.9\"\n"},{"name":"grc20reg.gno","body":"package grc20reg\n\nimport (\n\t\"chain\"\n\t\"strings\"\n\n\t\"gno.land/p/demo/tokens/grc20\"\n\t\"gno.land/p/moul/md\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/avl/v0/rotree\"\n\t\"gno.land/p/nt/fqname/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/demo/grc20reg:\" + 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"},{"name":"grc20reg_test.gno","body":"package grc20reg\n\nimport (\n\t\"chain\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/demo/tokens/grc20\"\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\nfunc TestRegistry(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/foo\"))\n\ttoken, ledger := grc20.NewToken(\"TestToken\", \"TST\", 4, 0, cur)\n\tledger.Mint(cur.Address(), 1234567)\n\t// register\n\tkey := Register(cross(cur), token, \"mySlug\")\n\tregToken := Get(key)\n\turequire.True(t, regToken != nil, \"expected to find a token\") // fixme: use urequire.NotNil\n\turequire.Equal(t, regToken.GetSymbol(), \"TST\")\n\n\texpected := `- **TestToken** - [gno.land/r/demo/foo](/r/demo/foo).TST - [info](/r/demo/grc20reg:gno.land/r/demo/foo.TST)\n`\n\tgot := Render(\"\")\n\turequire.True(t, strings.Contains(got, expected))\n\t// 404\n\tinvalidToken := Get(\"0xdeadbeef\")\n\turequire.True(t, invalidToken == nil)\n\n\tgot = Render(\"\")\n\turequire.True(t, strings.Contains(got, expected))\n\n\texpected = `# TestToken\n- symbol: **TST**\n- realm: [gno.land/r/demo/foo](/r/demo/foo).TST\n- decimals: 4\n- total supply: 1234567\n`\n\tgot = Render(key)\n\turequire.Equal(t, expected, got)\n\n\t// The registry keys by rlmPath.symbol, so a second token with the same\n\t// symbol in the same realm is rejected even though its Token.ID() differs\n\t// (distinct trailing sequence id). See TestRegisterRejectsOverwrite.\n\tsecond, _ := grc20.NewToken(\"Second\", \"TST\", 4, 1, cur)\n\turequire.NotEqual(t, token.ID(), second.ID()) // ids are decoupled from symbol\n\turequire.AbortsContains(t, cur, \"token already registered\", func() {\n\t\tRegister(cross(cur), second, \"\")\n\t})\n}\n\n// TestRegistryLookupGrantsNoSpendAuthority pins the property that replaced the\n// former Transfer/Approve/TransferFrom wrappers: a registry lookup yields a\n// *Token, and a *Token alone carries no authority to debit anybody. The\n// frame-relative teller is reachable only from the ledger, which never leaves\n// the token's own realm, so this realm cannot act on behalf of its caller —\n// that shape was the confused deputy.\n//\n// The supported route for a realm that must move a user's funds is the one\n// exercised below: the user grants an allowance, and the realm spends it as\n// itself through a RealmTeller, which is eagerly bound to its own address.\nfunc TestRegistryLookupGrantsNoSpendAuthority(cur realm, t *testing.T) {\n\tconst (\n\t\ttokenPath    = \"gno.land/r/demo/token\"\n\t\tconsumerPath = \"gno.land/r/demo/grc20reg_consumer\"\n\t)\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\tconsumer := chain.PackageAddress(consumerPath)\n\n\ttesting.SetRealm(testing.NewCodeRealm(tokenPath))\n\ttoken, ledger := grc20.NewToken(\"TestToken\", \"TST\", 4, 0, cur)\n\turequire.NoError(t, ledger.Mint(alice, 1_000))\n\ttokenKey := Register(cross(cur), token, \"\")\n\tuassert.Equal(t, \"TestToken\", MustGet(tokenKey).GetName())\n\tuassert.Equal(t, int64(1_000), MustGet(tokenKey).BalanceOf(alice))\n\tuassert.Equal(t, int64(0), MustGet(tokenKey).Allowance(alice, consumer))\n\n\t// alice approves the consumer realm on the token. On chain she does this\n\t// through the token realm's own entry point; the ledger stands in for it.\n\turequire.NoError(t, ledger.ImpersonateTeller(alice).Approve(0, cur, consumer, 300))\n\tuassert.Equal(t, int64(300), MustGet(tokenKey).Allowance(alice, consumer))\n\n\t// The consumer spends that allowance as ITSELF, over a token it found in\n\t// the registry and does not own. The actor is fixed at construction, so it\n\t// cannot be redirected by whoever calls in.\n\ttesting.SetRealm(testing.NewCodeRealm(consumerPath))\n\tspender := MustGet(tokenKey).RealmTeller(0, cur)\n\turequire.NoError(t, spender.TransferFrom(0, cur, alice, bob, 200))\n\tuassert.Equal(t, int64(800), MustGet(tokenKey).BalanceOf(alice))\n\tuassert.Equal(t, int64(200), MustGet(tokenKey).BalanceOf(bob))\n\tuassert.Equal(t, int64(100), MustGet(tokenKey).Allowance(alice, consumer))\n\n\t// Beyond the allowance it stops: the balance is not reachable directly.\n\tuassert.ErrorContains(t,\n\t\tspender.TransferFrom(0, cur, alice, bob, 101),\n\t\t\"insufficient allowance\")\n\tuassert.Equal(t, int64(800), MustGet(tokenKey).BalanceOf(alice))\n\tuassert.Equal(t, int64(200), MustGet(tokenKey).BalanceOf(bob))\n}\n\n// TestRegistryConsumerCannotRedirectItsActor is the negative half of the\n// property above: a realm holding a registered token pays out of its own\n// balance, not the signing user's. The actor is bound at construction, so the\n// transaction's origin caller has no bearing on who is debited — which is what\n// made the frame-relative teller in a foreign realm a phishing primitive.\nfunc TestRegistryConsumerCannotRedirectItsActor(cur realm, t *testing.T) {\n\tconst (\n\t\ttokenPath    = \"gno.land/r/demo/token_actor_binding\"\n\t\tconsumerPath = \"gno.land/r/demo/grc20reg_actor_consumer\"\n\t)\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\tconsumer := chain.PackageAddress(consumerPath)\n\n\ttesting.SetRealm(testing.NewCodeRealm(tokenPath))\n\ttoken, ledger := grc20.NewToken(\"ActorBinding\", \"ACTB\", 4, 0, cur)\n\turequire.NoError(t, ledger.Mint(alice, 1_000))\n\turequire.NoError(t, ledger.Mint(consumer, 500))\n\ttokenKey := Register(cross(cur), token, \"\")\n\n\t// alice signs the transaction, and holds a balance the consumer would love\n\t// to spend. The consumer pays out of its own instead.\n\ttesting.SetOriginCaller(alice)\n\ttesting.SetRealm(testing.NewCodeRealm(consumerPath))\n\turequire.NoError(t, MustGet(tokenKey).RealmTeller(0, cur).Transfer(0, cur, bob, 100))\n\tuassert.Equal(t, int64(1_000), MustGet(tokenKey).BalanceOf(alice))\n\tuassert.Equal(t, int64(400), MustGet(tokenKey).BalanceOf(consumer))\n\tuassert.Equal(t, int64(100), MustGet(tokenKey).BalanceOf(bob))\n}\n\nfunc TestRegisterRejectsOverwrite(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/grc20reg_overwrite\"))\n\ttoken, ledger := grc20.NewToken(\"Bar\", \"BAR\", 4, 0, cur)\n\tledger.Mint(cur.Address(), 11)\n\tkey := Register(cross(cur), token, \"\")\n\n\turequire.Equal(t, \"BAR\", Get(key).GetSymbol())\n\turequire.Equal(t, int64(11), Get(key).BalanceOf(cur.Address()))\n\n\treplacement, _ := grc20.NewToken(\"Replacement\", \"BAR\", 6, 0, cur)\n\turequire.AbortsContains(t, cur, \"token already registered\", func() {\n\t\tRegister(cross(cur), replacement, \"\")\n\t})\n}\n\nfunc TestRegisterRejectsAliasedTokenPaths(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/grc20reg_alias\"))\n\ttoken, _ := grc20.NewToken(\"Aliased Token\", \"ALIAS\", 4, 0, cur)\n\tRegister(cross(cur), token, \"first\")\n\n\turequire.AbortsContains(t, cur, \"token already registered\", func() {\n\t\tRegister(cross(cur), token, \"second\")\n\t})\n}\n\nfunc TestRegisterRejectsTokenFromDifferentRealm(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/grc20reg_id_source\"))\n\ttoken, _ := grc20.NewToken(\"Mismatch Token\", \"MISMATCH\", 4, 0, cur)\n\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/grc20reg_id_target\"))\n\turequire.AbortsContains(t, cur, \"token must be registered from its own realm\", func() {\n\t\tRegister(cross(cur), token, \"\")\n\t})\n}\n\nfunc TestValidateSlug(cur realm, t *testing.T) {\n\t// Valid slugs — should not panic\n\tvalid := []string{\"mytoken\", \"my-token\", \"my_token\", \"Token123\", \"a\", \"A-B_c\", strings.Repeat(\"a\", maxSlugLen)}\n\tfor _, slug := range valid {\n\t\tvalidateSlug(slug) // no panic = pass\n\t}\n}\n\nfunc TestValidateSlugPanicsOnTooLong(cur realm, t *testing.T) {\n\tdefer func() { recover() }()\n\tvalidateSlug(strings.Repeat(\"a\", maxSlugLen+1))\n\tt.Errorf(\"should have panicked\")\n}\n\nfunc TestValidateSlugPanicsOnSpace(cur realm, t *testing.T) {\n\tdefer func() { recover() }()\n\tvalidateSlug(\"has space\")\n\tt.Errorf(\"should have panicked\")\n}\n\nfunc TestValidateSlugPanicsOnDot(cur realm, t *testing.T) {\n\tdefer func() { recover() }()\n\tvalidateSlug(\"has.dot\")\n\tt.Errorf(\"should have panicked\")\n}\n\nfunc TestValidateSlugPanicsOnSlash(cur realm, t *testing.T) {\n\tdefer func() { recover() }()\n\tvalidateSlug(\"has/slash\")\n\tt.Errorf(\"should have panicked\")\n}\n\nfunc TestValidateSlugPanicsOnBrackets(cur realm, t *testing.T) {\n\tdefer func() { recover() }()\n\tvalidateSlug(\"[brackets]\")\n\tt.Errorf(\"should have panicked\")\n}\n\nfunc TestValidateSlugPanicsOnParens(cur realm, t *testing.T) {\n\tdefer func() { recover() }()\n\tvalidateSlug(\"(parens)\")\n\tt.Errorf(\"should have panicked\")\n}\n\nfunc TestValidateSlugPanicsOnInjection(cur realm, t *testing.T) {\n\tdefer func() { recover() }()\n\tvalidateSlug(`) [Claim](https://evil.com`)\n\tt.Errorf(\"should have panicked\")\n}\n\nfunc TestRegisterRejectsNilToken(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/grc20reg_nil\"))\n\turequire.AbortsContains(t, cur, \"nil token\", func() {\n\t\tRegister(cross(cur), nil, \"\")\n\t})\n}\n\n// TestWrappersBindActorToCallingRealm pins the property that makes the write\n// wrappers safe: they are non-crossing, so `rlm` reaches RealmTeller as the\n// caller's own live token and the debit lands on the caller. A crossing wrapper\n// would mint a fresh `cur` for grc20reg and spend the registry's balance\n// instead, which is why the convention is not a stylistic choice.\n//\n// Both the consumer and the registry hold a balance, so whichever one is\n// debited is observable rather than inferred.\nfunc TestWrappersBindActorToCallingRealm(cur realm, t *testing.T) {\n\tconst (\n\t\ttokenPath    = \"gno.land/r/demo/token_wrapper_actor\"\n\t\tconsumerPath = \"gno.land/r/demo/grc20reg_wrapper_consumer\"\n\t)\n\tbob := testutils.TestAddress(\"bob\")\n\tconsumer := chain.PackageAddress(consumerPath)\n\tregistry := chain.PackageAddress(\"gno.land/r/demo/defi/grc20reg\")\n\n\ttesting.SetRealm(testing.NewCodeRealm(tokenPath))\n\ttoken, ledger := grc20.NewToken(\"WrapperActor\", \"WRPA\", 4, 0, cur)\n\turequire.NoError(t, ledger.Mint(consumer, 1_000))\n\turequire.NoError(t, ledger.Mint(registry, 1_000))\n\ttokenKey := Register(cross(cur), token, \"\")\n\n\ttesting.SetRealm(testing.NewCodeRealm(consumerPath))\n\tTransfer(0, cur, tokenKey, bob, 100)\n\n\tuassert.Equal(t, int64(900), MustGet(tokenKey).BalanceOf(consumer))\n\tuassert.Equal(t, int64(1_000), MustGet(tokenKey).BalanceOf(registry))\n\tuassert.Equal(t, int64(100), MustGet(tokenKey).BalanceOf(bob))\n}\n\n// TestWrapperActorIgnoresSigningUser is the negative half: the signing user has\n// a balance the calling realm would like to spend, and does not lose it. The\n// actor comes from rlm.Address(), so the transaction's origin has no say in who\n// pays — a hub cannot be induced to debit its caller's caller.\nfunc TestWrapperActorIgnoresSigningUser(cur realm, t *testing.T) {\n\tconst (\n\t\ttokenPath    = \"gno.land/r/demo/token_wrapper_origin\"\n\t\tconsumerPath = \"gno.land/r/demo/grc20reg_wrapper_origin_consumer\"\n\t)\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\tconsumer := chain.PackageAddress(consumerPath)\n\n\ttesting.SetRealm(testing.NewCodeRealm(tokenPath))\n\ttoken, ledger := grc20.NewToken(\"WrapperOrigin\", \"WRPO\", 4, 0, cur)\n\turequire.NoError(t, ledger.Mint(alice, 1_000))\n\turequire.NoError(t, ledger.Mint(consumer, 500))\n\ttokenKey := Register(cross(cur), token, \"\")\n\n\ttesting.SetOriginCaller(alice)\n\ttesting.SetRealm(testing.NewCodeRealm(consumerPath))\n\tTransfer(0, cur, tokenKey, bob, 100)\n\n\tuassert.Equal(t, int64(1_000), MustGet(tokenKey).BalanceOf(alice))\n\tuassert.Equal(t, int64(400), MustGet(tokenKey).BalanceOf(consumer))\n}\n\n// TestTransferFromSpendsAllowanceGrantedToCallingRealm records the semantic\n// shift that comes with binding the actor to the caller: the owner must have\n// approved the CALLING REALM, not the signing user. An allowance granted to\n// anyone else does not authorize the wrapper.\nfunc TestTransferFromSpendsAllowanceGrantedToCallingRealm(cur realm, t *testing.T) {\n\tconst (\n\t\ttokenPath    = \"gno.land/r/demo/token_wrapper_allowance\"\n\t\tconsumerPath = \"gno.land/r/demo/grc20reg_wrapper_allowance_consumer\"\n\t)\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\tconsumer := chain.PackageAddress(consumerPath)\n\n\ttesting.SetRealm(testing.NewCodeRealm(tokenPath))\n\ttoken, ledger := grc20.NewToken(\"WrapperAllowance\", \"WRPL\", 4, 0, cur)\n\turequire.NoError(t, ledger.Mint(alice, 1_000))\n\ttokenKey := Register(cross(cur), token, \"\")\n\n\t// No allowance yet: the wrapper cannot touch alice's balance.\n\ttesting.SetRealm(testing.NewCodeRealm(consumerPath))\n\tuassert.PanicsContains(t, cur, \"insufficient allowance\", func() {\n\t\tTransferFrom(0, cur, tokenKey, alice, bob, 100)\n\t})\n\tuassert.Equal(t, int64(1_000), MustGet(tokenKey).BalanceOf(alice))\n\n\t// alice approves the consuming realm itself, and only then does it work.\n\turequire.NoError(t, ledger.Approve(alice, consumer, 100))\n\n\ttesting.SetRealm(testing.NewCodeRealm(consumerPath))\n\tTransferFrom(0, cur, tokenKey, alice, bob, 100)\n\tuassert.Equal(t, int64(900), MustGet(tokenKey).BalanceOf(alice))\n\tuassert.Equal(t, int64(100), MustGet(tokenKey).BalanceOf(bob))\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"FtyHXMfRMc/a/UVwiz7Od/wej6vFZAIuU2zlb+KYmEVklVrpxLjeqmtwlAaw3JYgrXxxmFrmFvQANV6dyJRDCg=="}],"memo":""}},{"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/demo/tokens/grc20\"\n\t\"gno.land/p/moul/md\"\n\t\"gno.land/p/nt/avl/v0\"\n\tp \"gno.land/p/nt/avl/v0/pager\"\n\t\"gno.land/p/nt/avl/v0/rotree\"\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/demo/defi/grc20reg\"\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"},{"name":"grc20factory_test.gno","body":"package grc20factory\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/ufmt/v0\"\n)\n\nfunc TestReadOnlyPublicMethods(cur realm, t *testing.T) {\n\tadmin := testutils.TestAddress(\"admin\")\n\tbob := testutils.TestAddress(\"bob\")\n\tcarl := testutils.TestAddress(\"carl\")\n\n\ttype test struct {\n\t\tname    string\n\t\tbalance int64\n\t\tfn      func() int64\n\t}\n\n\tcheckBalances := func(step string, totSup, balAdm, balBob, allowAdmBob, balCarl int64) {\n\t\ttests := []test{\n\t\t\t{\"TotalSupply\", totSup, func() int64 { return TotalSupply(\"FOO\") }},\n\t\t\t{\"BalanceOf(admin)\", balAdm, func() int64 { return BalanceOf(\"FOO\", admin) }},\n\t\t\t{\"BalanceOf(bob)\", balBob, func() int64 { return BalanceOf(\"FOO\", bob) }},\n\t\t\t{\"Allowance(admin, bob)\", allowAdmBob, func() int64 { return Allowance(\"FOO\", admin, bob) }},\n\t\t\t{\"BalanceOf(carl)\", balCarl, func() int64 { return BalanceOf(\"FOO\", carl) }},\n\t\t}\n\t\tfor _, tc := range tests {\n\t\t\treason := ufmt.Sprintf(\"%s.%s - %s\", step, tc.name, \"balances do not match\")\n\t\t\tuassert.Equal(t, tc.balance, tc.fn(), reason)\n\t\t}\n\t}\n\n\t// admin creates FOO and BAR.\n\ttesting.SetOriginCaller(admin)\n\tNewWithAdmin(cross(cur), \"Foo\", \"FOO\", 3, 1_111_111_000, 5_555, admin)\n\tNewWithAdmin(cross(cur), \"Bar\", \"BAR\", 3, 2_222_000, 6_666, admin)\n\tuassert.Equal(t, Bank(\"FOO\").ID(), \"gno.land/r/demo/defi/grc20factory.FOO.0000001\")\n\tuassert.Equal(t, Bank(\"BAR\").ID(), \"gno.land/r/demo/defi/grc20factory.BAR.0000002\")\n\tcheckBalances(\"step1\", 1_111_111_000, 1_111_111_000, 0, 0, 0)\n\n\t// admin mints to bob.\n\tmustGetInstance(\"FOO\").ledger.Mint(bob, 333_333_000)\n\tcheckBalances(\"step2\", 1_444_444_000, 1_111_111_000, 333_333_000, 0, 0)\n\n\t// carl uses the faucet.\n\ttesting.SetOriginCaller(carl)\n\tFaucet(cross(cur), \"FOO\")\n\tcheckBalances(\"step3\", 1_444_449_555, 1_111_111_000, 333_333_000, 0, 5_555)\n\n\t// admin gives to bob some allowance.\n\ttesting.SetOriginCaller(admin)\n\tApprove(cross(cur), \"FOO\", bob, 1_000_000)\n\tcheckBalances(\"step4\", 1_444_449_555, 1_111_111_000, 333_333_000, 1_000_000, 5_555)\n\n\t// bob uses a part of the allowance.\n\ttesting.SetOriginCaller(bob)\n\tTransferFrom(cross(cur), \"FOO\", admin, carl, 400_000)\n\tcheckBalances(\"step5\", 1_444_449_555, 1_110_711_000, 333_333_000, 600_000, 405_555)\n\n\t// bob uses a part of the allowance.\n\ttesting.SetOriginCaller(bob)\n\tTransferFrom(cross(cur), \"FOO\", admin, carl, 600_000)\n\tcheckBalances(\"step6\", 1_444_449_555, 1_110_111_000, 333_333_000, 0, 1_005_555)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"DkOZMns1T3efPI2BEEaGaNWUtJffgGvLZQFqUU6kJkxxwMUmINEDB6SoKlx4O0A7r8R++mXLVR9gb6xmpdvpSg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"panictoerr","path":"gno.land/p/aeddi/panictoerr","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/aeddi/panictoerr\"\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"},{"name":"panictoerr_test.gno","body":"package panictoerr_test\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\tpte \"gno.land/p/aeddi/panictoerr\"\n\t\"gno.land/p/nt/uassert/v0\"\n\tgrc20 \"gno.land/r/demo/defi/grc20factory\"\n)\n\n// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\n\n// Test PanicToError with different types as panic value.\nfunc TestSimplePanicToError(t *testing.T) {\n\terr := pte.PanicToError(func() {\n\t\tpanic(\"string\")\n\t})\n\tuassert.Equal(t, err.Error(), \"string\")\n\n\terr = pte.PanicToError(func() {\n\t\tpanic(errors.New(\"error\"))\n\t})\n\tuassert.Equal(t, err.Error(), \"error\")\n\n\terr = pte.PanicToError(func() {\n\t\tpanic(42)\n\t})\n\tuassert.Equal(t, err.Error(), \"42\")\n}\n\nfunc TestRealmPanicToError(cur realm, t *testing.T) {\n\t// Set a test realm to be able to call a realm.\n\ttestRealm := testing.NewCodeRealm(\"gno.land/r/aeddi/panictoerr/test\")\n\ttesting.SetRealm(testRealm)\n\n\tconst message = \"token instance does not exist\"\n\tvar err error\n\n\t// Define a panicking function (local panic; does not cross any\n\t// realm boundary). Under the unified declaring-realm borrow,\n\t// calling grc20.Bank() would borrow into /r/demo/defi/grc20factory\n\t// and any panic there would cross a realm boundary, becoming an\n\t// abort catchable only by revive() — see the `aborting` case\n\t// below. To exercise the pure recover() path, panic locally.\n\tpanicking := func() {\n\t\tpanic(message)\n\t}\n\n\t// panicking function should panic.\n\tuassert.PanicsWithMessage(t, cur, message, panicking)\n\n\t// panicking function should panic when wrapped in AbortToError.\n\tuassert.PanicsWithMessage(t, cur, message, func() { pte.AbortToError(panicking) })\n\n\t// panicking function should not panic when wrapped in PanicToError.\n\tuassert.NotPanics(\n\t\tt, cur,\n\t\tfunc() { err = pte.PanicToError(panicking) },\n\t\t\"panicking function should not panic when wrapped in PanicToError\",\n\t)\n\tuassert.Equal(t, err.Error(), message)\n\n\t// panicking function should not panic when wrapped in PanicAbortToError.\n\tuassert.NotPanics(\n\t\tt, cur,\n\t\tfunc() { err = pte.PanicAbortToError(panicking) },\n\t\t\"panicking function should not panic when wrapped in PanicAbortToError\",\n\t)\n\tuassert.Equal(t, err.Error(), message)\n\n\t// Define an aborting function (crossing).\n\taborting := func() {\n\t\tgrc20.Faucet(cross(cur), \"unknown\")\n\t}\n\n\t// aborting function should abort.\n\tuassert.AbortsWithMessage(t, cur, message, aborting)\n\n\t// aborting function should abort when wrapped in PanicToError.\n\tuassert.AbortsWithMessage(t, cur, message, func() { pte.PanicToError(aborting) })\n\n\t// aborting function should not abort when wrapped in AbortToError.\n\tuassert.NotAborts(\n\t\tt, cur,\n\t\tfunc() { err = pte.AbortToError(aborting) },\n\t\t\"aborting function should not abort when wrapped in AbortToError\",\n\t)\n\tuassert.Equal(t, err.Error(), message)\n\n\t// aborting function should not abort when wrapped in PanicAbortToError.\n\tuassert.NotAborts(\n\t\tt, cur,\n\t\tfunc() { err = pte.PanicAbortToError(aborting) },\n\t\t\"aborting function should not abort when wrapped in PanicAbortToError\",\n\t)\n\tuassert.Equal(t, err.Error(), message)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"8uK0daI2h1ddKcAU/LevwC1CvShnQ3ru1mjlcZpnM1ABk++2chiVqH7vc5GxkPyCxrM4uHSDxekiMDiiTDvetg=="}],"memo":""}},{"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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"yLqgRuMxNYIxYKkeJaHUJTtKHORDuP6DMFYLTlJPDw0g4x3pfmtI6Co5R0TrsDlhoBB45U4aYOLqcfrILDor4g=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"blog","path":"gno.land/p/demo/blog","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":"blog_test.gno","body":"package blog\n\n// TODO: add generic tests here.\n//       right now, you can checkout r/gnoland/blog/*_test.gno.\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/demo/blog\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"LnNPKMpM6Je+Sx+tdo5EO5pPFakOgsi4JyoJRFIm2sgCcy6zVpegzHiAXxFOTiyITNizbIGVN3cZYWFQVc0C3Q=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"agent","path":"gno.land/p/demo/gnorkle/agent","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/gnorkle/agent\"\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"},{"name":"whitelist_test.gno","body":"package agent_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/demo/gnorkle/agent\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestWhitelist(t *testing.T) {\n\tvar whitelist agent.Whitelist\n\n\tuassert.False(t, whitelist.HasDefinition(), \"whitelist should not be defined initially\")\n\n\twhitelist.AddAddresses([]string{\"a\", \"b\"})\n\tuassert.True(t, whitelist.HasAddress(\"a\"), `whitelist should have address \"a\"`)\n\tuassert.True(t, whitelist.HasAddress(\"b\"), `whitelist should have address \"b\"`)\n\tuassert.True(t, whitelist.HasDefinition(), \"whitelist should be defined after adding addresses\")\n\n\twhitelist.RemoveAddress(\"a\")\n\tuassert.False(t, whitelist.HasAddress(\"a\"), `whitelist should not have address \"a\"`)\n\tuassert.True(t, whitelist.HasAddress(\"b\"), `whitelist should still have address \"b\"`)\n\n\twhitelist.ClearAddresses()\n\tuassert.False(t, whitelist.HasAddress(\"a\"), `whitelist cleared; should not have address \"a\"`)\n\tuassert.False(t, whitelist.HasAddress(\"b\"), `whitelist cleared; should still have address \"b\"`)\n\tuassert.False(t, whitelist.HasDefinition(), \"whitelist cleared; should not be defined\")\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"F01imfM0WpL4I6CEljAGOv0i51Xv8uqovATmp5RZN+9tYsPDyF+6Z3C7mXs6UxfBjPLIp6c2T47emwmcWmHSUw=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"feed","path":"gno.land/p/demo/gnorkle/feed","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\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"2oTRmDCA8Z+YOhoon0Y2w8u0Orn8eQd4LgqBcbkL1TEHbknTsxqqHd7s9UWHJn+bOIIPMhkmoKDXWAtYV5hVSQ=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"ingester","path":"gno.land/p/demo/gnorkle/ingester","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\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"VjxyMuew+5YoPGoHwdikXGe27FR8wTWD96WMhmAzzDhILVG6+dl+9/BuQQM2G0TgZbUDyPOFF0uKWTeQ3p2kTg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"message","path":"gno.land/p/demo/gnorkle/message","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/gnorkle/message\"\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":"parse_test.gno","body":"package message_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/demo/gnorkle/message\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestParseFunc(t *testing.T) {\n\ttests := []struct {\n\t\tname         string\n\t\tinput        string\n\t\texpFuncType  message.FuncType\n\t\texpRemainder string\n\t}{\n\t\t{\n\t\t\tname: \"empty\",\n\t\t},\n\t\t{\n\t\t\tname:        \"func only\",\n\t\t\tinput:       \"ingest\",\n\t\t\texpFuncType: message.FuncTypeIngest,\n\t\t},\n\t\t{\n\t\t\tname:         \"func with short remainder\",\n\t\t\tinput:        \"commit,asdf\",\n\t\t\texpFuncType:  message.FuncTypeCommit,\n\t\t\texpRemainder: \"asdf\",\n\t\t},\n\t\t{\n\t\t\tname:         \"func with long remainder\",\n\t\t\tinput:        \"request,hello,world,goodbye\",\n\t\t\texpFuncType:  message.FuncTypeRequest,\n\t\t\texpRemainder: \"hello,world,goodbye\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tfuncType, remainder := message.ParseFunc(tt.input)\n\n\t\t\tuassert.Equal(t, string(tt.expFuncType), string(funcType))\n\t\t\tuassert.Equal(t, tt.expRemainder, remainder)\n\t\t})\n\t}\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"AdZOiAhi14NniaBvUfJnvisbeK2BfxdxJbzaRoO2eLRxMa72SCn0EO87uTx+R7Y8w8tdr5O3MEOnzZDdHlrHQA=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"gnorkle","path":"gno.land/p/demo/gnorkle/gnorkle","files":[{"name":"feed.gno","body":"package gnorkle\n\nimport (\n\t\"gno.land/p/demo/gnorkle/feed\"\n\t\"gno.land/p/demo/gnorkle/message\"\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\"\ngno = \"0.9\"\n"},{"name":"ingester.gno","body":"package gnorkle\n\nimport \"gno.land/p/demo/gnorkle/ingester\"\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\"\n\t\"gno.land/p/demo/gnorkle/feed\"\n\t\"gno.land/p/demo/gnorkle/message\"\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\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"Zek9Rx5Qce21eO/5AZteqrmcUt7XDnN4ZPKQPrX3vOxBYQmWoDXj/yZZ+G46KvkqO5VbDMhbPPkKsjCfv/Ffow=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"storage","path":"gno.land/p/demo/gnorkle/storage","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\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"VdAwIBmsbPhgaExejkirXDAxBp4NMLdNU+MMLrK5Z6tHh8XF/5eV2qKEkGRtmKeblHmt915WYjnfMiwlSNP12A=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"simple","path":"gno.land/p/demo/gnorkle/storage/simple","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/gnorkle/storage/simple\"\ngno = \"0.9\"\n"},{"name":"storage.gno","body":"package simple\n\nimport (\n\t\"time\"\n\n\t\"gno.land/p/demo/gnorkle/feed\"\n\t\"gno.land/p/demo/gnorkle/storage\"\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"},{"name":"storage_test.gno","body":"package simple_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/demo/gnorkle/storage\"\n\t\"gno.land/p/demo/gnorkle/storage/simple\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc TestStorage(t *testing.T) {\n\tvar undefinedStorage *simple.Storage\n\terr := undefinedStorage.Put(\"\")\n\tuassert.ErrorIs(t, err, storage.ErrUndefined, \"expected storage.ErrUndefined on undefined storage\")\n\n\ttests := []struct {\n\t\tname                      string\n\t\tvaluesToPut               []string\n\t\texpLatestValueString      string\n\t\texpLatestValueTimeIsZero  bool\n\t\texpHistoricalValueStrings []string\n\t}{\n\t\t{\n\t\t\tname:                     \"empty\",\n\t\t\texpLatestValueTimeIsZero: true,\n\t\t},\n\t\t{\n\t\t\tname:                      \"one value\",\n\t\t\tvaluesToPut:               []string{\"one\"},\n\t\t\texpLatestValueString:      \"one\",\n\t\t\texpHistoricalValueStrings: []string{\"one\"},\n\t\t},\n\t\t{\n\t\t\tname:                      \"two values\",\n\t\t\tvaluesToPut:               []string{\"one\", \"two\"},\n\t\t\texpLatestValueString:      \"two\",\n\t\t\texpHistoricalValueStrings: []string{\"one\", \"two\"},\n\t\t},\n\t\t{\n\t\t\tname:                      \"three values\",\n\t\t\tvaluesToPut:               []string{\"one\", \"two\", \"three\"},\n\t\t\texpLatestValueString:      \"three\",\n\t\t\texpHistoricalValueStrings: []string{\"two\", \"three\"},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsimpleStorage := simple.NewStorage(2)\n\t\t\tfor _, value := range tt.valuesToPut {\n\t\t\t\terr := simpleStorage.Put(value)\n\t\t\t\turequire.NoError(t, err, \"unexpected error putting value in storage\")\n\t\t\t}\n\n\t\t\tlatestValue := simpleStorage.GetLatest()\n\t\t\tuassert.Equal(t, tt.expLatestValueString, latestValue.String)\n\t\t\tuassert.Equal(t, tt.expLatestValueTimeIsZero, latestValue.Time.IsZero())\n\n\t\t\thistoricalValues := simpleStorage.GetHistory()\n\t\t\turequire.Equal(t, len(tt.expHistoricalValueStrings), len(historicalValues), \"historical values length does not match\")\n\n\t\t\tfor i, expValue := range tt.expHistoricalValueStrings {\n\t\t\t\tuassert.Equal(t, historicalValues[i].String, expValue)\n\t\t\t\turequire.False(t, historicalValues[i].Time.IsZero(), ufmt.Sprintf(\"unexpeced zero time for historical value at index %d\", i))\n\t\t\t}\n\t\t})\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"L2RglpRIqeo0NzddkzbwZZqXxt9yHY42gkbjA7nyW2llJC3jk6zQhxGnwDhkM579j9p4tkqwANFsHRytIVMzSg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"single","path":"gno.land/p/demo/gnorkle/ingesters/single","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/gnorkle/ingesters/single\"\ngno = \"0.9\"\n"},{"name":"ingester.gno","body":"package single\n\nimport (\n\t\"gno.land/p/demo/gnorkle/gnorkle\"\n\t\"gno.land/p/demo/gnorkle/ingester\"\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"},{"name":"ingester_test.gno","body":"package single_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/demo/gnorkle/ingester\"\n\t\"gno.land/p/demo/gnorkle/ingesters/single\"\n\t\"gno.land/p/demo/gnorkle/storage/simple\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestValueIngester(t *testing.T) {\n\tstorage := simple.NewStorage(1)\n\n\tvar undefinedIngester *single.ValueIngester\n\t_, err := undefinedIngester.Ingest(\"asdf\", \"gno11111\")\n\tuassert.ErrorIs(t, err, ingester.ErrUndefined, \"undefined ingester call to Ingest should return ingester.ErrUndefined\")\n\n\terr = undefinedIngester.CommitValue(storage, \"gno11111\")\n\tuassert.ErrorIs(t, err, ingester.ErrUndefined, \"undefined ingester call to CommitValue should return ingester.ErrUndefined\")\n\n\tvar valueIngester single.ValueIngester\n\ttyp := valueIngester.Type()\n\tuassert.Equal(t, int(ingester.TypeSingle), int(typ), \"single value ingester should return type ingester.TypeSingle\")\n\n\tingestValue := \"value\"\n\tautocommit, err := valueIngester.Ingest(ingestValue, \"gno11111\")\n\tuassert.True(t, autocommit, \"single value ingester should return autocommit true\")\n\tuassert.NoError(t, err)\n\n\terr = valueIngester.CommitValue(storage, \"gno11111\")\n\tuassert.NoError(t, err)\n\n\tlatestValue := storage.GetLatest()\n\tuassert.Equal(t, ingestValue, latestValue.String)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"HBRqUHb8tF/3OB2awlC9Gd1c1SO2paK1oYLHcGqNtkFTNPG2D4V2BYdLijzBw0+o0e5TARxXO2J8hVXvztST9w=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"static","path":"gno.land/p/demo/gnorkle/feeds/static","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\"\n\t\"gno.land/p/demo/gnorkle/gnorkle\"\n\t\"gno.land/p/demo/gnorkle/ingesters/single\"\n\t\"gno.land/p/demo/gnorkle/message\"\n\t\"gno.land/p/demo/gnorkle/storage/simple\"\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":"feed_test.gno","body":"package static_test\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"gno.land/p/demo/gnorkle/feed\"\n\t\"gno.land/p/demo/gnorkle/feeds/static\"\n\t\"gno.land/p/demo/gnorkle/gnorkle\"\n\t\"gno.land/p/demo/gnorkle/ingester\"\n\t\"gno.land/p/demo/gnorkle/message\"\n\t\"gno.land/p/demo/gnorkle/storage/simple\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\ntype mockIngester struct {\n\tcanAutoCommit   bool\n\tingestErr       error\n\tcommitErr       error\n\tvalue           string\n\tproviderAddress string\n}\n\nfunc (i mockIngester) Type() ingester.Type {\n\treturn ingester.Type(0)\n}\n\nfunc (i *mockIngester) Ingest(value, providerAddress string) (bool, error) {\n\tif i.ingestErr != nil {\n\t\treturn false, i.ingestErr\n\t}\n\n\ti.value = value\n\ti.providerAddress = providerAddress\n\treturn i.canAutoCommit, nil\n}\n\nfunc (i *mockIngester) CommitValue(storage gnorkle.Storage, providerAddress string) error {\n\tif i.commitErr != nil {\n\t\treturn i.commitErr\n\t}\n\n\treturn storage.Put(i.value)\n}\n\nfunc TestNewSingleValueFeed(t *testing.T) {\n\tstaticFeed := static.NewSingleValueFeed(\"1\", \"\")\n\n\tuassert.Equal(t, \"1\", staticFeed.ID())\n\tuassert.Equal(t, int(feed.TypeStatic), int(staticFeed.Type()))\n}\n\nfunc TestFeed_Ingest(t *testing.T) {\n\tvar undefinedFeed *static.Feed\n\terr := undefinedFeed.Ingest(\"\", \"\", \"\")\n\tuassert.ErrorIs(t, err, feed.ErrUndefined)\n\n\ttests := []struct {\n\t\tname               string\n\t\tingester           *mockIngester\n\t\tverifyIsLocked     bool\n\t\tdoCommit           bool\n\t\tfuncType           message.FuncType\n\t\tmsg                string\n\t\tproviderAddress    string\n\t\texpFeedValueString string\n\t\texpErrText         string\n\t\texpIsActive        bool\n\t}{\n\t\t{\n\t\t\tname:        \"func invalid error\",\n\t\t\tingester:    \u0026mockIngester{},\n\t\t\tfuncType:    message.FuncType(\"derp\"),\n\t\t\texpErrText:  \"invalid message function derp\",\n\t\t\texpIsActive: true,\n\t\t},\n\t\t{\n\t\t\tname: \"func ingest ingest error\",\n\t\t\tingester: \u0026mockIngester{\n\t\t\t\tingestErr: errors.New(\"ingest error\"),\n\t\t\t},\n\t\t\tfuncType:    message.FuncTypeIngest,\n\t\t\texpErrText:  \"ingest error\",\n\t\t\texpIsActive: true,\n\t\t},\n\t\t{\n\t\t\tname: \"func ingest commit error\",\n\t\t\tingester: \u0026mockIngester{\n\t\t\t\tcommitErr:     errors.New(\"commit error\"),\n\t\t\t\tcanAutoCommit: true,\n\t\t\t},\n\t\t\tfuncType:    message.FuncTypeIngest,\n\t\t\texpErrText:  \"commit error\",\n\t\t\texpIsActive: true,\n\t\t},\n\t\t{\n\t\t\tname: \"func commit commit error\",\n\t\t\tingester: \u0026mockIngester{\n\t\t\t\tcommitErr:     errors.New(\"commit error\"),\n\t\t\t\tcanAutoCommit: true,\n\t\t\t},\n\t\t\tfuncType:    message.FuncTypeCommit,\n\t\t\texpErrText:  \"commit error\",\n\t\t\texpIsActive: true,\n\t\t},\n\t\t{\n\t\t\tname:            \"only ingest\",\n\t\t\tingester:        \u0026mockIngester{},\n\t\t\tfuncType:        message.FuncTypeIngest,\n\t\t\tmsg:             \"still active feed\",\n\t\t\tproviderAddress: \"gno1234\",\n\t\t\texpIsActive:     true,\n\t\t},\n\t\t{\n\t\t\tname:               \"ingest autocommit\",\n\t\t\tingester:           \u0026mockIngester{canAutoCommit: true},\n\t\t\tfuncType:           message.FuncTypeIngest,\n\t\t\tmsg:                \"still active feed\",\n\t\t\tproviderAddress:    \"gno1234\",\n\t\t\texpFeedValueString: \"still active feed\",\n\t\t\tverifyIsLocked:     true,\n\t\t},\n\t\t{\n\t\t\tname:           \"commit no value\",\n\t\t\tingester:       \u0026mockIngester{},\n\t\t\tfuncType:       message.FuncTypeCommit,\n\t\t\tmsg:            \"shouldn't be stored\",\n\t\t\tverifyIsLocked: true,\n\t\t},\n\t\t{\n\t\t\tname:               \"ingest then commmit\",\n\t\t\tingester:           \u0026mockIngester{},\n\t\t\tfuncType:           message.FuncTypeIngest,\n\t\t\tmsg:                \"blahblah\",\n\t\t\tdoCommit:           true,\n\t\t\texpFeedValueString: \"blahblah\",\n\t\t\tverifyIsLocked:     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\tstaticFeed := static.NewFeed(\n\t\t\t\t\"1\",\n\t\t\t\t\"string\",\n\t\t\t\ttt.ingester,\n\t\t\t\tsimple.NewStorage(1),\n\t\t\t\tnil,\n\t\t\t)\n\n\t\t\tvar errText string\n\t\t\tif err := staticFeed.Ingest(tt.funcType, tt.msg, tt.providerAddress); err != nil {\n\t\t\t\terrText = err.Error()\n\t\t\t}\n\n\t\t\turequire.Equal(t, tt.expErrText, errText)\n\n\t\t\tif tt.doCommit {\n\t\t\t\terr := staticFeed.Ingest(message.FuncTypeCommit, \"\", \"\")\n\t\t\t\turequire.NoError(t, err, \"follow up commit failed\")\n\t\t\t}\n\n\t\t\tif tt.verifyIsLocked {\n\t\t\t\terrText = \"\"\n\t\t\t\tif err := staticFeed.Ingest(tt.funcType, tt.msg, tt.providerAddress); err != nil {\n\t\t\t\t\terrText = err.Error()\n\t\t\t\t}\n\n\t\t\t\turequire.Equal(t, \"feed locked\", errText)\n\t\t\t}\n\n\t\t\tuassert.Equal(t, tt.providerAddress, tt.ingester.providerAddress)\n\n\t\t\tfeedValue, dataType, isLocked := staticFeed.Value()\n\t\t\tuassert.Equal(t, tt.expFeedValueString, feedValue.String)\n\t\t\tuassert.Equal(t, \"string\", dataType)\n\t\t\tuassert.Equal(t, tt.verifyIsLocked, isLocked)\n\t\t\tuassert.Equal(t, tt.expIsActive, staticFeed.IsActive())\n\t\t})\n\t}\n}\n\ntype mockTask struct {\n\terr   error\n\tvalue string\n}\n\nfunc (t mockTask) MarshalJSON() ([]byte, error) {\n\tif t.err != nil {\n\t\treturn nil, t.err\n\t}\n\n\treturn []byte(`{\"value\":\"` + t.value + `\"}`), nil\n}\n\nfunc TestFeed_Tasks(t *testing.T) {\n\tid := \"99\"\n\tvalueDataType := \"int\"\n\n\ttests := []struct {\n\t\tname       string\n\t\ttasks      []feed.Task\n\t\texpErrText string\n\t\texpJSON    string\n\t}{\n\t\t{\n\t\t\tname:    \"no tasks\",\n\t\t\texpJSON: `{\"id\":\"99\",\"type\":\"0\",\"value_type\":\"int\",\"tasks\":[]}`,\n\t\t},\n\t\t{\n\t\t\tname: \"marshal error\",\n\t\t\ttasks: []feed.Task{\n\t\t\t\tmockTask{err: errors.New(\"marshal error\")},\n\t\t\t},\n\t\t\texpErrText: \"marshal error\",\n\t\t},\n\t\t{\n\t\t\tname: \"one task\",\n\t\t\ttasks: []feed.Task{\n\t\t\t\tmockTask{value: \"single\"},\n\t\t\t},\n\t\t\texpJSON: `{\"id\":\"99\",\"type\":\"0\",\"value_type\":\"int\",\"tasks\":[{\"value\":\"single\"}]}`,\n\t\t},\n\t\t{\n\t\t\tname: \"two tasks\",\n\t\t\ttasks: []feed.Task{\n\t\t\t\tmockTask{value: \"first\"},\n\t\t\t\tmockTask{value: \"second\"},\n\t\t\t},\n\t\t\texpJSON: `{\"id\":\"99\",\"type\":\"0\",\"value_type\":\"int\",\"tasks\":[{\"value\":\"first\"},{\"value\":\"second\"}]}`,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tstaticFeed := static.NewSingleValueFeed(\n\t\t\t\tid,\n\t\t\t\tvalueDataType,\n\t\t\t\ttt.tasks...,\n\t\t\t)\n\n\t\t\turequire.Equal(t, len(tt.tasks), len(staticFeed.Tasks()))\n\n\t\t\tvar errText string\n\t\t\tjson, err := staticFeed.MarshalJSON()\n\t\t\tif err != nil {\n\t\t\t\terrText = err.Error()\n\t\t\t}\n\n\t\t\turequire.Equal(t, tt.expErrText, errText)\n\t\t\turequire.Equal(t, tt.expJSON, string(json))\n\t\t})\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/gnorkle/feeds/static\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"rX/ZYTRFG14Cr9PD6t1FaUZxU5gI7mCwh1vOi4iFzRxUtHtm4z+Vm3uwTI4KRH8B4EcNfnF6PhzPVdGLkSqSOA=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"svg","path":"gno.land/p/demo/svg","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/demo/svg\"\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/demo/svg\"\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/svg\"\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"},{"name":"z0_filetest.gno","body":"// PKGPATH: gno.land/p/demo/svg_test\npackage svg_test\n\nimport \"gno.land/p/demo/svg\"\n\nfunc main() {\n\tcanvas := svg.Canvas{Width: 500, Height: 500}\n\tcanvas.Append(\n\t\tsvg.Rectangle{X: 50, Y: 50, Width: 100, Height: 100, Fill: \"red\"},\n\t\tsvg.Circle{CX: 100, CY: 100, R: 50, Fill: \"blue\"},\n\t\tsvg.Text{X: 100, Y: 100, Text: \"hello world!\", Fill: \"magenta\"},\n\t)\n\tcanvas.Append(\n\t\tsvg.NewCircle(100, 100, 50, \"blue\").WithClass(\"toto\"),\n\t)\n\tprintln(canvas)\n}\n\n// Output:\n// \u003csvg xmlns=\"http://www.w3.org/2000/svg\" width=\"500\" height=\"500\" viewBox=\"\"\u003e\u003crect x=\"50\" y=\"50\" width=\"100\" height=\"100\" rx=\"0\" ry=\"0\" fill=\"red\" /\u003e\u003ccircle cx=\"100\" cy=\"100\" r=\"50\" fill=\"blue\" /\u003e\u003ctext x=\"100\" y=\"100\" dx=\"0\" dy=\"0\" rotate=\"\" fill=\"magenta\" \u003ehello world!\u003c/text\u003e\u003ccircle cx=\"100\" cy=\"100\" r=\"50\" fill=\"blue\" class=\"toto\"/\u003e\u003c/svg\u003e\n"},{"name":"z1_filetest.gno","body":"// PKGPATH: gno.land/p/demo/svg_test\npackage svg_test\n\nimport \"gno.land/p/demo/svg\"\n\nfunc main() {\n\tcanvas := svg.Canvas{\n\t\tWidth: 500, Height: 500,\n\t\tElems: []svg.Elem{\n\t\t\tsvg.Rectangle{X: 50, Y: 50, Width: 100, Height: 100, Fill: \"red\"},\n\t\t\tsvg.Circle{CX: 50, CY: 50, R: 100, Fill: \"red\"},\n\t\t\tsvg.Text{X: 100, Y: 100, Text: \"hello world!\", Fill: \"magenta\"},\n\t\t},\n\t}\n\tprintln(canvas)\n}\n\n// Output:\n// \u003csvg xmlns=\"http://www.w3.org/2000/svg\" width=\"500\" height=\"500\" viewBox=\"\"\u003e\u003crect x=\"50\" y=\"50\" width=\"100\" height=\"100\" rx=\"0\" ry=\"0\" fill=\"red\" /\u003e\u003ccircle cx=\"50\" cy=\"50\" r=\"100\" fill=\"red\" /\u003e\u003ctext x=\"100\" y=\"100\" dx=\"0\" dy=\"0\" rotate=\"\" fill=\"magenta\" \u003ehello world!\u003c/text\u003e\u003c/svg\u003e\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"fJbd32o4caChEypOhFpM0rvhJ8aKcaEu4crngEZRoRJ+HG4QcuyUqMtTAtJ5gcdolJKhBKfWnuUGXYtEqFu10Q=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"subtests","path":"gno.land/p/demo/tests/subtests","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/tests/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() 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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"ojkVIdNEs56B6YqMFGeCEc/2OSxBDlJlCL/EU4hiqWpE8+s91P9Fir9t1QIcjTRUnImP4hwS0NtD6fmxyVllEg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"tests","path":"gno.land/p/demo/tests","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\"\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\"\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"},{"name":"tests_test.gno","body":"package tests_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/demo/tests\"\n)\n\nvar World = \"WORLD\"\n\nfunc TestGetHelloWorld(t *testing.T) {\n\t// tests.World is 'world'\n\ts := \"hello \" + tests.World + World\n\tconst want = \"hello worldWORLD\"\n\tif s != want {\n\t\tt.Error(\"not the same\")\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"X+Gfq8PFY4mN5bVZelHD0kFPx8jACFFCnRBXD+1rr4oyZ3uh7SHGXlAWU+aRNcLL+KhOwdC1Kea054D4LXDwAQ=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"launderpkg","path":"gno.land/p/demo/tests/launderpkg","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/tests/launderpkg\"\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.\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"hb9u4hxXMrumgy9oiuRDj8Ic4+SFiZ7/Os5V8+o14Ph0TJ1WJXNXpMuzIje+OTUE/8mH/dSesdMIHhs6iNcp6Q=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"launderattack","path":"gno.land/p/demo/tests/launderattack","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/tests/launderattack\"\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\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"JLaWutrYESC4a9qG5Dy30aXE/Lzw1CnS0lNVaSz8GaBE/X6BrDQ7WzAJwdsKye9aOmiX3GD70db7qgLl4mOYwg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"p_closurecap","path":"gno.land/p/demo/tests/p_closurecap","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/tests/p_closurecap\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"15ZdeXPp6Rsz78s2eYrOInNxWpGwXslU5ZiHt9gVWg8GBoUqy2PuAjZnIEXTEeVnFYq0JqL8ki8sBhJ5z+fk9A=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"p_crossrealm","path":"gno.land/p/demo/tests/p_crossrealm","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/tests/p_crossrealm\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"xmo2BK4jgCyKA4GZE6IZ5JdaCKMFMQXWQYwMVLnfXwFwlRO8lbP//7XrNhMhNwyO/We56x98cALQwXef9kCjYw=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"grc721","path":"gno.land/p/demo/tokens/grc721","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/tokens/grc721\"\ngno = \"0.9\"\n"},{"name":"newtoken_event_filetest.gno","body":"// PKGPATH: gno.land/r/demo/grc721dupsignal\n\n// This filetest is the reference for the detection rule the NewToken event\n// enables. The realm below reuses seqid 0 twice, so both tokens end up with the\n// same Token.ID() and their Transfer events are indistinguishable — the\n// long-standing event-provenance ambiguity.\n//\n// What changes is that the ambiguity is now *announced*. Two NewToken events\n// carry the same \"token\" value, which is a complete signal: NewToken is the only\n// way a Token can exist (Token's fields are unexported), so an indexer watching\n// this event sees every token that will ever emit. On the second duplicate\n// announcement it should flag the realm and stop trusting its token events.\npackage grc721dupsignal\n\nimport (\n\t\"gno.land/p/demo/tokens/grc721\"\n)\n\nfunc main(cur realm) {\n\tfirst, firstLedger := grc721.NewToken(\"Same\", \"DUP\", 0, cur)\n\tsecond, secondLedger := grc721.NewToken(\"Same\", \"DUP\", 0, cur)\n\n\tprintln(\"same id:\", first.ID() == second.ID())\n\n\t// Two independent ledgers, one identifier: these Transfers cannot be\n\t// attributed to either object from the event stream alone.\n\tfirstLedger.Mint(cur.Address(), \"1\")\n\tsecondLedger.Mint(cur.Address(), \"2\")\n}\n\n// Output:\n// same id: true\n\n// Events:\n// [\n//   {\n//     \"type\": \"NewToken\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/grc721dupsignal.DUP.0000000\"\n//       },\n//       {\n//         \"key\": \"name\",\n//         \"value\": \"Same\"\n//       },\n//       {\n//         \"key\": \"symbol\",\n//         \"value\": \"DUP\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/p/demo/tokens/grc721\"\n//   },\n//   {\n//     \"type\": \"NewToken\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/grc721dupsignal.DUP.0000000\"\n//       },\n//       {\n//         \"key\": \"name\",\n//         \"value\": \"Same\"\n//       },\n//       {\n//         \"key\": \"symbol\",\n//         \"value\": \"DUP\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/p/demo/tokens/grc721\"\n//   },\n//   {\n//     \"type\": \"Transfer\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/grc721dupsignal.DUP.0000000\"\n//       },\n//       {\n//         \"key\": \"from\",\n//         \"value\": \"\"\n//       },\n//       {\n//         \"key\": \"to\",\n//         \"value\": \"g1f2p7p8jhjmg6atgukt8kveqgsrrk3qqhe6vg9m\"\n//       },\n//       {\n//         \"key\": \"tokenId\",\n//         \"value\": \"1\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/p/demo/tokens/grc721\"\n//   },\n//   {\n//     \"type\": \"Transfer\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/grc721dupsignal.DUP.0000000\"\n//       },\n//       {\n//         \"key\": \"from\",\n//         \"value\": \"\"\n//       },\n//       {\n//         \"key\": \"to\",\n//         \"value\": \"g1f2p7p8jhjmg6atgukt8kveqgsrrk3qqhe6vg9m\"\n//       },\n//       {\n//         \"key\": \"tokenId\",\n//         \"value\": \"2\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/p/demo/tokens/grc721\"\n//   }\n// ]\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":"tellers_test.gno","body":"package grc721\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\ntype evilTeller struct{ Teller }\n\nfunc TestIsCanonicalTeller(cur realm, t *testing.T) {\n\ttok, led := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\n\tvar realmTeller Teller\n\tfunc(cur realm) {\n\t\trealmTeller = tok.RealmTeller(0, cur)\n\t}(cross(cur))\n\n\ttests := []struct {\n\t\tname string\n\t\tte   Teller\n\t\twant bool\n\t}{\n\t\t{\"CallerTeller is canonical\", led.CallerTeller(), true},\n\t\t{\"ReadonlyTeller is canonical\", tok.ReadonlyTeller(), true},\n\t\t{\"RealmTeller is canonical\", realmTeller, true},\n\t\t{\"ImpersonateTeller is canonical\", led.ImpersonateTeller(alice), true},\n\t\t{\"embedding wrapper is rejected\", \u0026evilTeller{led.CallerTeller()}, false},\n\t}\n\n\tfor _, tc := range tests {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, tc.want, IsCanonicalTeller(tc.te))\n\t\t})\n\t}\n}\n\nfunc TestTellerNilGuards(cur realm, t *testing.T) {\n\tvar nilTok *Token\n\tvar nilLed *PrivateLedger\n\n\ttests := []struct {\n\t\tname string\n\t\tmsg  string\n\t\tfn   func()\n\t}{\n\t\t{\"CallerTeller on nil ledger panics\", \"Ledger cannot be nil\", func() {\n\t\t\tnilLed.CallerTeller()\n\t\t}},\n\t\t{\"ReadonlyTeller on nil token panics\", \"Token cannot be nil\", func() {\n\t\t\tnilTok.ReadonlyTeller()\n\t\t}},\n\t\t{\"RealmTeller on nil token panics\", \"Token cannot be nil\", func() {\n\t\t\tnilTok.RealmTeller(0, cur)\n\t\t}},\n\t\t{\"RealmSubTeller on nil token panics\", \"Token cannot be nil\", func() {\n\t\t\tnilTok.RealmSubTeller(0, cur, \"slug\")\n\t\t}},\n\t\t{\"ImpersonateTeller on nil ledger panics\", \"Ledger cannot be nil\", func() {\n\t\t\tnilLed.ImpersonateTeller(alice)\n\t\t}},\n\t}\n\n\tfor _, tc := range tests {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tuassert.PanicsWithMessage(t, cur, tc.msg, tc.fn)\n\t\t})\n\t}\n}\n\nfunc TestReadonlyTeller(cur realm, t *testing.T) {\n\ttok, led := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\turequire.NoError(t, led.Mint(alice, \"1\"))\n\tro := tok.ReadonlyTeller()\n\n\ttests := []struct {\n\t\tname string\n\t\top   string\n\t}{\n\t\t{\"Approve rejected with ErrReadonly\", \"approve\"},\n\t\t{\"TransferFrom rejected with ErrReadonly\", \"transfer\"},\n\t\t{\"SetApprovalForAll rejected with ErrReadonly\", \"setall\"},\n\t}\n\n\tfor _, tc := range tests {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tvar err error\n\t\t\ttesting.SetRealm(testing.NewUserRealm(alice))\n\t\t\tfunc(cur realm) {\n\t\t\t\tswitch tc.op {\n\t\t\t\tcase \"approve\":\n\t\t\t\t\terr = ro.Approve(0, cur, bob, \"1\")\n\t\t\t\tcase \"transfer\":\n\t\t\t\t\terr = ro.TransferFrom(0, cur, alice, bob, \"1\")\n\t\t\t\tcase \"setall\":\n\t\t\t\t\terr = ro.SetApprovalForAll(0, cur, bob, true)\n\t\t\t\t}\n\t\t\t}(cross(cur))\n\t\t\tuassert.ErrorIs(t, err, ErrReadonly)\n\t\t})\n\t}\n}\n\nfunc TestCallerTellerFlow(cur realm, t *testing.T) {\n\ttok, led := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\turequire.NoError(t, led.Mint(alice, \"1\"))\n\turequire.NoError(t, led.Mint(alice, \"2\"))\n\n\tteller := led.CallerTeller()\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tfunc(cur realm) {\n\t\turequire.NoError(t, teller.Approve(0, cur, bob, \"1\"))\n\t}(cross(cur))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tfunc(cur realm) {\n\t\turequire.NoError(t, teller.SetApprovalForAll(0, cur, bob, true))\n\t}(cross(cur))\n\tuassert.True(t, tok.IsApprovedForAll(alice, bob))\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tfunc(cur realm) {\n\t\turequire.NoError(t, teller.TransferFrom(0, cur, alice, carl, \"1\"))\n\t}(cross(cur))\n\n\towner, err := tok.OwnerOf(\"1\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, carl, owner)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tfunc(cur realm) {\n\t\tuassert.ErrorIs(t, teller.TransferFrom(0, cur, carl, bob, \"1\"), ErrCallerIsNotOwnerOrApproved)\n\t}(cross(cur))\n}\n\nfunc TestCallerTellerSpoofedRealm(cur realm, t *testing.T) {\n\t_, led := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\turequire.NoError(t, led.Mint(alice, \"1\"))\n\tteller := led.CallerTeller()\n\n\t// Stale outer cur while a fresh frame is current → ErrSpoofedRealm.\n\ttests := []struct {\n\t\tname string\n\t\top   string\n\t}{\n\t\t{\"Approve rejects spoofed realm\", \"approve\"},\n\t\t{\"TransferFrom rejects spoofed realm\", \"transfer\"},\n\t\t{\"SetApprovalForAll rejects spoofed realm\", \"setall\"},\n\t}\n\n\tfor _, tc := range tests {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tvar err error\n\t\t\tstale := cur\n\t\t\tfunc(cur realm) {\n\t\t\t\tswitch tc.op {\n\t\t\t\tcase \"approve\":\n\t\t\t\t\terr = teller.Approve(0, stale, bob, \"1\")\n\t\t\t\tcase \"transfer\":\n\t\t\t\t\terr = teller.TransferFrom(0, stale, alice, bob, \"1\")\n\t\t\t\tcase \"setall\":\n\t\t\t\t\terr = teller.SetApprovalForAll(0, stale, bob, true)\n\t\t\t\t}\n\t\t\t}(cross(cur))\n\t\t\tuassert.ErrorIs(t, err, ErrSpoofedRealm)\n\t\t})\n\t}\n}\n\nfunc TestRealmTellerFlow(cur realm, t *testing.T) {\n\ttok, led := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\n\tvar teller Teller\n\tvar realmAddr address\n\tfunc(cur realm) {\n\t\tteller = tok.RealmTeller(0, cur)\n\t\trealmAddr = cur.Address()\n\t}(cross(cur))\n\n\turequire.NoError(t, led.Mint(realmAddr, \"1\"))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tfunc(cur realm) {\n\t\turequire.NoError(t, teller.TransferFrom(0, cur, realmAddr, bob, \"1\"))\n\t}(cross(cur))\n\n\towner, err := tok.OwnerOf(\"1\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, bob, owner)\n}\n\nfunc TestRealmSubTellerFlow(cur realm, t *testing.T) {\n\ttok, led := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\n\ttests := []struct {\n\t\tname           string\n\t\tslug           string\n\t\ttid            TokenID\n\t\twantsRealmAddr bool\n\t}{\n\t\t{\"empty slug derives the realm address itself\", \"\", \"10\", true},\n\t\t{\"non-empty slug derives a sub-account\", \"vault\", \"11\", false},\n\t}\n\n\tfor _, tc := range tests {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tvar teller Teller\n\t\t\tvar realmAddr, account address\n\t\t\tfunc(cur realm) {\n\t\t\t\tteller = tok.RealmSubTeller(0, cur, tc.slug)\n\t\t\t\trealmAddr = cur.Address()\n\t\t\t\taccount = accountSlugAddr(cur.Address(), tc.slug)\n\t\t\t}(cross(cur))\n\n\t\t\tif tc.wantsRealmAddr {\n\t\t\t\tuassert.Equal(t, realmAddr, account)\n\t\t\t} else {\n\t\t\t\tuassert.True(t, realmAddr != account, \"sub-account must differ from realm address\")\n\t\t\t}\n\n\t\t\turequire.NoError(t, led.Mint(account, tc.tid))\n\t\t\ttesting.SetRealm(testing.NewUserRealm(alice))\n\t\t\tfunc(cur realm) {\n\t\t\t\turequire.NoError(t, teller.TransferFrom(0, cur, account, bob, tc.tid))\n\t\t\t}(cross(cur))\n\n\t\t\towner, err := tok.OwnerOf(tc.tid)\n\t\t\turequire.NoError(t, err)\n\t\t\tuassert.Equal(t, bob, owner)\n\t\t})\n\t}\n}\n\nfunc TestRealmTellerSpoofedRealm(cur realm, t *testing.T) {\n\ttok, _ := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\n\ttests := []struct {\n\t\tname string\n\t\tfn   func()\n\t}{\n\t\t{\"RealmTeller rejects spoofed realm\", func() {\n\t\t\tstale := cur\n\t\t\tfunc(cur realm) {\n\t\t\t\ttok.RealmTeller(0, stale)\n\t\t\t}(cross(cur))\n\t\t}},\n\t\t{\"RealmSubTeller rejects spoofed realm\", func() {\n\t\t\tstale := cur\n\t\t\tfunc(cur realm) {\n\t\t\t\ttok.RealmSubTeller(0, stale, \"vault\")\n\t\t\t}(cross(cur))\n\t\t}},\n\t}\n\n\tfor _, tc := range tests {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\turequire.AbortsContains(t, cur, \"rlm does not match the current crossing frame\", tc.fn)\n\t\t})\n\t}\n}\n\nfunc TestImpersonateTeller(cur realm, t *testing.T) {\n\ttok, led := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\turequire.NoError(t, led.Mint(alice, \"1\"))\n\n\tteller := led.ImpersonateTeller(alice)\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tfunc(cur realm) {\n\t\turequire.NoError(t, teller.TransferFrom(0, cur, alice, bob, \"1\"))\n\t}(cross(cur))\n\n\towner, err := tok.OwnerOf(\"1\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, bob, owner)\n}\n\nfunc TestImpersonateTellerRejectsInvalidAddress(cur realm, t *testing.T) {\n\t_, led := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\tuassert.PanicsWithMessage(t, cur, \"invalid address\", func() {\n\t\tled.ImpersonateTeller(zeroAddress)\n\t})\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":"token_test.gno","body":"package grc721\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\nfunc mustBalanceOf(t *testing.T, tok *Token, addr address) int64 {\n\tbalance, err := tok.BalanceOf(addr)\n\turequire.NoError(t, err)\n\treturn balance\n}\n\n// newTestToken builds via same-realm cross (NewToken requires rlm.IsCurrent()).\nfunc newTestToken(name, symbol string, id seqid.ID, rlm realm) (tok *Token, led *PrivateLedger) {\n\tfunc(cur realm) {\n\t\ttok, led = NewToken(name, symbol, id, cur)\n\t}(cross(rlm))\n\treturn\n}\n\ntype mockExtension struct {\n\tmints, transfers, burns int\n\tlastMintTo              address\n\tlastTransferFrom        address\n\tlastTransferTo          address\n\tlastBurn                TokenID\n}\n\nfunc (m *mockExtension) ExtensionKind() string { return \"mock\" }\n\nfunc (m *mockExtension) OnMint(to address, tid TokenID) {\n\tm.mints++\n\tm.lastMintTo = to\n}\n\nfunc (m *mockExtension) OnTransfer(from, to address, tid TokenID) {\n\tm.transfers++\n\tm.lastTransferFrom = from\n\tm.lastTransferTo = to\n}\n\nfunc (m *mockExtension) OnBurn(tid TokenID) {\n\tm.burns++\n\tm.lastBurn = tid\n}\n\n// Value type holding a slice: uncomparable, so `==` on two of them is a runtime fault.\ntype journalExtension struct{ seen []TokenID }\n\nfunc (e journalExtension) ExtensionKind() string                    { return \"journal\" }\nfunc (e journalExtension) OnMint(to address, tid TokenID)           {}\nfunc (e journalExtension) OnTransfer(from, to address, tid TokenID) {}\nfunc (e journalExtension) OnBurn(tid TokenID)                       {}\n\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n\tcarl  = testutils.TestAddress(\"carl\")\n)\n\nfunc TestNewToken(cur realm, t *testing.T) {\n\ttok, led := newTestToken(\"Foo NFT\", \"FOO\", 0, cur)\n\turequire.False(t, tok == nil, \"token should not be nil\")\n\turequire.False(t, led == nil, \"ledger should not be nil\")\n\n\tuassert.Equal(t, \"Foo NFT\", tok.GetName())\n\tuassert.Equal(t, \"FOO\", tok.GetSymbol())\n\tuassert.Equal(t, int64(0), tok.TotalSupply())\n\tuassert.Equal(t, 0, tok.KnownAccounts())\n\tuassert.True(t, strings.HasSuffix(tok.ID(), \".FOO.\"+seqid.ID(0).String()), \"ID must end with .symbol.id\")\n\tuassert.True(t, strings.HasPrefix(tok.ID(), \"gno.land/\"), \"ID must begin with the origin realm path\")\n\tuassert.Equal(t, tok.ID(), led.ReadToken().ID())\n}\n\nfunc TestNewTokenDistinctIDs(cur realm, t *testing.T) {\n\tfirst, _ := newTestToken(\"Same\", \"DUP\", 1, cur)\n\tsecond, _ := newTestToken(\"Same\", \"DUP\", 2, cur)\n\tuassert.True(t, first.ID() != second.ID(), \"distinct seqid must yield distinct IDs\")\n\n\ta, _ := newTestToken(\"Same\", \"DUP\", 3, cur)\n\tb, _ := newTestToken(\"Same\", \"DUP\", 3, cur)\n\tuassert.Equal(t, a.ID(), b.ID())\n}\n\nfunc TestNewTokenValidation(cur realm, t *testing.T) {\n\tlongName := strings.Repeat(\"a\", MaxNameLen+1)\n\tmaxName := strings.Repeat(\"a\", MaxNameLen)\n\tlongSymbol := strings.Repeat(\"A\", MaxSymbolLen+1)\n\n\ttests := []struct {\n\t\tname       string\n\t\ttokenName  string\n\t\tsymbol     string\n\t\twantAbort  bool\n\t\twantSubstr string\n\t}{\n\t\t{\"valid name and symbol succeeds\", \"Foo\", \"FOO\", false, \"\"},\n\t\t{\"symbol with full slug charset succeeds\", \"Foo\", \"aZ9_-\", false, \"\"},\n\t\t{\"name at max length succeeds\", maxName, \"FOO\", false, \"\"},\n\t\t{\"empty name returns ErrInvalidName\", \"\", \"FOO\", true, \"invalid token name\"},\n\t\t{\"name over max length returns ErrInvalidName\", longName, \"FOO\", true, \"invalid token name\"},\n\t\t{\"name with low control char returns ErrInvalidName\", \"Foo\\x01\", \"FOO\", true, \"invalid token name\"},\n\t\t{\"name with DEL control char returns ErrInvalidName\", \"Foo\\x7f\", \"FOO\", true, \"invalid token name\"},\n\t\t{\"empty symbol returns ErrInvalidSymbol\", \"Foo\", \"\", true, \"invalid token symbol\"},\n\t\t{\"symbol over max length returns ErrInvalidSymbol\", \"Foo\", longSymbol, true, \"invalid token symbol\"},\n\t\t{\"symbol with space returns ErrInvalidSymbol\", \"Foo\", \"has space\", true, \"invalid token symbol\"},\n\t\t{\"symbol with dot returns ErrInvalidSymbol\", \"Foo\", \"FO.O\", true, \"invalid token symbol\"},\n\t\t{\"symbol with slash returns ErrInvalidSymbol\", \"Foo\", \"FO/O\", true, \"invalid token symbol\"},\n\t}\n\n\tfor _, tc := range tests {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tif tc.wantAbort {\n\t\t\t\turequire.AbortsContains(t, cur, tc.wantSubstr, func() {\n\t\t\t\t\tnewTestToken(tc.tokenName, tc.symbol, 0, cur)\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttok, _ := newTestToken(tc.tokenName, tc.symbol, 0, cur)\n\t\t\tuassert.Equal(t, tc.tokenName, tok.GetName())\n\t\t\tuassert.Equal(t, tc.symbol, tok.GetSymbol())\n\t\t})\n\t}\n}\n\nfunc TestNewTokenRejectsSpoofedRealm(cur realm, t *testing.T) {\n\t// Stale outer cur in a fresh frame → ErrSpoofedRealm.\n\turequire.AbortsContains(t, cur, \"rlm does not match the current crossing frame\", func() {\n\t\tstale := cur\n\t\tfunc(cur realm) {\n\t\t\tNewToken(\"Foo\", \"FOO\", 0, stale)\n\t\t}(cross(cur))\n\t})\n}\n\nfunc TestMint(cur realm, t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\taction  func(led *PrivateLedger) error\n\t\twantErr error\n\t\tverify  func(t *testing.T, tok *Token, led *PrivateLedger)\n\t}{\n\t\t{\n\t\t\tname: \"mint to valid address succeeds\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\treturn led.Mint(alice, \"1\")\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\tverify: func(t *testing.T, tok *Token, led *PrivateLedger) {\n\t\t\t\tuassert.Equal(t, int64(1), tok.TotalSupply())\n\t\t\t\tuassert.Equal(t, int64(1), mustBalanceOf(t, tok, alice))\n\t\t\t\tuassert.Equal(t, 1, tok.KnownAccounts())\n\t\t\t\towner, err := tok.OwnerOf(\"1\")\n\t\t\t\turequire.NoError(t, err)\n\t\t\t\tuassert.Equal(t, alice, owner)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"mint to invalid address returns ErrInvalidAddress\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\treturn led.Mint(zeroAddress, \"1\")\n\t\t\t},\n\t\t\twantErr: ErrInvalidAddress,\n\t\t\tverify: func(t *testing.T, tok *Token, led *PrivateLedger) {\n\t\t\t\tuassert.Equal(t, int64(0), tok.TotalSupply())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"mint duplicate token id returns ErrTokenIdAlreadyExists\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\treturn led.Mint(bob, \"1\")\n\t\t\t},\n\t\t\twantErr: ErrTokenIdAlreadyExists,\n\t\t\tverify: func(t *testing.T, tok *Token, led *PrivateLedger) {\n\t\t\t\towner, err := tok.OwnerOf(\"1\")\n\t\t\t\turequire.NoError(t, err)\n\t\t\t\tuassert.Equal(t, alice, owner)\n\t\t\t\tuassert.Equal(t, int64(1), tok.TotalSupply())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"minting distinct ids to same owner accumulates balance\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\treturn led.Mint(alice, \"2\")\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\tverify: func(t *testing.T, tok *Token, led *PrivateLedger) {\n\t\t\t\tuassert.Equal(t, int64(2), mustBalanceOf(t, tok, alice))\n\t\t\t\tuassert.Equal(t, int64(2), tok.TotalSupply())\n\t\t\t\tuassert.Equal(t, 1, tok.KnownAccounts())\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\ttok, led := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\t\t\terr := tc.action(led)\n\t\t\tif tc.wantErr == nil {\n\t\t\t\tuassert.NoError(t, err)\n\t\t\t} else {\n\t\t\t\tuassert.ErrorIs(t, err, tc.wantErr)\n\t\t\t}\n\t\t\tif tc.verify != nil {\n\t\t\t\ttc.verify(t, tok, led)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestBurn(cur realm, t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\taction  func(led *PrivateLedger) error\n\t\twantErr error\n\t\tverify  func(t *testing.T, tok *Token, led *PrivateLedger)\n\t}{\n\t\t{\n\t\t\tname: \"burn existing token clears all state\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\treturn led.Burn(\"1\")\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\tverify: func(t *testing.T, tok *Token, led *PrivateLedger) {\n\t\t\t\tuassert.Equal(t, int64(0), tok.TotalSupply())\n\t\t\t\tuassert.Equal(t, int64(0), mustBalanceOf(t, tok, alice))\n\t\t\t\tuassert.Equal(t, 0, tok.KnownAccounts())\n\t\t\t\t_, err := tok.OwnerOf(\"1\")\n\t\t\t\tuassert.ErrorIs(t, err, ErrInvalidTokenId)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"burn clears any outstanding approval\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\turequire.NoError(t, led.Approve(alice, bob, \"1\"))\n\t\t\t\treturn led.Burn(\"1\")\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\tverify: func(t *testing.T, tok *Token, led *PrivateLedger) {\n\t\t\t\tuassert.Equal(t, 0, led.tokenApprovals.Size())\n\t\t\t\t_, err := tok.GetApproved(\"1\")\n\t\t\t\tuassert.ErrorIs(t, err, ErrInvalidTokenId)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"burn missing token returns ErrInvalidTokenId\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\treturn led.Burn(\"999\")\n\t\t\t},\n\t\t\twantErr: ErrInvalidTokenId,\n\t\t},\n\t\t{\n\t\t\tname: \"burn one of two tokens keeps the account known\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"2\"))\n\t\t\t\treturn led.Burn(\"1\")\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\tverify: func(t *testing.T, tok *Token, led *PrivateLedger) {\n\t\t\t\tuassert.Equal(t, int64(1), mustBalanceOf(t, tok, alice))\n\t\t\t\tuassert.Equal(t, 1, tok.KnownAccounts())\n\t\t\t\tuassert.Equal(t, int64(1), tok.TotalSupply())\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\ttok, led := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\t\t\terr := tc.action(led)\n\t\t\tif tc.wantErr == nil {\n\t\t\t\tuassert.NoError(t, err)\n\t\t\t} else {\n\t\t\t\tuassert.ErrorIs(t, err, tc.wantErr)\n\t\t\t}\n\t\t\tif tc.verify != nil {\n\t\t\t\ttc.verify(t, tok, led)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestApprove(cur realm, t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\taction  func(led *PrivateLedger) error\n\t\twantErr error\n\t\tverify  func(t *testing.T, tok *Token, led *PrivateLedger)\n\t}{\n\t\t{\n\t\t\tname: \"owner approves another account\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\treturn led.Approve(alice, bob, \"1\")\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\tverify: func(t *testing.T, tok *Token, led *PrivateLedger) {\n\t\t\t\tapproved, err := tok.GetApproved(\"1\")\n\t\t\t\turequire.NoError(t, err)\n\t\t\t\tuassert.Equal(t, bob, approved)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"operator approves on behalf of owner\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\turequire.NoError(t, led.SetApprovalForAll(alice, bob, true))\n\t\t\t\treturn led.Approve(bob, carl, \"1\")\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\tverify: func(t *testing.T, tok *Token, led *PrivateLedger) {\n\t\t\t\tapproved, err := tok.GetApproved(\"1\")\n\t\t\t\turequire.NoError(t, err)\n\t\t\t\tuassert.Equal(t, carl, approved)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"approve to zero address revokes an existing approval (EIP-721)\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\turequire.NoError(t, led.Approve(alice, bob, \"1\"))\n\t\t\t\treturn led.Approve(alice, zeroAddress, \"1\")\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\tverify: func(t *testing.T, tok *Token, led *PrivateLedger) {\n\t\t\t\t_, err := tok.GetApproved(\"1\")\n\t\t\t\tuassert.ErrorIs(t, err, ErrTokenIdNotApproved)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"revoke with no prior approval is a no-op\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\treturn led.Approve(alice, zeroAddress, \"1\")\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\tverify: func(t *testing.T, tok *Token, led *PrivateLedger) {\n\t\t\t\t_, err := tok.GetApproved(\"1\")\n\t\t\t\tuassert.ErrorIs(t, err, ErrTokenIdNotApproved)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"approve on missing token returns ErrInvalidTokenId\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\treturn led.Approve(alice, bob, \"999\")\n\t\t\t},\n\t\t\twantErr: ErrInvalidTokenId,\n\t\t},\n\t\t{\n\t\t\tname: \"approve to current owner returns ErrApprovalToCurrentOwner\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\treturn led.Approve(alice, alice, \"1\")\n\t\t\t},\n\t\t\twantErr: ErrApprovalToCurrentOwner,\n\t\t},\n\t\t{\n\t\t\tname: \"non-owner non-operator approve returns ErrCallerIsNotOwnerOrApproved\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\treturn led.Approve(bob, carl, \"1\")\n\t\t\t},\n\t\t\twantErr: ErrCallerIsNotOwnerOrApproved,\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\ttok, led := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\t\t\terr := tc.action(led)\n\t\t\tif tc.wantErr == nil {\n\t\t\t\tuassert.NoError(t, err)\n\t\t\t} else {\n\t\t\t\tuassert.ErrorIs(t, err, tc.wantErr)\n\t\t\t}\n\t\t\tif tc.verify != nil {\n\t\t\t\ttc.verify(t, tok, led)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestSetApprovalForAll(cur realm, t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\taction  func(led *PrivateLedger) error\n\t\twantErr error\n\t\tverify  func(t *testing.T, tok *Token, led *PrivateLedger)\n\t}{\n\t\t{\n\t\t\tname: \"grant operator approval\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\treturn led.SetApprovalForAll(alice, bob, true)\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\tverify: func(t *testing.T, tok *Token, led *PrivateLedger) {\n\t\t\t\tuassert.True(t, tok.IsApprovedForAll(alice, bob))\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"revoke operator approval releases the node\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.SetApprovalForAll(alice, bob, true))\n\t\t\t\treturn led.SetApprovalForAll(alice, bob, false)\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\tverify: func(t *testing.T, tok *Token, led *PrivateLedger) {\n\t\t\t\tuassert.False(t, tok.IsApprovedForAll(alice, bob))\n\t\t\t\tuassert.Equal(t, 0, led.operatorApprovals.Size())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"revoke without a prior grant stores nothing\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\treturn led.SetApprovalForAll(alice, bob, false)\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\tverify: func(t *testing.T, tok *Token, led *PrivateLedger) {\n\t\t\t\tuassert.False(t, tok.IsApprovedForAll(alice, bob))\n\t\t\t\tuassert.Equal(t, 0, led.operatorApprovals.Size())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"invalid operator returns ErrInvalidAddress\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\treturn led.SetApprovalForAll(alice, zeroAddress, true)\n\t\t\t},\n\t\t\twantErr: ErrInvalidAddress,\n\t\t},\n\t\t{\n\t\t\tname: \"owner equals operator returns ErrApprovalToCurrentOwner\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\treturn led.SetApprovalForAll(alice, alice, true)\n\t\t\t},\n\t\t\twantErr: ErrApprovalToCurrentOwner,\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\ttok, led := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\t\t\terr := tc.action(led)\n\t\t\tif tc.wantErr == nil {\n\t\t\t\tuassert.NoError(t, err)\n\t\t\t} else {\n\t\t\t\tuassert.ErrorIs(t, err, tc.wantErr)\n\t\t\t}\n\t\t\tif tc.verify != nil {\n\t\t\t\ttc.verify(t, tok, led)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestTransferFrom(cur realm, t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\taction  func(led *PrivateLedger) error\n\t\twantErr error\n\t\tverify  func(t *testing.T, tok *Token, led *PrivateLedger)\n\t}{\n\t\t{\n\t\t\tname: \"owner transfers own token\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\treturn led.TransferFrom(alice, alice, bob, \"1\")\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\tverify: func(t *testing.T, tok *Token, led *PrivateLedger) {\n\t\t\t\towner, err := tok.OwnerOf(\"1\")\n\t\t\t\turequire.NoError(t, err)\n\t\t\t\tuassert.Equal(t, bob, owner)\n\t\t\t\tuassert.Equal(t, int64(0), mustBalanceOf(t, tok, alice))\n\t\t\t\tuassert.Equal(t, int64(1), mustBalanceOf(t, tok, bob))\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"approved spender transfers and approval is cleared\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\turequire.NoError(t, led.Approve(alice, bob, \"1\"))\n\t\t\t\treturn led.TransferFrom(bob, alice, carl, \"1\")\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\tverify: func(t *testing.T, tok *Token, led *PrivateLedger) {\n\t\t\t\towner, err := tok.OwnerOf(\"1\")\n\t\t\t\turequire.NoError(t, err)\n\t\t\t\tuassert.Equal(t, carl, owner)\n\t\t\t\t_, err = tok.GetApproved(\"1\")\n\t\t\t\tuassert.ErrorIs(t, err, ErrTokenIdNotApproved)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"operator transfers owner token\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\turequire.NoError(t, led.SetApprovalForAll(alice, bob, true))\n\t\t\t\treturn led.TransferFrom(bob, alice, carl, \"1\")\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\tverify: func(t *testing.T, tok *Token, led *PrivateLedger) {\n\t\t\t\towner, err := tok.OwnerOf(\"1\")\n\t\t\t\turequire.NoError(t, err)\n\t\t\t\tuassert.Equal(t, carl, owner)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"unauthorized spender returns ErrCallerIsNotOwnerOrApproved\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\treturn led.TransferFrom(bob, alice, carl, \"1\")\n\t\t\t},\n\t\t\twantErr: ErrCallerIsNotOwnerOrApproved,\n\t\t},\n\t\t{\n\t\t\tname: \"spender on missing token returns ErrCallerIsNotOwnerOrApproved\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\treturn led.TransferFrom(alice, alice, bob, \"999\")\n\t\t\t},\n\t\t\twantErr: ErrCallerIsNotOwnerOrApproved,\n\t\t},\n\t\t{\n\t\t\tname: \"transfer to self returns ErrCannotTransferToSelf\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\treturn led.TransferFrom(alice, alice, alice, \"1\")\n\t\t\t},\n\t\t\twantErr: ErrCannotTransferToSelf,\n\t\t},\n\t\t{\n\t\t\tname: \"transfer from invalid address returns ErrInvalidAddress\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\treturn led.TransferFrom(alice, zeroAddress, bob, \"1\")\n\t\t\t},\n\t\t\twantErr: ErrInvalidAddress,\n\t\t},\n\t\t{\n\t\t\tname: \"transfer to invalid address returns ErrInvalidAddress\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\treturn led.TransferFrom(alice, alice, zeroAddress, \"1\")\n\t\t\t},\n\t\t\twantErr: ErrInvalidAddress,\n\t\t},\n\t\t{\n\t\t\tname: \"transfer from incorrect owner returns ErrTransferFromIncorrectOwner\",\n\t\t\taction: func(led *PrivateLedger) error {\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\treturn led.TransferFrom(alice, bob, carl, \"1\")\n\t\t\t},\n\t\t\twantErr: ErrTransferFromIncorrectOwner,\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\ttok, led := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\t\t\terr := tc.action(led)\n\t\t\tif tc.wantErr == nil {\n\t\t\t\tuassert.NoError(t, err)\n\t\t\t} else {\n\t\t\t\tuassert.ErrorIs(t, err, tc.wantErr)\n\t\t\t}\n\t\t\tif tc.verify != nil {\n\t\t\t\ttc.verify(t, tok, led)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestReadViews(cur realm, t *testing.T) {\n\ttok, led := newTestToken(\"Foo NFT\", \"FOO\", 0, cur)\n\turequire.NoError(t, led.Mint(alice, \"1\"))\n\turequire.NoError(t, led.Mint(alice, \"2\"))\n\turequire.NoError(t, led.Mint(bob, \"3\"))\n\turequire.NoError(t, led.Approve(alice, carl, \"1\"))\n\turequire.NoError(t, led.SetApprovalForAll(alice, bob, true))\n\n\ttests := []struct {\n\t\tname  string\n\t\tcheck func(t *testing.T)\n\t}{\n\t\t{\"GetName returns collection name\", func(t *testing.T) {\n\t\t\tuassert.Equal(t, \"Foo NFT\", tok.GetName())\n\t\t}},\n\t\t{\"GetSymbol returns collection symbol\", func(t *testing.T) {\n\t\t\tuassert.Equal(t, \"FOO\", tok.GetSymbol())\n\t\t}},\n\t\t{\"ID carries realm, symbol and seqid\", func(t *testing.T) {\n\t\t\tuassert.True(t, strings.HasPrefix(tok.ID(), \"gno.land/\"))\n\t\t\tuassert.True(t, strings.Contains(tok.ID(), \".FOO.\"))\n\t\t}},\n\t\t{\"TotalSupply counts live tokens\", func(t *testing.T) {\n\t\t\tuassert.Equal(t, int64(3), tok.TotalSupply())\n\t\t}},\n\t\t{\"KnownAccounts counts distinct holders\", func(t *testing.T) {\n\t\t\tuassert.Equal(t, 2, tok.KnownAccounts())\n\t\t}},\n\t\t{\"BalanceOf of a holder\", func(t *testing.T) {\n\t\t\tuassert.Equal(t, int64(2), mustBalanceOf(t, tok, alice))\n\t\t}},\n\t\t{\"BalanceOf of a non-holder is zero\", func(t *testing.T) {\n\t\t\tuassert.Equal(t, int64(0), mustBalanceOf(t, tok, carl))\n\t\t}},\n\t\t{\"BalanceOf of the zero address returns ErrInvalidAddress\", func(t *testing.T) {\n\t\t\t_, err := tok.BalanceOf(zeroAddress)\n\t\t\tuassert.ErrorIs(t, err, ErrInvalidAddress)\n\t\t}},\n\t\t{\"OwnerOf existing token\", func(t *testing.T) {\n\t\t\towner, err := tok.OwnerOf(\"3\")\n\t\t\turequire.NoError(t, err)\n\t\t\tuassert.Equal(t, bob, owner)\n\t\t}},\n\t\t{\"OwnerOf missing token returns ErrInvalidTokenId\", func(t *testing.T) {\n\t\t\t_, err := tok.OwnerOf(\"999\")\n\t\t\tuassert.ErrorIs(t, err, ErrInvalidTokenId)\n\t\t}},\n\t\t{\"GetApproved returns the approved account\", func(t *testing.T) {\n\t\t\tapproved, err := tok.GetApproved(\"1\")\n\t\t\turequire.NoError(t, err)\n\t\t\tuassert.Equal(t, carl, approved)\n\t\t}},\n\t\t{\"GetApproved on unapproved token returns ErrTokenIdNotApproved\", func(t *testing.T) {\n\t\t\t_, err := tok.GetApproved(\"2\")\n\t\t\tuassert.ErrorIs(t, err, ErrTokenIdNotApproved)\n\t\t}},\n\t\t{\"GetApproved on missing token returns ErrInvalidTokenId\", func(t *testing.T) {\n\t\t\t_, err := tok.GetApproved(\"999\")\n\t\t\tuassert.ErrorIs(t, err, ErrInvalidTokenId)\n\t\t}},\n\t\t{\"IsApprovedForAll true for operator\", func(t *testing.T) {\n\t\t\tuassert.True(t, tok.IsApprovedForAll(alice, bob))\n\t\t}},\n\t\t{\"IsApprovedForAll false for non-operator\", func(t *testing.T) {\n\t\t\tuassert.False(t, tok.IsApprovedForAll(alice, carl))\n\t\t}},\n\t\t{\"RenderHome renders header and counters\", func(t *testing.T) {\n\t\t\tout := tok.RenderHome()\n\t\t\tuassert.True(t, strings.Contains(out, \"# Foo NFT ($FOO)\"), \"header\")\n\t\t\tuassert.True(t, strings.Contains(out, \"**Total supply**: 3\"), \"supply\")\n\t\t\tuassert.True(t, strings.Contains(out, \"**Known accounts**: 2\"), \"accounts\")\n\t\t}},\n\t}\n\n\tfor _, tc := range tests {\n\t\ttc := tc\n\t\tt.Run(tc.name, tc.check)\n\t}\n}\n\nfunc TestRegisterExtensionNil(cur realm, t *testing.T) {\n\t_, led := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\tuassert.PanicsWithMessage(t, cur, \"grc721: nil extension\", func() {\n\t\tled.RegisterExtension(nil)\n\t})\n}\n\nfunc TestRegisterExtensionRejectsDuplicateKind(cur realm, t *testing.T) {\n\t_, led := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\text := \u0026mockExtension{}\n\tled.RegisterExtension(ext)\n\n\tuassert.PanicsWithMessage(t, cur, \"grc721: extension kind already registered: mock\", func() {\n\t\tled.RegisterExtension(ext)\n\t})\n\tuassert.PanicsWithMessage(t, cur, \"grc721: extension kind already registered: mock\", func() {\n\t\tled.RegisterExtension(\u0026mockExtension{})\n\t})\n}\n\nfunc TestRegisterExtensionRejectsDuplicateKindOfUncomparableType(cur realm, t *testing.T) {\n\t_, led := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\tled.RegisterExtension(journalExtension{seen: []TokenID{\"1\"}})\n\n\tuassert.PanicsWithMessage(t, cur, \"grc721: extension kind already registered: journal\", func() {\n\t\tled.RegisterExtension(journalExtension{seen: []TokenID{\"2\"}})\n\t})\n}\n\nfunc TestExtensionHookFanOut(cur realm, t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\trun    func(t *testing.T, led *PrivateLedger, ext *mockExtension)\n\t\tverify func(t *testing.T, ext *mockExtension)\n\t}{\n\t\t{\n\t\t\tname: \"mint, transfer and burn each notify the extension\",\n\t\t\trun: func(t *testing.T, led *PrivateLedger, ext *mockExtension) {\n\t\t\t\tled.RegisterExtension(ext)\n\t\t\t\turequire.NoError(t, led.Mint(alice, \"1\"))\n\t\t\t\turequire.NoError(t, led.TransferFrom(alice, alice, bob, \"1\"))\n\t\t\t\turequire.NoError(t, led.Burn(\"1\"))\n\t\t\t},\n\t\t\tverify: func(t *testing.T, ext *mockExtension) {\n\t\t\t\tuassert.Equal(t, 1, ext.mints)\n\t\t\t\tuassert.Equal(t, 1, ext.transfers)\n\t\t\t\tuassert.Equal(t, alice, ext.lastTransferFrom)\n\t\t\t\tuassert.Equal(t, bob, ext.lastTransferTo)\n\t\t\t\tuassert.Equal(t, 1, ext.burns)\n\t\t\t\tuassert.Equal(t, \"1\", ext.lastBurn.String())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"failed operations do not notify the extension\",\n\t\t\trun: func(t *testing.T, led *PrivateLedger, ext *mockExtension) {\n\t\t\t\tled.RegisterExtension(ext)\n\t\t\t\tuassert.ErrorIs(t, led.Mint(zeroAddress, \"1\"), ErrInvalidAddress)\n\t\t\t\tuassert.ErrorIs(t, led.Burn(\"999\"), ErrInvalidTokenId)\n\t\t\t},\n\t\t\tverify: func(t *testing.T, ext *mockExtension) {\n\t\t\t\tuassert.Equal(t, 0, ext.mints)\n\t\t\t\tuassert.Equal(t, 0, ext.burns)\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t_, led := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\t\t\text := \u0026mockExtension{}\n\t\t\ttc.run(t, led, ext)\n\t\t\ttc.verify(t, ext)\n\t\t})\n\t}\n}\n\nfunc TestReadToken(cur realm, t *testing.T) {\n\ttok, led := newTestToken(\"Foo\", \"FOO\", 0, cur)\n\tuassert.Equal(t, tok.ID(), led.ReadToken().ID())\n\tuassert.True(t, led.ReadToken() == tok, \"ReadToken returns the same *Token\")\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 // origRealm + \".\" + 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"},{"name":"veto_no_event_filetest.gno","body":"// PKGPATH: gno.land/r/demo/grc721veto\n\n// Extension hooks run before the Transfer event is emitted, so a hook that vetoes\n// a movement leaves nothing on the event stream. Only the second mint, which no\n// hook refuses, is announced.\npackage grc721veto\n\nimport (\n\t\"gno.land/p/demo/tokens/grc721\"\n)\n\ntype vetoExtension struct {\n\trefuse grc721.TokenID\n}\n\nfunc (e *vetoExtension) ExtensionKind() string { return \"veto\" }\n\nfunc (e *vetoExtension) OnMint(to address, tid grc721.TokenID) {\n\tif tid == e.refuse {\n\t\tpanic(\"veto: mint refused\")\n\t}\n}\n\nfunc (e *vetoExtension) OnTransfer(from, to address, tid grc721.TokenID) {}\n\nfunc (e *vetoExtension) OnBurn(tid grc721.TokenID) {}\n\nfunc main(cur realm) {\n\t_, ledger := grc721.NewToken(\"Veto\", \"VETO\", 0, cur)\n\tledger.RegisterExtension(\u0026vetoExtension{refuse: \"1\"})\n\n\tfunc() {\n\t\tdefer func() { println(\"recovered:\", recover()) }()\n\t\tledger.Mint(cur.Address(), \"1\")\n\t}()\n\n\tledger.Mint(cur.Address(), \"2\")\n}\n\n// Output:\n// recovered: veto: mint refused\n\n// Events:\n// [\n//   {\n//     \"type\": \"NewToken\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/grc721veto.VETO.0000000\"\n//       },\n//       {\n//         \"key\": \"name\",\n//         \"value\": \"Veto\"\n//       },\n//       {\n//         \"key\": \"symbol\",\n//         \"value\": \"VETO\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/p/demo/tokens/grc721\"\n//   },\n//   {\n//     \"type\": \"Transfer\",\n//     \"attrs\": [\n//       {\n//         \"key\": \"token\",\n//         \"value\": \"gno.land/r/demo/grc721veto.VETO.0000000\"\n//       },\n//       {\n//         \"key\": \"from\",\n//         \"value\": \"\"\n//       },\n//       {\n//         \"key\": \"to\",\n//         \"value\": \"g1dywcn8v2jdpl6fuks8tw3l8gnzer0hv8mfkraa\"\n//       },\n//       {\n//         \"key\": \"tokenId\",\n//         \"value\": \"2\"\n//       }\n//     ],\n//     \"pkg_path\": \"gno.land/p/demo/tokens/grc721\"\n//   }\n// ]\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"ONU9hrBlwXPPoc55oz5JTuwqgnTUPMvryWeYak1HAo0K7Z7IuFYkkRVpCpgIutyiNqSeBqb5w5MORyLzXEsMag=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"enumerable","path":"gno.land/p/demo/tokens/grc721/enumerable","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/tokens/grc721/enumerable\"\ngno = \"0.9\"\n"},{"name":"token.gno","body":"package enumerable\n\nimport (\n\t\"gno.land/p/demo/tokens/grc721\"\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":"token_test.gno","body":"package enumerable\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/demo/tokens/grc721\"\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\n// Same-realm cross: NewToken requires rlm.IsCurrent().\nfunc newCore(name, symbol string, id seqid.ID, rlm realm) (tok *grc721.Token, led *grc721.PrivateLedger) {\n\tfunc(cur realm) {\n\t\ttok, led = grc721.NewToken(name, symbol, id, cur)\n\t}(cross(rlm))\n\n\treturn\n}\n\nfunc newEnum(cur realm) (enum *Enumerable, core *grc721.PrivateLedger, led *Ledger) {\n\t_, coreLedger := newCore(\"Foo\", \"FOO\", 0, cur)\n\tenum, led = NewEnumerable(coreLedger)\n\treturn enum, coreLedger, led\n}\n\nfunc globalOrder(t *testing.T, enum *Enumerable) []string {\n\tt.Helper()\n\tout := []string{}\n\tfor i := int64(0); i \u003c enum.TotalSupply(); i++ {\n\t\ttid, err := enum.TokenByIndex(i)\n\t\turequire.NoError(t, err)\n\t\tout = append(out, tid.String())\n\t}\n\treturn out\n}\n\nfunc ownerOrder(t *testing.T, enum *Enumerable, owner address) []string {\n\tt.Helper()\n\tout := []string{}\n\tfor i := int64(0); ; i++ {\n\t\ttid, err := enum.TokenOfOwnerByIndex(owner, i)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tout = append(out, tid.String())\n\t}\n\treturn out\n}\n\nfunc eqStrings(t *testing.T, name string, got, want []string) {\n\tt.Helper()\n\tif len(got) != len(want) {\n\t\tt.Errorf(\"%s: length got %d want %d (%v vs %v)\", name, len(got), len(want), got, want)\n\t\treturn\n\t}\n\tfor i := range want {\n\t\tuassert.Equal(t, want[i], got[i])\n\t}\n}\n\nfunc TestNewEnumerable(cur realm, t *testing.T) {\n\tuassert.PanicsWithMessage(t, cur, \"enumerable: nil core ledger\", func() {\n\t\tNewEnumerable(nil)\n\t})\n\n\ttok, coreLedger := newCore(\"Foo\", \"FOO\", 0, cur)\n\tenum, led := NewEnumerable(coreLedger)\n\n\turequire.True(t, enum != nil, \"enum built\")\n\turequire.True(t, led != nil, \"ledger built\")\n\n\ttests := []struct {\n\t\tname string\n\t\tgot  string\n\t\twant string\n\t}{\n\t\t{\"ExtensionKind is enumerable\", enum.ExtensionKind(), Kind},\n\t\t{\"ExtensionKind constant value\", Kind, \"enumerable\"},\n\t\t{\"TokenID matches core token id\", enum.TokenID(), tok.ID()},\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, tt.got)\n\t\t})\n\t}\n\n\tuassert.Equal(t, int64(0), enum.TotalSupply())\n}\n\nfunc TestReadIndices(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\tcarol := testutils.TestAddress(\"carol\")\n\n\tenum, coreLedger, _ := newEnum(cur)\n\turequire.NoError(t, coreLedger.Mint(alice, \"1\"))\n\turequire.NoError(t, coreLedger.Mint(alice, \"2\"))\n\turequire.NoError(t, coreLedger.Mint(bob, \"3\"))\n\n\tuassert.Equal(t, int64(3), enum.TotalSupply())\n\n\ttests := []struct {\n\t\tname string\n\t\trun  func(t *testing.T)\n\t}{\n\t\t{\"TokenByIndex 0 returns first minted\", func(t *testing.T) {\n\t\t\ttid, err := enum.TokenByIndex(0)\n\t\t\turequire.NoError(t, err)\n\t\t\tuassert.Equal(t, \"1\", tid.String())\n\t\t}},\n\t\t{\"TokenByIndex last returns last minted\", func(t *testing.T) {\n\t\t\ttid, err := enum.TokenByIndex(2)\n\t\t\turequire.NoError(t, err)\n\t\t\tuassert.Equal(t, \"3\", tid.String())\n\t\t}},\n\t\t{\"TokenByIndex negative returns ErrIndexOutOfRange\", func(t *testing.T) {\n\t\t\t_, err := enum.TokenByIndex(-1)\n\t\t\tuassert.ErrorIs(t, err, ErrIndexOutOfRange)\n\t\t}},\n\t\t{\"TokenByIndex out of range returns ErrIndexOutOfRange\", func(t *testing.T) {\n\t\t\t_, err := enum.TokenByIndex(3)\n\t\t\tuassert.ErrorIs(t, err, ErrIndexOutOfRange)\n\t\t}},\n\t\t{\"TokenOfOwnerByIndex returns owner's token\", func(t *testing.T) {\n\t\t\ttid, err := enum.TokenOfOwnerByIndex(alice, 1)\n\t\t\turequire.NoError(t, err)\n\t\t\tuassert.Equal(t, \"2\", tid.String())\n\t\t}},\n\t\t{\"TokenOfOwnerByIndex unknown owner returns ErrIndexOutOfRange\", func(t *testing.T) {\n\t\t\t_, err := enum.TokenOfOwnerByIndex(carol, 0)\n\t\t\tuassert.ErrorIs(t, err, ErrIndexOutOfRange)\n\t\t}},\n\t\t{\"TokenOfOwnerByIndex negative index returns ErrIndexOutOfRange\", func(t *testing.T) {\n\t\t\t_, err := enum.TokenOfOwnerByIndex(alice, -1)\n\t\t\tuassert.ErrorIs(t, err, ErrIndexOutOfRange)\n\t\t}},\n\t\t{\"TokenOfOwnerByIndex past end returns ErrIndexOutOfRange\", func(t *testing.T) {\n\t\t\t_, err := enum.TokenOfOwnerByIndex(alice, 2)\n\t\t\tuassert.ErrorIs(t, err, ErrIndexOutOfRange)\n\t\t}},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, tt.run)\n\t}\n\n\teqStrings(t, \"global order\", globalOrder(t, enum), []string{\"1\", \"2\", \"3\"})\n\teqStrings(t, \"alice order\", ownerOrder(t, enum, alice), []string{\"1\", \"2\"})\n\teqStrings(t, \"bob order\", ownerOrder(t, enum, bob), []string{\"3\"})\n}\n\nfunc TestBurnGlobalSwapAndPop(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\n\ttests := []struct {\n\t\tname      string\n\t\tburn      grc721.TokenID\n\t\twantOrder []string\n\t}{\n\t\t{\"burn last token truncates global list (idx == last)\", \"3\", []string{\"1\", \"2\"}},\n\t\t{\"burn middle token swap-and-pops the global list (idx != last)\", \"2\", []string{\"1\", \"3\"}},\n\t\t{\"burn first token swap-and-pops the global list (idx != last)\", \"1\", []string{\"3\", \"2\"}},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tenum, coreLedger, _ := newEnum(cur)\n\t\t\turequire.NoError(t, coreLedger.Mint(alice, \"1\"))\n\t\t\turequire.NoError(t, coreLedger.Mint(alice, \"2\"))\n\t\t\turequire.NoError(t, coreLedger.Mint(alice, \"3\"))\n\n\t\t\turequire.NoError(t, coreLedger.Burn(tt.burn))\n\n\t\t\tuassert.Equal(t, int64(2), enum.TotalSupply())\n\t\t\teqStrings(t, tt.name, globalOrder(t, enum), tt.wantOrder)\n\t\t})\n\t}\n}\n\nfunc TestBurnOwnerSwapAndPop(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\n\ttests := []struct {\n\t\tname       string\n\t\tmint       []grc721.TokenID\n\t\tburn       grc721.TokenID\n\t\twantOwner  []string\n\t\townerEmpty bool\n\t}{\n\t\t{\n\t\t\tname:      \"burn first of owner swap-and-pops per-owner list (idx != last)\",\n\t\t\tmint:      []grc721.TokenID{\"1\", \"2\", \"3\"},\n\t\t\tburn:      \"1\",\n\t\t\twantOwner: []string{\"3\", \"2\"},\n\t\t},\n\t\t{\n\t\t\tname:      \"burn middle of owner swap-and-pops per-owner list (idx != last)\",\n\t\t\tmint:      []grc721.TokenID{\"1\", \"2\", \"3\"},\n\t\t\tburn:      \"2\",\n\t\t\twantOwner: []string{\"1\", \"3\"},\n\t\t},\n\t\t{\n\t\t\tname:      \"burn last of owner truncates per-owner list (idx == last)\",\n\t\t\tmint:      []grc721.TokenID{\"1\", \"2\", \"3\"},\n\t\t\tburn:      \"3\",\n\t\t\twantOwner: []string{\"1\", \"2\"},\n\t\t},\n\t\t{\n\t\t\tname:       \"burn only token empties per-owner list (owned.Remove)\",\n\t\t\tmint:       []grc721.TokenID{\"1\"},\n\t\t\tburn:       \"1\",\n\t\t\townerEmpty: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tenum, coreLedger, _ := newEnum(cur)\n\t\t\tfor _, tid := range tt.mint {\n\t\t\t\turequire.NoError(t, coreLedger.Mint(alice, tid))\n\t\t\t}\n\n\t\t\turequire.NoError(t, coreLedger.Burn(tt.burn))\n\n\t\t\tif tt.ownerEmpty {\n\t\t\t\t_, err := enum.TokenOfOwnerByIndex(alice, 0)\n\t\t\t\tuassert.ErrorIs(t, err, ErrIndexOutOfRange)\n\t\t\t\treturn\n\t\t\t}\n\t\t\teqStrings(t, tt.name, ownerOrder(t, enum, alice), tt.wantOwner)\n\t\t})\n\t}\n}\n\nfunc TestTransfer(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\tenum, coreLedger, _ := newEnum(cur)\n\turequire.NoError(t, coreLedger.Mint(alice, \"1\"))\n\turequire.NoError(t, coreLedger.Mint(alice, \"2\"))\n\turequire.NoError(t, coreLedger.Mint(bob, \"3\"))\n\n\ttests := []struct {\n\t\tname string\n\t\trun  func(t *testing.T)\n\t}{\n\t\t{\"transfer 1 alice-\u003ebob swap-and-pops alice list\", func(t *testing.T) {\n\t\t\turequire.NoError(t, coreLedger.TransferFrom(alice, alice, bob, \"1\"))\n\t\t\teqStrings(t, \"alice after transfer\", ownerOrder(t, enum, alice), []string{\"2\"})\n\t\t\teqStrings(t, \"bob after transfer\", ownerOrder(t, enum, bob), []string{\"3\", \"1\"})\n\t\t}},\n\t\t{\"transfer 2 alice-\u003ebob empties alice list\", func(t *testing.T) {\n\t\t\turequire.NoError(t, coreLedger.TransferFrom(alice, alice, bob, \"2\"))\n\t\t\t_, err := enum.TokenOfOwnerByIndex(alice, 0)\n\t\t\tuassert.ErrorIs(t, err, ErrIndexOutOfRange)\n\t\t\teqStrings(t, \"bob owns all\", ownerOrder(t, enum, bob), []string{\"3\", \"1\", \"2\"})\n\t\t}},\n\t\t{\"global supply unchanged by transfers\", func(t *testing.T) {\n\t\t\tuassert.Equal(t, int64(3), enum.TotalSupply())\n\t\t}},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, tt.run)\n\t}\n}\n\nfunc TestDefensiveNoOps(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\n\tenum, coreLedger, led := newEnum(cur)\n\turequire.NoError(t, coreLedger.Mint(alice, \"1\"))\n\n\ttests := []struct {\n\t\tname string\n\t\trun  func(t *testing.T)\n\t}{\n\t\t{\"removeFromAll unknown id is a no-op\", func(t *testing.T) {\n\t\t\tled.removeFromAll(\"999\")\n\t\t\tuassert.Equal(t, int64(1), enum.TotalSupply())\n\t\t}},\n\t\t{\"removeFromOwner unknown owner is a no-op\", func(t *testing.T) {\n\t\t\tled.removeFromOwner(bob, \"1\")\n\t\t\teqStrings(t, \"alice untouched\", ownerOrder(t, enum, alice), []string{\"1\"})\n\t\t}},\n\t\t{\"removeFromOwner known owner unknown id is a no-op\", func(t *testing.T) {\n\t\t\tled.removeFromOwner(alice, \"999\")\n\t\t\teqStrings(t, \"alice untouched\", ownerOrder(t, enum, alice), []string{\"1\"})\n\t\t}},\n\t\t{\"OnBurn of never-minted id is a no-op\", func(t *testing.T) {\n\t\t\tled.OnBurn(\"neverminted\")\n\t\t\tuassert.Equal(t, int64(1), enum.TotalSupply())\n\t\t\teqStrings(t, \"alice untouched\", ownerOrder(t, enum, alice), []string{\"1\"})\n\t\t}},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, tt.run)\n\t}\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/demo/tokens/grc721\"\n\t\"gno.land/p/nt/avl/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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"rxGGe6rAQ9cXXn79QHE/4BUmsRJIMNTah9wYDbb7vWoO5CjywloHuMinkPawbv4uB1CoOF78eLXa9QOilbEc/Q=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"metadata","path":"gno.land/p/demo/tokens/grc721/metadata","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/tokens/grc721/metadata\"\ngno = \"0.9\"\n"},{"name":"token.gno","body":"package metadata\n\nimport (\n\t\"chain\"\n\n\t\"gno.land/p/demo/tokens/grc721\"\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":"token_test.gno","body":"package metadata\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/demo/tokens/grc721\"\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\n// newToken builds via same-realm cross (NewToken requires rlm.IsCurrent()).\nfunc newToken(name, symbol string, id seqid.ID, rlm realm) (tok *grc721.Token, led *grc721.PrivateLedger) {\n\tfunc(cur realm) {\n\t\ttok, led = grc721.NewToken(name, symbol, id, cur)\n\t}(cross(rlm))\n\treturn\n}\n\nfunc newMeta(id seqid.ID, rlm realm) (*grc721.PrivateLedger, *Metadata, *Ledger) {\n\t_, tokenLedger := newToken(\"Foo\", \"FOO\", id, rlm)\n\tmeta, metaLedger := NewMetadata(tokenLedger)\n\treturn tokenLedger, meta, metaLedger\n}\n\nfunc TestNewMetadata(cur realm, t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tnilLedger bool\n\t}{\n\t\t{\"nil token ledger panics\", true},\n\t\t{\"valid token ledger constructs read view and ledger\", false},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif tt.nilLedger {\n\t\t\t\tuassert.PanicsWithMessage(t, cur, \"metadata: nil core ledger\", func() {\n\t\t\t\t\tNewMetadata(nil)\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t_, tokenLedger := newToken(\"Foo\", \"FOO\", 0, cur)\n\t\t\tmeta, metaLedger := NewMetadata(tokenLedger)\n\n\t\t\tuassert.True(t, meta != nil)\n\t\t\tuassert.True(t, metaLedger != nil)\n\t\t\tuassert.Equal(t, Kind, meta.ExtensionKind())\n\t\t\tuassert.Equal(t, \"metadata\", meta.ExtensionKind())\n\t\t\tuassert.Equal(t, tokenLedger.ReadToken().ID(), meta.TokenID())\n\t\t})\n\t}\n}\n\nfunc TestSetTokenURI(cur realm, t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tmint    bool\n\t\ttid     grc721.TokenID\n\t\turi     string\n\t\twantErr error\n\t}{\n\t\t{\"unminted token returns ErrTokenNotMinted\", false, \"404\", \"ipfs://x\", ErrTokenNotMinted},\n\t\t{\"minted token sets uri\", true, \"1\", \"ipfs://uri-1\", nil},\n\t\t{\"empty uri on minted token is allowed\", true, \"1\", \"\", nil},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttokenLedger, meta, metaLedger := newMeta(0, cur)\n\t\t\tif tt.mint {\n\t\t\t\turequire.NoError(t, tokenLedger.Mint(testutils.TestAddress(\"alice\"), tt.tid))\n\t\t\t}\n\n\t\t\terr := metaLedger.SetTokenURI(tt.tid, tt.uri)\n\t\t\tif tt.wantErr != nil {\n\t\t\t\tuassert.ErrorIs(t, err, tt.wantErr)\n\t\t\t\tuassert.False(t, meta.HasTokenURI(tt.tid))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.NoError(t, err)\n\t\t\tuassert.True(t, meta.HasTokenURI(tt.tid))\n\t\t\tgot, err := meta.TokenURI(tt.tid)\n\t\t\turequire.NoError(t, err)\n\t\t\tuassert.Equal(t, tt.uri, got)\n\t\t})\n\t}\n}\n\nfunc TestSetTokenURIOverwrite(cur realm, t *testing.T) {\n\ttokenLedger, meta, metaLedger := newMeta(0, cur)\n\turequire.NoError(t, tokenLedger.Mint(testutils.TestAddress(\"alice\"), \"1\"))\n\n\turequire.NoError(t, metaLedger.SetTokenURI(\"1\", \"ipfs://first\"))\n\turequire.NoError(t, metaLedger.SetTokenURI(\"1\", \"ipfs://second\"))\n\n\tgot, err := meta.TokenURI(\"1\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"ipfs://second\", got)\n}\n\nfunc TestSetTokenMetadata(cur realm, t *testing.T) {\n\tfull := Data{\n\t\tImage:           \"ipfs://img-1\",\n\t\tImageData:       \"\u003csvg/\u003e\",\n\t\tExternalURL:     \"https://example.com/1\",\n\t\tDescription:     \"first\",\n\t\tName:            \"Token One\",\n\t\tAttributes:      []Trait{{DisplayType: \"string\", TraitType: \"rarity\", Value: \"rare\"}},\n\t\tBackgroundColor: \"ffffff\",\n\t\tAnimationURL:    \"ipfs://anim-1\",\n\t\tYoutubeURL:      \"https://youtu.be/abc\",\n\t}\n\n\ttests := []struct {\n\t\tname    string\n\t\tmint    bool\n\t\ttid     grc721.TokenID\n\t\tdata    Data\n\t\twantErr error\n\t}{\n\t\t{\"unminted token returns ErrTokenNotMinted\", false, \"404\", Data{Name: \"x\"}, ErrTokenNotMinted},\n\t\t{\"minted token stores full metadata\", true, \"1\", full, nil},\n\t\t{\"minted token stores zero-value metadata\", true, \"2\", Data{}, nil},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttokenLedger, meta, metaLedger := newMeta(0, cur)\n\t\t\tif tt.mint {\n\t\t\t\turequire.NoError(t, tokenLedger.Mint(testutils.TestAddress(\"alice\"), tt.tid))\n\t\t\t}\n\n\t\t\terr := metaLedger.SetTokenMetadata(tt.tid, tt.data)\n\t\t\tif tt.wantErr != nil {\n\t\t\t\tuassert.ErrorIs(t, err, tt.wantErr)\n\t\t\t\tuassert.False(t, meta.HasMetadata(tt.tid))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.NoError(t, err)\n\t\t\tuassert.True(t, meta.HasMetadata(tt.tid))\n\t\t\tgot, err := meta.TokenMetadata(tt.tid)\n\t\t\turequire.NoError(t, err)\n\t\t\tuassert.Equal(t, tt.data.Name, got.Name)\n\t\t\tuassert.Equal(t, tt.data.Description, got.Description)\n\t\t\tuassert.Equal(t, tt.data.Image, got.Image)\n\t\t\tuassert.Equal(t, len(tt.data.Attributes), len(got.Attributes))\n\t\t\tif len(tt.data.Attributes) \u003e 0 {\n\t\t\t\tuassert.Equal(t, tt.data.Attributes[0].Value, got.Attributes[0].Value)\n\t\t\t\tuassert.Equal(t, tt.data.Attributes[0].TraitType, got.Attributes[0].TraitType)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestSetTokenMetadataOverwrite(cur realm, t *testing.T) {\n\ttokenLedger, meta, metaLedger := newMeta(0, cur)\n\turequire.NoError(t, tokenLedger.Mint(testutils.TestAddress(\"alice\"), \"1\"))\n\n\turequire.NoError(t, metaLedger.SetTokenMetadata(\"1\", Data{Name: \"first\"}))\n\turequire.NoError(t, metaLedger.SetTokenMetadata(\"1\", Data{Name: \"second\"}))\n\n\tgot, err := meta.TokenMetadata(\"1\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"second\", got.Name)\n}\n\nfunc TestReadsOnUnsetToken(cur realm, t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tfn   func(t *testing.T, meta *Metadata)\n\t}{\n\t\t{\"TokenURI on unset token returns ErrNoTokenURI\", func(t *testing.T, meta *Metadata) {\n\t\t\turi, err := meta.TokenURI(\"1\")\n\t\t\tuassert.Equal(t, \"\", uri)\n\t\t\tuassert.ErrorIs(t, err, ErrNoTokenURI)\n\t\t}},\n\t\t{\"TokenMetadata on unset token returns ErrNoMetadata\", func(t *testing.T, meta *Metadata) {\n\t\t\tdata, err := meta.TokenMetadata(\"1\")\n\t\t\tuassert.Equal(t, \"\", data.Name)\n\t\t\tuassert.ErrorIs(t, err, ErrNoMetadata)\n\t\t}},\n\t\t{\"HasTokenURI is false on unset token\", func(t *testing.T, meta *Metadata) {\n\t\t\tuassert.False(t, meta.HasTokenURI(\"1\"))\n\t\t}},\n\t\t{\"HasMetadata is false on unset token\", func(t *testing.T, meta *Metadata) {\n\t\t\tuassert.False(t, meta.HasMetadata(\"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\t_, meta, _ := newMeta(0, cur)\n\t\t\ttt.fn(t, meta)\n\t\t})\n\t}\n}\n\nfunc TestOnBurnClearsMetadata(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\ttokenLedger, meta, metaLedger := newMeta(0, cur)\n\n\turequire.NoError(t, tokenLedger.Mint(alice, \"1\"))\n\turequire.NoError(t, metaLedger.SetTokenURI(\"1\", \"ipfs://uri-1\"))\n\turequire.NoError(t, metaLedger.SetTokenMetadata(\"1\", Data{Name: \"one\"}))\n\tuassert.True(t, meta.HasTokenURI(\"1\"))\n\tuassert.True(t, meta.HasMetadata(\"1\"))\n\n\turequire.NoError(t, tokenLedger.Burn(\"1\"))\n\tuassert.False(t, meta.HasTokenURI(\"1\"))\n\tuassert.False(t, meta.HasMetadata(\"1\"))\n\n\t_, err := meta.TokenURI(\"1\")\n\tuassert.ErrorIs(t, err, ErrNoTokenURI)\n\t_, err = meta.TokenMetadata(\"1\")\n\tuassert.ErrorIs(t, err, ErrNoMetadata)\n\n\turequire.NoError(t, tokenLedger.Mint(alice, \"1\"))\n\tuassert.False(t, meta.HasTokenURI(\"1\"))\n\tuassert.False(t, meta.HasMetadata(\"1\"))\n}\n\nfunc TestHooks(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\ttokenLedger, meta, metaLedger := newMeta(0, cur)\n\n\turequire.NoError(t, tokenLedger.Mint(alice, \"1\"))\n\turequire.NoError(t, metaLedger.SetTokenURI(\"1\", \"ipfs://uri-1\"))\n\turequire.NoError(t, metaLedger.SetTokenMetadata(\"1\", Data{Name: \"one\"}))\n\n\tmetaLedger.OnMint(alice, \"1\")\n\tmetaLedger.OnTransfer(alice, bob, \"1\")\n\tuassert.True(t, meta.HasTokenURI(\"1\"))\n\tuassert.True(t, meta.HasMetadata(\"1\"))\n\turi, err := meta.TokenURI(\"1\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"ipfs://uri-1\", uri)\n\n\tmetaLedger.OnBurn(\"1\")\n\tuassert.False(t, meta.HasTokenURI(\"1\"))\n\tuassert.False(t, meta.HasMetadata(\"1\"))\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/demo/tokens/grc721\"\n\t\"gno.land/p/nt/avl/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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"OPx/aNG7Tn4gGvXinL0hUwApRUKkW4xtl0I70uFfSascVuV91FQ6j6Z40+OOvugRG9QcynKJ2iGbG6H//w1wHQ=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"royalty","path":"gno.land/p/demo/tokens/grc721/royalty","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/demo/tokens/grc721/royalty\"\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/demo/tokens/grc721\"\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":"token_test.gno","body":"package royalty\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/demo/tokens/grc721\"\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\n// newToken builds via same-realm cross (NewToken requires rlm.IsCurrent()).\nfunc newToken(name, symbol string, id seqid.ID, rlm realm) (tok *grc721.Token, led *grc721.PrivateLedger) {\n\tfunc(cur realm) {\n\t\ttok, led = grc721.NewToken(name, symbol, id, cur)\n\t}(cross(rlm))\n\treturn\n}\n\nfunc newRoy(maxBps int64, rlm realm) (*grc721.PrivateLedger, *Royalty, *Ledger) {\n\t_, tokenLedger := newToken(\"Foo\", \"FOO\", 0, rlm)\n\troy, royLedger := NewRoyalty(tokenLedger, maxBps)\n\treturn tokenLedger, roy, royLedger\n}\n\nfunc TestNewRoyalty(cur realm, t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tnilLedger bool\n\t\tmaxBps    int64\n\t\twantPanic string // \"\" = success\n\t}{\n\t\t{\"nil token ledger panics\", true, 500, \"royalty: nil core ledger\"},\n\t\t{\"maxBps above FeeDenominator panics\", false, 10001, ErrMaxBpsRange.Error()},\n\t\t{\"negative maxBps panics\", false, -1, ErrMaxBpsRange.Error()},\n\t\t{\"maxBps at FeeDenominator boundary constructs\", false, 10000, \"\"},\n\t\t{\"maxBps zero boundary constructs\", false, 0, \"\"},\n\t\t{\"typical maxBps constructs\", false, 1000, \"\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif tt.nilLedger {\n\t\t\t\tuassert.PanicsWithMessage(t, cur, tt.wantPanic, func() {\n\t\t\t\t\tNewRoyalty(nil, tt.maxBps)\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t_, tokenLedger := newToken(\"Foo\", \"FOO\", 0, cur)\n\t\t\tif tt.wantPanic != \"\" {\n\t\t\t\tuassert.PanicsWithMessage(t, cur, tt.wantPanic, func() {\n\t\t\t\t\tNewRoyalty(tokenLedger, tt.maxBps)\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\troy, royLedger := NewRoyalty(tokenLedger, tt.maxBps)\n\t\t\tuassert.True(t, roy != nil)\n\t\t\tuassert.True(t, royLedger != nil)\n\t\t\tuassert.Equal(t, Kind, roy.ExtensionKind())\n\t\t\tuassert.Equal(t, \"royalty\", roy.ExtensionKind())\n\t\t\tuassert.Equal(t, tt.maxBps, roy.MaxBps())\n\t\t\tuassert.Equal(t, tokenLedger.ReadToken().ID(), roy.TokenID())\n\t\t})\n\t}\n}\n\nfunc TestRoyaltyInfo(cur realm, t *testing.T) {\n\tartist := testutils.TestAddress(\"artist\")\n\tspecial := testutils.TestAddress(\"special\")\n\n\ttests := []struct {\n\t\tname         string\n\t\tsetDefault   bool\n\t\tdefaultBps   int64\n\t\tsetToken     bool\n\t\ttokenBps     int64\n\t\tsalePrice    int64\n\t\twantReceiver address\n\t\twantAmount   int64\n\t}{\n\t\t{\n\t\t\tname:         \"no royalty configured returns zero receiver and amount\",\n\t\t\tsalePrice:    10000,\n\t\t\twantReceiver: zeroAddress,\n\t\t\twantAmount:   0,\n\t\t},\n\t\t{\n\t\t\tname:         \"default 5% yields 500 on salePrice 10000\",\n\t\t\tsetDefault:   true,\n\t\t\tdefaultBps:   500,\n\t\t\tsalePrice:    10000,\n\t\t\twantReceiver: artist,\n\t\t\twantAmount:   500,\n\t\t},\n\t\t{\n\t\t\tname:         \"per-token override takes precedence over default\",\n\t\t\tsetDefault:   true,\n\t\t\tdefaultBps:   500,\n\t\t\tsetToken:     true,\n\t\t\ttokenBps:     250,\n\t\t\tsalePrice:    10000,\n\t\t\twantReceiver: special,\n\t\t\twantAmount:   250,\n\t\t},\n\t\t{\n\t\t\tname:         \"fractional bps 250 truncates on small sale price\",\n\t\t\tsetToken:     true,\n\t\t\ttokenBps:     250,\n\t\t\tsalePrice:    100, // 100*250/10000 = 2\n\t\t\twantReceiver: special,\n\t\t\twantAmount:   2,\n\t\t},\n\t\t{\n\t\t\tname:         \"zero sale price yields zero amount\",\n\t\t\tsetDefault:   true,\n\t\t\tdefaultBps:   500,\n\t\t\tsalePrice:    0,\n\t\t\twantReceiver: artist,\n\t\t\twantAmount:   0,\n\t\t},\n\t\t{\n\t\t\tname:         \"default receiver applies when token has no override\",\n\t\t\tsetDefault:   true,\n\t\t\tdefaultBps:   1000,\n\t\t\tsalePrice:    5000,\n\t\t\twantReceiver: artist,\n\t\t\twantAmount:   500,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttokenLedger, roy, royLedger := newRoy(1000, cur)\n\t\t\turequire.NoError(t, tokenLedger.Mint(testutils.TestAddress(\"alice\"), \"1\"))\n\n\t\t\tif tt.setDefault {\n\t\t\t\turequire.NoError(t, royLedger.SetDefaultRoyalty(artist, tt.defaultBps))\n\t\t\t}\n\t\t\tif tt.setToken {\n\t\t\t\turequire.NoError(t, royLedger.SetTokenRoyalty(\"1\", special, tt.tokenBps))\n\t\t\t}\n\n\t\t\trecv, amt, err := roy.RoyaltyInfo(\"1\", tt.salePrice)\n\t\t\turequire.NoError(t, err)\n\t\t\tuassert.Equal(t, tt.wantReceiver, recv)\n\t\t\tuassert.Equal(t, tt.wantAmount, amt)\n\t\t})\n\t}\n}\n\nfunc TestDefaultRoyalty(cur realm, t *testing.T) {\n\tartist := testutils.TestAddress(\"artist\")\n\n\tt.Run(\"unset default reports not present\", func(t *testing.T) {\n\t\t_, roy, _ := newRoy(1000, cur)\n\t\tinfo, ok := roy.DefaultRoyalty()\n\t\tuassert.False(t, ok)\n\t\tuassert.Equal(t, zeroAddress, info.Receiver)\n\t\tuassert.Equal(t, int64(0), info.Bps)\n\t})\n\n\tt.Run(\"set default is reported and readable\", func(t *testing.T) {\n\t\t_, roy, royLedger := newRoy(1000, cur)\n\t\turequire.NoError(t, royLedger.SetDefaultRoyalty(artist, 500))\n\t\tinfo, ok := roy.DefaultRoyalty()\n\t\tuassert.True(t, ok)\n\t\tuassert.Equal(t, artist, info.Receiver)\n\t\tuassert.Equal(t, int64(500), info.Bps)\n\t})\n\n\tt.Run(\"delete default clears it\", func(t *testing.T) {\n\t\t_, roy, royLedger := newRoy(1000, cur)\n\t\turequire.NoError(t, royLedger.SetDefaultRoyalty(artist, 500))\n\t\troyLedger.DeleteDefaultRoyalty()\n\t\tinfo, ok := roy.DefaultRoyalty()\n\t\tuassert.False(t, ok)\n\t\tuassert.Equal(t, zeroAddress, info.Receiver)\n\n\t\trecv, amt, err := roy.RoyaltyInfo(\"1\", 10000)\n\t\turequire.NoError(t, err)\n\t\tuassert.Equal(t, zeroAddress, recv)\n\t\tuassert.Equal(t, int64(0), amt)\n\t})\n}\n\nfunc TestTokenRoyalty(cur realm, t *testing.T) {\n\tartist := testutils.TestAddress(\"artist\")\n\tspecial := testutils.TestAddress(\"special\")\n\n\tt.Run(\"unset per-token override reports not present\", func(t *testing.T) {\n\t\t_, roy, _ := newRoy(1000, cur)\n\t\tinfo, ok := roy.TokenRoyalty(\"1\")\n\t\tuassert.False(t, ok)\n\t\tuassert.Equal(t, zeroAddress, info.Receiver)\n\t})\n\n\tt.Run(\"set per-token override is reported and readable\", func(t *testing.T) {\n\t\ttokenLedger, roy, royLedger := newRoy(1000, cur)\n\t\turequire.NoError(t, tokenLedger.Mint(testutils.TestAddress(\"alice\"), \"1\"))\n\t\turequire.NoError(t, royLedger.SetTokenRoyalty(\"1\", special, 250))\n\t\tinfo, ok := roy.TokenRoyalty(\"1\")\n\t\tuassert.True(t, ok)\n\t\tuassert.Equal(t, special, info.Receiver)\n\t\tuassert.Equal(t, int64(250), info.Bps)\n\t})\n\n\tt.Run(\"delete per-token override falls back to default\", func(t *testing.T) {\n\t\ttokenLedger, roy, royLedger := newRoy(1000, cur)\n\t\turequire.NoError(t, tokenLedger.Mint(testutils.TestAddress(\"alice\"), \"1\"))\n\t\turequire.NoError(t, royLedger.SetDefaultRoyalty(artist, 500))\n\t\turequire.NoError(t, royLedger.SetTokenRoyalty(\"1\", special, 250))\n\n\t\troyLedger.DeleteTokenRoyalty(\"1\")\n\t\t_, ok := roy.TokenRoyalty(\"1\")\n\t\tuassert.False(t, ok)\n\n\t\trecv, amt, err := roy.RoyaltyInfo(\"1\", 10000)\n\t\turequire.NoError(t, err)\n\t\tuassert.Equal(t, artist, recv)\n\t\tuassert.Equal(t, int64(500), amt)\n\t})\n}\n\nfunc TestSetDefaultRoyaltyValidation(cur realm, t *testing.T) {\n\tartist := testutils.TestAddress(\"artist\")\n\n\ttests := []struct {\n\t\tname     string\n\t\treceiver address\n\t\tbps      int64\n\t\twantErr  error\n\t}{\n\t\t{\"bps above maxBps returns ErrInvalidBps\", artist, 1001, ErrInvalidBps},\n\t\t{\"negative bps returns ErrInvalidBps\", artist, -1, ErrInvalidBps},\n\t\t{\"invalid (zero) receiver returns ErrInvalidReceiver\", zeroAddress, 100, ErrInvalidReceiver},\n\t\t{\"bps at maxBps boundary succeeds\", artist, 1000, nil},\n\t\t{\"zero bps succeeds\", artist, 0, nil},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t_, roy, royLedger := newRoy(1000, cur)\n\t\t\terr := royLedger.SetDefaultRoyalty(tt.receiver, tt.bps)\n\t\t\tif tt.wantErr != nil {\n\t\t\t\tuassert.ErrorIs(t, err, tt.wantErr)\n\t\t\t\t_, ok := roy.DefaultRoyalty()\n\t\t\t\tuassert.False(t, ok)\n\t\t\t\treturn\n\t\t\t}\n\t\t\turequire.NoError(t, err)\n\t\t\tinfo, ok := roy.DefaultRoyalty()\n\t\t\tuassert.True(t, ok)\n\t\t\tuassert.Equal(t, tt.bps, info.Bps)\n\t\t})\n\t}\n}\n\nfunc TestSetTokenRoyaltyValidation(cur realm, t *testing.T) {\n\tartist := testutils.TestAddress(\"artist\")\n\n\ttests := []struct {\n\t\tname     string\n\t\tmint     bool\n\t\ttid      grc721.TokenID\n\t\treceiver address\n\t\tbps      int64\n\t\twantErr  error\n\t}{\n\t\t{\"unminted token returns ErrTokenNotMinted\", false, \"404\", artist, 100, ErrTokenNotMinted},\n\t\t{\"minted token with bps above maxBps returns ErrInvalidBps\", true, \"1\", artist, 1001, ErrInvalidBps},\n\t\t{\"minted token with negative bps returns ErrInvalidBps\", true, \"1\", artist, -1, ErrInvalidBps},\n\t\t{\"minted token with invalid receiver returns ErrInvalidReceiver\", true, \"1\", zeroAddress, 100, ErrInvalidReceiver},\n\t\t{\"minted token at maxBps boundary succeeds\", true, \"1\", artist, 1000, nil},\n\t\t{\"minted token with valid override succeeds\", true, \"1\", artist, 250, nil},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttokenLedger, roy, royLedger := newRoy(1000, cur)\n\t\t\tif tt.mint {\n\t\t\t\turequire.NoError(t, tokenLedger.Mint(testutils.TestAddress(\"alice\"), tt.tid))\n\t\t\t}\n\n\t\t\terr := royLedger.SetTokenRoyalty(tt.tid, tt.receiver, tt.bps)\n\t\t\tif tt.wantErr != nil {\n\t\t\t\tuassert.ErrorIs(t, err, tt.wantErr)\n\t\t\t\t_, ok := roy.TokenRoyalty(tt.tid)\n\t\t\t\tuassert.False(t, ok)\n\t\t\t\treturn\n\t\t\t}\n\t\t\turequire.NoError(t, err)\n\t\t\tinfo, ok := roy.TokenRoyalty(tt.tid)\n\t\t\tuassert.True(t, ok)\n\t\t\tuassert.Equal(t, tt.bps, info.Bps)\n\t\t})\n\t}\n}\n\nfunc TestOnBurnClearsTokenRoyaltyKeepsDefault(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tartist := testutils.TestAddress(\"artist\")\n\tspecial := testutils.TestAddress(\"special\")\n\ttokenLedger, roy, royLedger := newRoy(1000, cur)\n\n\turequire.NoError(t, tokenLedger.Mint(alice, \"1\"))\n\turequire.NoError(t, royLedger.SetDefaultRoyalty(artist, 500))\n\turequire.NoError(t, royLedger.SetTokenRoyalty(\"1\", special, 250))\n\n\t_, ok := roy.TokenRoyalty(\"1\")\n\tuassert.True(t, ok)\n\n\turequire.NoError(t, tokenLedger.Burn(\"1\"))\n\t_, ok = roy.TokenRoyalty(\"1\")\n\tuassert.False(t, ok)\n\n\tinfo, ok := roy.DefaultRoyalty()\n\tuassert.True(t, ok)\n\tuassert.Equal(t, artist, info.Receiver)\n\n\turequire.NoError(t, tokenLedger.Mint(alice, \"1\"))\n\t_, ok = roy.TokenRoyalty(\"1\")\n\tuassert.False(t, ok)\n\trecv, amt, err := roy.RoyaltyInfo(\"1\", 10000)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, artist, recv)\n\tuassert.Equal(t, int64(500), amt)\n}\n\nfunc TestHooks(cur realm, t *testing.T) {\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\tartist := testutils.TestAddress(\"artist\")\n\tspecial := testutils.TestAddress(\"special\")\n\ttokenLedger, roy, royLedger := newRoy(1000, cur)\n\n\turequire.NoError(t, tokenLedger.Mint(alice, \"1\"))\n\turequire.NoError(t, royLedger.SetDefaultRoyalty(artist, 500))\n\turequire.NoError(t, royLedger.SetTokenRoyalty(\"1\", special, 250))\n\n\troyLedger.OnMint(alice, \"1\")\n\troyLedger.OnTransfer(alice, bob, \"1\")\n\tinfo, ok := roy.TokenRoyalty(\"1\")\n\tuassert.True(t, ok)\n\tuassert.Equal(t, special, info.Receiver)\n\t_, ok = roy.DefaultRoyalty()\n\tuassert.True(t, ok)\n\n\troyLedger.OnBurn(\"1\")\n\t_, ok = roy.TokenRoyalty(\"1\")\n\tuassert.False(t, ok)\n\t_, ok = roy.DefaultRoyalty()\n\tuassert.True(t, ok)\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/demo/tokens/grc721\"\n\t\"gno.land/p/nt/avl/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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"qO/1GVejt0r6+8rDJcYpOrNHu3iJwnoO55+Y8MqaLg4MuoB93RO9uKvglMmLcrrNbllmt0TSodqoDMQHdGPVqw=="}],"memo":""}},{"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/v0/list` - ordered list built on top of `BPTree`.\n- `gno.land/p/nt/bptree/v0/pager` - pagination helper for trees and lists.\n- `gno.land/p/nt/bptree/v0/rotree` - 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":"example_test.gno","body":"package bptree\n\n// ExampleNew shows NewBPTree32() and adding a value\nfunc ExampleNew() {\n\tvar tree *BPTree\n\ttree = NewBPTree32()\n\ttree.Set(\"key0\", \"value0\")\n\n\tvar updated bool\n\tupdated = tree.Set(\"key1\", \"value1\")\n\tprintln(updated, tree.Size())\n\n\t// Output:\n\t// false 2\n}\n\n// ExampleUpdate shows NewBPTree32() and updating a value\nfunc ExampleUpdate() {\n\tvar tree *BPTree\n\ttree = NewBPTree32()\n\ttree.Set(\"key0\", \"value0\")\n\n\tvar updated bool\n\tupdated = tree.Set(\"key0\", \"new_value0\")\n\tprintln(updated, tree.Size())\n\n\t// Output:\n\t// true 1\n}\n\n// ExampleZeroValue shows updating the zero value of a BPTree without NewBPTree32()\nfunc ExampleZeroValue() {\n\tvar tree BPTree\n\ttree.Set(\"key0\", \"value0\")\n\ttree.Set(\"key1\", \"value1\")\n\n\tvar updated bool\n\tupdated = tree.Set(\"key2\", \"value2\")\n\tprintln(updated, tree.Size())\n\n\t// Output:\n\t// false 3\n}\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"},{"name":"tree_test.gno","body":"package bptree\n\nimport (\n\t\"math/rand\"\n\t\"sort\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n)\n\n//----------------------------------------\n// Basic operations\n\nfunc TestNewTree(t *testing.T) {\n\ttree := NewBPTree32()\n\tif tree.Size() != 0 {\n\t\tt.Error(\"Expected empty tree size to be 0\")\n\t}\n}\n\nfunc TestZeroValue(t *testing.T) {\n\tvar tree BPTree\n\tif tree.Size() != 0 {\n\t\tt.Error(\"Expected zero-value tree size to be 0\")\n\t}\n\tif tree.Has(\"x\") {\n\t\tt.Error(\"Expected Has to return false on zero-value tree\")\n\t}\n\tif v := tree.Get(\"x\"); v != nil {\n\t\tt.Errorf(\"Expected Get to return nil on zero-value tree, got %v\", v)\n\t}\n\tif _, ok := tree.Remove(\"x\"); ok {\n\t\tt.Error(\"Expected Remove to return false on zero-value tree\")\n\t}\n\n\t// Set should work on zero-value tree.\n\tif updated := tree.Set(\"a\", 1); updated {\n\t\tt.Error(\"Expected Set to return false for new key\")\n\t}\n\tif tree.Size() != 1 {\n\t\tt.Errorf(\"Expected size 1, got %d\", tree.Size())\n\t}\n\tif v := tree.Get(\"a\"); v != 1 {\n\t\tt.Errorf(\"Expected Get(a) = 1, got %v\", v)\n\t}\n}\n\nfunc TestSetAndGet(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"key1\", \"value1\")\n\ttree.Set(\"key2\", \"value2\")\n\n\tif tree.Size() != 2 {\n\t\tt.Errorf(\"Expected size 2, got %d\", tree.Size())\n\t}\n\n\tif v := tree.Get(\"key1\"); v != \"value1\" {\n\t\tt.Errorf(\"Expected value1, got %v\", v)\n\t}\n\n\tif v := tree.Get(\"missing\"); v != nil {\n\t\tt.Errorf(\"Expected Get to return nil for missing key, got %v\", v)\n\t}\n}\n\nfunc TestSetUpdate(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\tif updated := tree.Set(\"k\", \"v1\"); updated {\n\t\tt.Error(\"Expected false for new key\")\n\t}\n\tif updated := tree.Set(\"k\", \"v2\"); !updated {\n\t\tt.Error(\"Expected true for existing key\")\n\t}\n\tif tree.Size() != 1 {\n\t\tt.Errorf(\"Expected size 1 after update, got %d\", tree.Size())\n\t}\n\tif v := tree.Get(\"k\"); v != \"v2\" {\n\t\tt.Errorf(\"Expected v2, got %v\", v)\n\t}\n}\n\nfunc TestHas(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"a\", 1)\n\tif !tree.Has(\"a\") {\n\t\tt.Error(\"Expected Has(a) = true\")\n\t}\n\tif tree.Has(\"b\") {\n\t\tt.Error(\"Expected Has(b) = false\")\n\t}\n}\n\nfunc TestRemove(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"a\", 1)\n\ttree.Set(\"b\", 2)\n\n\tv, ok := tree.Remove(\"a\")\n\tif !ok || v != 1 {\n\t\tt.Errorf(\"Expected (1, true), got (%v, %v)\", v, ok)\n\t}\n\tif tree.Size() != 1 {\n\t\tt.Errorf(\"Expected size 1, got %d\", tree.Size())\n\t}\n\tif tree.Has(\"a\") {\n\t\tt.Error(\"Expected Has(a) = false after remove\")\n\t}\n\n\tv, ok = tree.Remove(\"missing\")\n\tif ok || v != nil {\n\t\tt.Errorf(\"Expected (nil, false), got (%v, %v)\", v, ok)\n\t}\n}\n\nfunc TestRemoveLastKey(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"a\", 1)\n\ttree.Remove(\"a\")\n\tif tree.Size() != 0 {\n\t\tt.Errorf(\"Expected size 0, got %d\", tree.Size())\n\t}\n\n\t// Insert after removing everything.\n\ttree.Set(\"b\", 2)\n\tif tree.Size() != 1 {\n\t\tt.Errorf(\"Expected size 1, got %d\", tree.Size())\n\t}\n\tif v := tree.Get(\"b\"); v != 2 {\n\t\tt.Errorf(\"Expected 2, got %v\", v)\n\t}\n}\n\nfunc TestNilValue(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"k\", nil)\n\t// Has distinguishes a nil-valued entry from a missing key (Get returns\n\t// nil for both cases, by design).\n\tif !tree.Has(\"k\") {\n\t\tt.Error(\"Expected Has(k) = true for nil-valued entry\")\n\t}\n\tif v := tree.Get(\"k\"); v != nil {\n\t\tt.Errorf(\"Expected nil value, got %v\", v)\n\t}\n\tv, ok := tree.Remove(\"k\")\n\tif !ok {\n\t\tt.Error(\"Expected remove to succeed\")\n\t}\n\tif v != nil {\n\t\tt.Errorf(\"Expected nil removed value, got %v\", v)\n\t}\n}\n\nfunc TestEmptyStringKey(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"\", \"empty\")\n\ttree.Set(\"a\", \"alpha\")\n\ttree.Set(\"b\", \"beta\")\n\n\tif !tree.Has(\"\") {\n\t\tt.Error(\"Expected Has('') = true for empty string key\")\n\t}\n\tif v := tree.Get(\"\"); v != \"empty\" {\n\t\tt.Errorf(\"Expected empty, got %v\", v)\n\t}\n\tif tree.Size() != 3 {\n\t\tt.Errorf(\"Expected size 3, got %d\", tree.Size())\n\t}\n\n\t// Remove \"\" key.\n\tv, ok := tree.Remove(\"\")\n\tif !ok || v != \"empty\" {\n\t\tt.Errorf(\"Remove('') = (%v, %v), want (empty, true)\", v, ok)\n\t}\n\tif tree.Size() != 2 {\n\t\tt.Errorf(\"Expected size 2, got %d\", tree.Size())\n\t}\n\tif tree.Has(\"\") {\n\t\tt.Error(\"Expected Has('') = false after remove\")\n\t}\n}\n\nfunc TestGetMissingReturnsNil(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"a\", 1)\n\tif v := tree.Get(\"missing\"); v != nil {\n\t\tt.Errorf(\"Expected nil value for missing key, got %v\", v)\n\t}\n}\n\nfunc TestRemoveMissingReturnsNilFalse(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"a\", 1)\n\tv, ok := tree.Remove(\"missing\")\n\tif v != nil {\n\t\tt.Errorf(\"Expected nil value for missing remove, got %v\", v)\n\t}\n\tif ok {\n\t\tt.Error(\"Expected false for missing remove\")\n\t}\n\n\t// Also on empty tree.\n\tvar empty BPTree\n\tv, ok = empty.Remove(\"x\")\n\tif v != nil || ok {\n\t\tt.Errorf(\"Remove on empty tree: got (%v, %v), want (nil, false)\", v, ok)\n\t}\n}\n\nfunc TestFanoutNeverResets(t *testing.T) {\n\tvar tree BPTree\n\ttree.Set(\"a\", 1)\n\ttree.Remove(\"a\")\n\t// Tree is empty again, but fanout should still be 32.\n\ttree.Set(\"b\", 2)\n\tif tree.Size() != 1 {\n\t\tt.Errorf(\"Expected size 1, got %d\", tree.Size())\n\t}\n\tif tree.fanout != 32 {\n\t\tt.Errorf(\"Expected fanout 32 after re-insert, got %d\", tree.fanout)\n\t}\n}\n\nfunc TestSingleEntry(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"x\", 42)\n\n\t// Root should be a leaf for single entry.\n\tif tree.root == nil {\n\t\tt.Fatal(\"root is nil\")\n\t}\n\tif !tree.root.isLeaf() {\n\t\tt.Error(\"root should be a leaf for single entry\")\n\t}\n\tif tree.Size() != 1 {\n\t\tt.Errorf(\"Expected size 1, got %d\", tree.Size())\n\t}\n\tk, v := tree.GetByIndex(0)\n\tif k != \"x\" || v != 42 {\n\t\tt.Errorf(\"GetByIndex(0) = (%v, %v), want (x, 42)\", k, v)\n\t}\n}\n\n//----------------------------------------\n// GetByIndex\n\nfunc TestGetByIndex(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"c\", 3)\n\ttree.Set(\"a\", 1)\n\ttree.Set(\"b\", 2)\n\n\tk, v := tree.GetByIndex(0)\n\tif k != \"a\" || v != 1 {\n\t\tt.Errorf(\"GetByIndex(0) = (%v, %v), want (a, 1)\", k, v)\n\t}\n\tk, v = tree.GetByIndex(1)\n\tif k != \"b\" || v != 2 {\n\t\tt.Errorf(\"GetByIndex(1) = (%v, %v), want (b, 2)\", k, v)\n\t}\n\tk, v = tree.GetByIndex(2)\n\tif k != \"c\" || v != 3 {\n\t\tt.Errorf(\"GetByIndex(2) = (%v, %v), want (c, 3)\", k, v)\n\t}\n}\n\nfunc TestGetByIndexPanics(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"a\", 1)\n\n\tassertPanics(t, \"empty tree\", func() {\n\t\tvar empty BPTree\n\t\tempty.GetByIndex(0)\n\t})\n\tassertPanics(t, \"negative index\", func() {\n\t\ttree.GetByIndex(-1)\n\t})\n\tassertPanics(t, \"index == size\", func() {\n\t\ttree.GetByIndex(1)\n\t})\n}\n\n//----------------------------------------\n// Iterate\n\nfunc TestIterate(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"a\", 1)\n\ttree.Set(\"b\", 2)\n\ttree.Set(\"c\", 3)\n\ttree.Set(\"d\", 4)\n\ttree.Set(\"e\", 5)\n\n\t// Full iteration.\n\tgot := collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"\", \"\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"a\", \"b\", \"c\", \"d\", \"e\"})\n\n\t// Bounded iteration [b, d) → b, c.\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"b\", \"d\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"b\", \"c\"})\n\n\t// start == end → empty.\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"b\", \"b\", cb)\n\t})\n\tassertSliceEqual(t, got, nil)\n\n\t// start \u003e end → empty.\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"z\", \"a\", cb)\n\t})\n\tassertSliceEqual(t, got, nil)\n\n\t// No lower bound.\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"\", \"c\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"a\", \"b\"})\n\n\t// Empty tree.\n\tvar empty BPTree\n\tstopped := empty.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\tt.Error(\"should not be called\")\n\t\treturn false\n\t})\n\tif stopped {\n\t\tt.Error(\"Expected false from Iterate on empty tree\")\n\t}\n}\n\nfunc TestIterateEarlyStop(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"a\", 1)\n\ttree.Set(\"b\", 2)\n\ttree.Set(\"c\", 3)\n\n\tcount := 0\n\tstopped := tree.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\tcount++\n\t\treturn true\n\t})\n\tif !stopped {\n\t\tt.Error(\"Expected true from early-stopped Iterate\")\n\t}\n\tif count != 1 {\n\t\tt.Errorf(\"Expected 1 callback, got %d\", count)\n\t}\n}\n\nfunc TestIterateAllEdgeCases(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"a\", 1)\n\ttree.Set(\"b\", 2)\n\ttree.Set(\"c\", 3)\n\ttree.Set(\"d\", 4)\n\ttree.Set(\"e\", 5)\n\n\t// Iterate(\"a\", \"a\") → empty [a,a).\n\tgot := collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"a\", \"a\", cb)\n\t})\n\tassertSliceEqual(t, got, nil)\n\n\t// Iterate(\"z\", \"a\") → empty (start \u003e end).\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"z\", \"a\", cb)\n\t})\n\tassertSliceEqual(t, got, nil)\n\n\t// Iterate(\"\", \"a\") → nothing \u003c \"a\".\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"\", \"a\", cb)\n\t})\n\tassertSliceEqual(t, got, nil)\n\n\t// Iterate(\"\", \"b\") → just \"a\".\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"\", \"b\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"a\"})\n\n\t// ReverseIterate(\"a\", \"a\") → visits \"a\" (both inclusive).\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.ReverseIterate(\"a\", \"a\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"a\"})\n\n\t// ReverseIterate(\"z\", \"a\") → empty (bounds don't swap).\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.ReverseIterate(\"z\", \"a\", cb)\n\t})\n\tassertSliceEqual(t, got, nil)\n\n\t// ReverseIterate(\"c\", \"\") → keys \u003e= \"c\" descending.\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.ReverseIterate(\"c\", \"\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"e\", \"d\", \"c\"})\n\n\t// Iterate(\"\", \"a\") on tree with key \"\" stored.\n\ttree2 := NewBPTreeN(4)\n\ttree2.Set(\"\", \"empty\")\n\ttree2.Set(\"a\", \"alpha\")\n\ttree2.Set(\"b\", \"beta\")\n\tgot = collectKeys(tree2, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"\", \"a\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"\"})\n\n\t// Iterate(\"\", \"\") visits all including \"\" key.\n\tgot = collectKeys(tree2, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"\", \"\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"\", \"a\", \"b\"})\n}\n\nfunc TestAllIterationEmptyTree(t *testing.T) {\n\tvar tree BPTree\n\tnoop := func(k string, v any) bool {\n\t\tt.Error(\"should not be called\")\n\t\treturn false\n\t}\n\tif tree.Iterate(\"\", \"\", noop) {\n\t\tt.Error(\"Iterate on empty tree should return false\")\n\t}\n\tif tree.ReverseIterate(\"\", \"\", noop) {\n\t\tt.Error(\"ReverseIterate on empty tree should return false\")\n\t}\n\tif tree.IterateByOffset(0, 1, noop) {\n\t\tt.Error(\"IterateByOffset on empty tree should return false\")\n\t}\n\tif tree.ReverseIterateByOffset(0, 1, noop) {\n\t\tt.Error(\"ReverseIterateByOffset on empty tree should return false\")\n\t}\n}\n\nfunc TestReverseIterate(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"a\", 1)\n\ttree.Set(\"b\", 2)\n\ttree.Set(\"c\", 3)\n\ttree.Set(\"d\", 4)\n\ttree.Set(\"e\", 5)\n\n\t// Full reverse.\n\tgot := collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.ReverseIterate(\"\", \"\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"e\", \"d\", \"c\", \"b\", \"a\"})\n\n\t// Bounded [b, d] inclusive → d, c, b.\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.ReverseIterate(\"b\", \"d\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"d\", \"c\", \"b\"})\n\n\t// start == end → visits that one key.\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.ReverseIterate(\"c\", \"c\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"c\"})\n\n\t// start \u003e end → empty.\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.ReverseIterate(\"z\", \"a\", cb)\n\t})\n\tassertSliceEqual(t, got, nil)\n\n\t// No upper bound.\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.ReverseIterate(\"c\", \"\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"e\", \"d\", \"c\"})\n\n\t// end \u003e max key → e, d, c, b, a.\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.ReverseIterate(\"a\", \"z\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"e\", \"d\", \"c\", \"b\", \"a\"})\n}\n\nfunc TestIterateByOffset(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"a\", 1)\n\ttree.Set(\"b\", 2)\n\ttree.Set(\"c\", 3)\n\ttree.Set(\"d\", 4)\n\ttree.Set(\"e\", 5)\n\n\tgot := collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.IterateByOffset(1, 3, cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"b\", \"c\", \"d\"})\n\n\t// offset=0, count=0 → nothing.\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.IterateByOffset(0, 0, cb)\n\t})\n\tassertSliceEqual(t, got, nil)\n\n\t// offset=size → nothing.\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.IterateByOffset(5, 1, cb)\n\t})\n\tassertSliceEqual(t, got, nil)\n\n\t// count exceeds remaining.\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.IterateByOffset(3, 100, cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"d\", \"e\"})\n}\n\nfunc TestReverseIterateByOffset(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"a\", 1)\n\ttree.Set(\"b\", 2)\n\ttree.Set(\"c\", 3)\n\ttree.Set(\"d\", 4)\n\ttree.Set(\"e\", 5)\n\n\t// Full reverse.\n\tgot := collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.ReverseIterateByOffset(0, 5, cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"e\", \"d\", \"c\", \"b\", \"a\"})\n\n\t// offset=1, count=2 → [d, c].\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.ReverseIterateByOffset(1, 2, cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"d\", \"c\"})\n\n\t// offset=4, count=1 → [a].\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.ReverseIterateByOffset(4, 1, cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"a\"})\n\n\t// offset=4, count=10 → [a].\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.ReverseIterateByOffset(4, 10, cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"a\"})\n\n\t// offset \u003e= size → nothing.\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.ReverseIterateByOffset(5, 1, cb)\n\t})\n\tassertSliceEqual(t, got, nil)\n\n\t// count=0 → nothing.\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.ReverseIterateByOffset(0, 0, cb)\n\t})\n\tassertSliceEqual(t, got, nil)\n\n\t// negative offset\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.ReverseIterateByOffset(-1, 3, cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"e\", \"d\", \"c\"})\n}\n\nfunc TestReverseIterateEarlyStop(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"a\", 1)\n\ttree.Set(\"b\", 2)\n\ttree.Set(\"c\", 3)\n\tcount := 0\n\tstopped := tree.ReverseIterate(\"\", \"\", func(k string, v any) bool {\n\t\tcount++\n\t\treturn true\n\t})\n\tif !stopped {\n\t\tt.Error(\"Expected true from early-stopped ReverseIterate\")\n\t}\n\tif count != 1 {\n\t\tt.Errorf(\"Expected 1 callback, got %d\", count)\n\t}\n}\n\n//----------------------------------------\n// Splits and merges (use small fanout to trigger them)\n\nfunc TestSplitAndMerge(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\n\t// Insert enough keys to cause multiple splits.\n\tkeys := []string{\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\"}\n\tfor _, k := range keys {\n\t\ttree.Set(k, k)\n\t}\n\tif tree.Size() != len(keys) {\n\t\tt.Errorf(\"Expected size %d, got %d\", len(keys), tree.Size())\n\t}\n\n\t// Verify all keys present and in order.\n\tgot := collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"\", \"\", cb)\n\t})\n\tassertSliceEqual(t, got, keys)\n\n\t// Verify GetByIndex works for all positions.\n\tfor i, k := range keys {\n\t\tgk, gv := tree.GetByIndex(i)\n\t\tif gk != k || gv != k {\n\t\t\tt.Errorf(\"GetByIndex(%d) = (%v, %v), want (%v, %v)\", i, gk, gv, k, k)\n\t\t}\n\t}\n\n\t// Remove keys one by one and verify.\n\tfor _, k := range keys {\n\t\tv, ok := tree.Remove(k)\n\t\tif !ok || v != k {\n\t\t\tt.Errorf(\"Remove(%v) = (%v, %v), want (%v, true)\", k, v, ok, k)\n\t\t}\n\t}\n\tif tree.Size() != 0 {\n\t\tt.Errorf(\"Expected size 0 after removing all, got %d\", tree.Size())\n\t}\n}\n\nfunc TestRemoveFromMiddle(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\tfor _, k := range []string{\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\"} {\n\t\ttree.Set(k, k)\n\t}\n\n\t// Remove from the middle to trigger redistributions and merges.\n\ttree.Remove(\"d\")\n\ttree.Remove(\"e\")\n\ttree.Remove(\"b\")\n\ttree.Remove(\"g\")\n\n\tgot := collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"\", \"\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"a\", \"c\", \"f\", \"h\"})\n\tif tree.Size() != 4 {\n\t\tt.Errorf(\"Expected size 4, got %d\", tree.Size())\n\t}\n}\n\nfunc TestSequentialInsertRemove(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\n\t// Sequential insert.\n\tn := 100\n\tfor i := 0; i \u003c n; i++ {\n\t\tk := intToKey(i)\n\t\ttree.Set(k, i)\n\t}\n\tif tree.Size() != n {\n\t\tt.Errorf(\"Expected size %d, got %d\", n, tree.Size())\n\t}\n\n\t// Verify sorted order.\n\tprev := \"\"\n\ttree.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\tif k \u003c= prev \u0026\u0026 prev != \"\" {\n\t\t\tt.Errorf(\"Keys not in order: %q after %q\", k, prev)\n\t\t}\n\t\tprev = k\n\t\treturn false\n\t})\n\n\t// Remove all in reverse order.\n\tfor i := n - 1; i \u003e= 0; i-- {\n\t\tk := intToKey(i)\n\t\t_, ok := tree.Remove(k)\n\t\tif !ok {\n\t\t\tt.Errorf(\"Remove(%v) failed\", k)\n\t\t}\n\t}\n\tif tree.Size() != 0 {\n\t\tt.Errorf(\"Expected size 0, got %d\", tree.Size())\n\t}\n}\n\nfunc TestRandomInsertRemove(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\n\t// Insert in \"random\" order (shuffled via simple hash).\n\tkeys := make([]string, 50)\n\tfor i := range keys {\n\t\tkeys[i] = intToKey((i*37 + 13) % 50)\n\t}\n\tfor _, k := range keys {\n\t\ttree.Set(k, k)\n\t}\n\tif tree.Size() != 50 {\n\t\tt.Errorf(\"Expected size 50, got %d\", tree.Size())\n\t}\n\n\t// Remove half.\n\tfor i := 0; i \u003c 25; i++ {\n\t\ttree.Remove(keys[i])\n\t}\n\tif tree.Size() != 25 {\n\t\tt.Errorf(\"Expected size 25, got %d\", tree.Size())\n\t}\n\n\t// Verify remaining keys are in sorted order.\n\tprev := \"\"\n\ttree.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\tif k \u003c= prev \u0026\u0026 prev != \"\" {\n\t\t\tt.Errorf(\"Keys not in order: %q after %q\", k, prev)\n\t\t}\n\t\tprev = k\n\t\treturn false\n\t})\n}\n\nfunc TestDifferentFanouts(t *testing.T) {\n\tfor _, fanout := range []int{4, 5, 8, 16, 32} {\n\t\ttree := NewBPTreeN(fanout)\n\t\tn := 100\n\t\tfor i := 0; i \u003c n; i++ {\n\t\t\ttree.Set(intToKey(i), i)\n\t\t}\n\t\tif tree.Size() != n {\n\t\t\tt.Errorf(\"fanout=%d: expected size %d, got %d\", fanout, n, tree.Size())\n\t\t}\n\n\t\t// Verify order.\n\t\tgot := collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\t\treturn tr.Iterate(\"\", \"\", cb)\n\t\t})\n\t\tfor i := 1; i \u003c len(got); i++ {\n\t\t\tif got[i] \u003c= got[i-1] {\n\t\t\t\tt.Errorf(\"fanout=%d: keys not in order at %d\", fanout, i)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Remove all.\n\t\tfor i := 0; i \u003c n; i++ {\n\t\t\ttree.Remove(intToKey(i))\n\t\t}\n\t\tif tree.Size() != 0 {\n\t\t\tt.Errorf(\"fanout=%d: expected size 0 after remove all, got %d\", fanout, tree.Size())\n\t\t}\n\t}\n}\n\nfunc TestNegativeCount(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\ttree.Set(\"a\", 1)\n\n\tgot := collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.IterateByOffset(0, -1, cb)\n\t})\n\tassertSliceEqual(t, got, nil)\n\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.ReverseIterateByOffset(0, -1, cb)\n\t})\n\tassertSliceEqual(t, got, nil)\n}\n\nfunc TestRootCollapse(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\t// Insert enough to create inner nodes.\n\tfor _, k := range []string{\"a\", \"b\", \"c\", \"d\", \"e\"} {\n\t\ttree.Set(k, k)\n\t}\n\tif tree.root.isLeaf() {\n\t\tt.Error(\"Expected inner root after 5 inserts with fanout 4\")\n\t}\n\n\t// Remove enough to trigger merges and root collapse.\n\ttree.Remove(\"a\")\n\ttree.Remove(\"b\")\n\ttree.Remove(\"c\")\n\t// With only \"d\" and \"e\" left, root should collapse to a leaf.\n\tif !tree.root.isLeaf() {\n\t\tt.Error(\"Expected leaf root after removing down to 2 entries\")\n\t}\n\tif tree.Size() != 2 {\n\t\tt.Errorf(\"Expected size 2, got %d\", tree.Size())\n\t}\n\tgot := collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"\", \"\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"d\", \"e\"})\n}\n\nfunc TestSeparatorKeyAfterLeftmostDeletion(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\t// Insert keys to create a split.\n\tfor _, k := range []string{\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\"} {\n\t\ttree.Set(k, k)\n\t}\n\t// Remove leftmost key \"a\" — should trigger separator update.\n\ttree.Remove(\"a\")\n\n\t// Verify all remaining keys are accessible.\n\tfor _, k := range []string{\"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\"} {\n\t\tif !tree.Has(k) {\n\t\t\tt.Errorf(\"Expected Has(%s) = true after removing 'a'\", k)\n\t\t}\n\t}\n\tif tree.Has(\"a\") {\n\t\tt.Error(\"Expected Has(a) = false\")\n\t}\n\n\t// Verify sorted order.\n\tgot := collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"\", \"\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\"})\n\n\t// Verify GetByIndex still works.\n\tk, _ := tree.GetByIndex(0)\n\tif k != \"b\" {\n\t\tt.Errorf(\"GetByIndex(0) = %v, want b\", k)\n\t}\n}\n\nfunc TestNinetyTenSplit(t *testing.T) {\n\t// Sequential inserts should trigger 90/10 splits, keeping left leaves ~97% full.\n\ttree := NewBPTreeN(4)\n\tfor _, k := range []string{\"a\", \"b\", \"c\", \"d\", \"e\"} {\n\t\ttree.Set(k, k)\n\t}\n\t// After inserting a,b,c,d (leaf full), then e (append → 90/10 split):\n\t// Left should have fanout-1=3 entries [a,b,c], right should have 2 entries [d,e].\n\tif !tree.root.isLeaf() == true {\n\t\t// Root should be an inner node after split.\n\t}\n\tinner := tree.root.(*innerNode)\n\tleft := inner.children[0].(*leafNode)\n\tright := inner.children[1].(*leafNode)\n\tif len(left.keys) != 3 {\n\t\tt.Errorf(\"90/10 split: left leaf has %d entries, want 3\", len(left.keys))\n\t}\n\tif len(right.keys) != 2 {\n\t\tt.Errorf(\"90/10 split: right leaf has %d entries, want 2\", len(right.keys))\n\t}\n\n\t// Verify all keys accessible.\n\tgot := collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"\", \"\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"a\", \"b\", \"c\", \"d\", \"e\"})\n}\n\nfunc TestNinetyTenSplitLargeFanout(t *testing.T) {\n\t// With fanout=32, sequential inserts should produce high fill factor.\n\ttree := NewBPTree32()\n\tn := 200\n\tfor i := 0; i \u003c n; i++ {\n\t\ttree.Set(intToKey(i), i)\n\t}\n\tif tree.Size() != n {\n\t\tt.Errorf(\"Expected size %d, got %d\", n, tree.Size())\n\t}\n\n\t// Verify all keys in order.\n\tprev := \"\"\n\tcount := 0\n\ttree.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\tif k \u003c= prev \u0026\u0026 prev != \"\" {\n\t\t\tt.Errorf(\"Keys not in order: %q after %q\", k, prev)\n\t\t}\n\t\tprev = k\n\t\tcount++\n\t\treturn false\n\t})\n\tif count != n {\n\t\tt.Errorf(\"Iterate visited %d entries, want %d\", count, n)\n\t}\n\n\t// Remove all and verify.\n\tfor i := 0; i \u003c n; i++ {\n\t\t_, ok := tree.Remove(intToKey(i))\n\t\tif !ok {\n\t\t\tt.Errorf(\"Remove(%s) failed\", intToKey(i))\n\t\t}\n\t}\n\tif tree.Size() != 0 {\n\t\tt.Errorf(\"Expected size 0, got %d\", tree.Size())\n\t}\n}\n\nfunc TestMixedSplitTypes(t *testing.T) {\n\t// Sequential inserts trigger 90/10, then a middle insert triggers 50/50.\n\ttree := NewBPTreeN(4)\n\t// Sequential: triggers 90/10 split.\n\tfor _, k := range []string{\"b\", \"c\", \"d\", \"e\"} {\n\t\ttree.Set(k, k)\n\t}\n\t// Insert \"a\" at the beginning of the left leaf — not an append, so if\n\t// that leaf overflows it will use 50/50.\n\ttree.Set(\"a\", \"a\")\n\n\t// Verify all keys present and sorted.\n\tgot := collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"\", \"\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"a\", \"b\", \"c\", \"d\", \"e\"})\n}\n\nfunc TestSizeCacheConsistency(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\tkeys := []string{\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\"}\n\n\t// Check after each insert.\n\tfor _, k := range keys {\n\t\ttree.Set(k, k)\n\t\tverifySizeCache(t, tree.root)\n\t}\n\n\t// Check after each remove.\n\tfor _, k := range keys {\n\t\ttree.Remove(k)\n\t\tverifySizeCache(t, tree.root)\n\t}\n\n\t// Also check with large fanout.\n\ttree2 := NewBPTree32()\n\tfor i := 0; i \u003c 100; i++ {\n\t\ttree2.Set(intToKey(i), i)\n\t}\n\tverifySizeCache(t, tree2.root)\n\tfor i := 0; i \u003c 100; i++ {\n\t\ttree2.Remove(intToKey(i))\n\t\tverifySizeCache(t, tree2.root)\n\t}\n}\n\nfunc verifySizeCache(t *testing.T, n node) {\n\tt.Helper()\n\tif n == nil || n.isLeaf() {\n\t\treturn\n\t}\n\tinner := n.(*innerNode)\n\t// Verify each sizes[i] matches the actual child subtree size.\n\tfor i, child := range inner.children {\n\t\tactual := child.nodeSize()\n\t\tif inner.sizes[i] != actual {\n\t\t\tt.Errorf(\"innerNode.sizes[%d]=%d but child.nodeSize()=%d\", i, inner.sizes[i], actual)\n\t\t}\n\t\tverifySizeCache(t, child)\n\t}\n}\n\nfunc TestValueIndirection(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\n\t// Nil value through *any.\n\ttree.Set(\"nil\", nil)\n\tif !tree.Has(\"nil\") {\n\t\tt.Error(\"Expected key 'nil' to exist\")\n\t}\n\tif v := tree.Get(\"nil\"); v != nil {\n\t\tt.Errorf(\"Expected nil value, got %v\", v)\n\t}\n\n\t// Various types.\n\ttree.Set(\"int\", 42)\n\ttree.Set(\"str\", \"hello\")\n\ttree.Set(\"slice\", []byte{1, 2, 3})\n\n\tif v := tree.Get(\"int\"); v != 42 {\n\t\tt.Errorf(\"Expected 42, got %v\", v)\n\t}\n\tif v := tree.Get(\"str\"); v != \"hello\" {\n\t\tt.Errorf(\"Expected hello, got %v\", v)\n\t}\n\tif v := tree.Get(\"slice\"); len(v.([]byte)) != 3 {\n\t\tt.Errorf(\"Expected 3-byte slice, got %v\", v)\n\t}\n\n\t// Update value in place (should reuse the *any pointer).\n\ttree.Set(\"int\", 99)\n\tif v := tree.Get(\"int\"); v != 99 {\n\t\tt.Errorf(\"Expected 99 after update, got %v\", v)\n\t}\n\n\t// Remove nil value.\n\tv, ok := tree.Remove(\"nil\")\n\tif !ok || v != nil {\n\t\tt.Errorf(\"Remove nil: got (%v, %v), want (nil, true)\", v, ok)\n\t}\n\n\t// Remove typed value.\n\tv, ok = tree.Remove(\"int\")\n\tif !ok || v != 99 {\n\t\tt.Errorf(\"Remove int: got (%v, %v), want (99, true)\", v, ok)\n\t}\n\n\t// Large string values — each stored as separate *any object.\n\tbigVal := make([]byte, 10000)\n\tfor i := range bigVal {\n\t\tbigVal[i] = byte(i % 256)\n\t}\n\tfor i := 0; i \u003c 10; i++ {\n\t\ttree.Set(intToKey(i), string(bigVal))\n\t}\n\tif tree.Size() != 12 { // 10 new + \"str\" + \"slice\" remaining\n\t\tt.Errorf(\"Expected size 12, got %d\", tree.Size())\n\t}\n\n\t// Verify large values round-trip correctly.\n\tfor i := 0; i \u003c 10; i++ {\n\t\tv := tree.Get(intToKey(i))\n\t\tif v == nil {\n\t\t\tt.Errorf(\"Missing key %s\", intToKey(i))\n\t\t\tcontinue\n\t\t}\n\t\ts := v.(string)\n\t\tif len(s) != 10000 {\n\t\t\tt.Errorf(\"Key %s: expected 10000-byte string, got %d\", intToKey(i), len(s))\n\t\t}\n\t}\n\n\t// Iteration with mixed values.\n\tcount := 0\n\ttree.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\tcount++\n\t\treturn false\n\t})\n\tif count != 12 {\n\t\tt.Errorf(\"Iterate counted %d, want 12\", count)\n\t}\n\n\t// Remove all and verify clean.\n\tfor i := 0; i \u003c 10; i++ {\n\t\ttree.Remove(intToKey(i))\n\t}\n\ttree.Remove(\"str\")\n\ttree.Remove(\"slice\")\n\tif tree.Size() != 0 {\n\t\tt.Errorf(\"Expected empty tree, got size %d\", tree.Size())\n\t}\n}\n\nfunc TestFanoutPanics(t *testing.T) {\n\tassertPanics(t, \"fanout 3\", func() {\n\t\tNewBPTreeN(3)\n\t})\n\tassertPanics(t, \"fanout 0\", func() {\n\t\tNewBPTreeN(0)\n\t})\n}\n\n//----------------------------------------\n// Ported from avl/v0 node_test.gno\n\nfunc TestHasTableDriven(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{\"has key in non-empty tree\", []string{\"C\", \"A\", \"B\", \"E\", \"D\"}, \"B\", true},\n\t\t{\"does not have key in non-empty tree\", []string{\"C\", \"A\", \"B\", \"E\", \"D\"}, \"F\", false},\n\t\t{\"has key in single-node tree\", []string{\"A\"}, \"A\", true},\n\t\t{\"does not have key in single-node tree\", []string{\"A\"}, \"B\", false},\n\t\t{\"does not have key in empty tree\", []string{}, \"A\", false},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttree := NewBPTreeN(4)\n\t\t\tfor _, key := range tt.input {\n\t\t\t\ttree.Set(key, nil)\n\t\t\t}\n\t\t\tresult := tree.Has(tt.hasKey)\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 TestGetByIndexTableDriven(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tinput       []string\n\t\tidx         int\n\t\texpectKey   string\n\t\texpectPanic bool\n\t}{\n\t\t{\"get by valid index\", []string{\"C\", \"A\", \"B\", \"E\", \"D\"}, 2, \"C\", false},\n\t\t{\"get by valid index (smallest)\", []string{\"C\", \"A\", \"B\", \"E\", \"D\"}, 0, \"A\", false},\n\t\t{\"get by valid index (largest)\", []string{\"C\", \"A\", \"B\", \"E\", \"D\"}, 4, \"E\", false},\n\t\t{\"get by invalid index (negative)\", []string{\"C\", \"A\", \"B\", \"E\", \"D\"}, -1, \"\", true},\n\t\t{\"get by invalid index (out of range)\", []string{\"C\", \"A\", \"B\", \"E\", \"D\"}, 5, \"\", true},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttree := NewBPTreeN(4)\n\t\t\tfor _, key := range tt.input {\n\t\t\t\ttree.Set(key, nil)\n\t\t\t}\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\t\t\tkey, _ := tree.GetByIndex(tt.idx)\n\t\t\tif !tt.expectPanic \u0026\u0026 key != tt.expectKey {\n\t\t\t\tt.Errorf(\"Expected key %s, got %s\", tt.expectKey, key)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestRemoveTableDriven(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{\"remove from middle\", []string{\"C\", \"A\", \"B\", \"D\"}, \"B\", []string{\"A\", \"C\", \"D\"}},\n\t\t{\"remove first key\", []string{\"C\", \"A\", \"B\", \"D\"}, \"A\", []string{\"B\", \"C\", \"D\"}},\n\t\t{\"remove last key\", []string{\"C\", \"A\", \"B\", \"E\", \"D\"}, \"E\", []string{\"A\", \"B\", \"C\", \"D\"}},\n\t\t{\"remove root-equivalent key\", []string{\"C\", \"A\", \"B\", \"E\", \"D\"}, \"C\", []string{\"A\", \"B\", \"D\", \"E\"}},\n\t\t{\"remove non-existent key\", []string{\"C\", \"A\", \"B\", \"E\", \"D\"}, \"F\", []string{\"A\", \"B\", \"C\", \"D\", \"E\"}},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttree := NewBPTreeN(4)\n\t\t\tfor _, key := range tt.input {\n\t\t\t\ttree.Set(key, nil)\n\t\t\t}\n\t\t\ttree.Remove(tt.removeKey)\n\t\t\tvar result []string\n\t\t\ttree.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\t\t\tresult = append(result, key)\n\t\t\t\treturn false\n\t\t\t})\n\t\t\tif len(result) == 0 {\n\t\t\t\tresult = []string{}\n\t\t\t}\n\t\t\tassertSliceEqual(t, result, tt.expected)\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{\"empty tree\", []string{}, []string{}},\n\t\t{\"single node tree\", []string{\"A\"}, []string{\"A\"}},\n\t\t{\"small tree\", []string{\"C\", \"A\", \"B\", \"E\", \"D\"}, []string{\"A\", \"B\", \"C\", \"D\", \"E\"}},\n\t\t{\"large tree\", []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}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttree := NewBPTreeN(4)\n\t\t\tfor _, key := range tt.input {\n\t\t\t\ttree.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(key string, value any) bool {\n\t\t\t\t\tresult = append(result, key)\n\t\t\t\t\treturn false\n\t\t\t\t})\n\t\t\t\tif len(result) == 0 {\n\t\t\t\t\tresult = []string{}\n\t\t\t\t}\n\t\t\t\tassertSliceEqual(t, result, tt.expected)\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(key string, value any) bool {\n\t\t\t\t\tresult = append(result, 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 len(result) == 0 {\n\t\t\t\t\tresult = []string{}\n\t\t\t\t}\n\t\t\t\tassertSliceEqual(t, result, expected)\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.Iterate(start, end, func(key string, value any) bool {\n\t\t\t\t\tresult = append(result, 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 len(result) == 0 {\n\t\t\t\t\tresult = []string{}\n\t\t\t\t}\n\t\t\t\tassertSliceEqual(t, result, expected)\n\t\t\t})\n\n\t\t\tt.Run(\"early termination\", func(t *testing.T) {\n\t\t\t\tif len(tt.input) == 0 {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tvar result []string\n\t\t\t\tvar count int\n\t\t\t\ttree.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\t\t\t\tcount++\n\t\t\t\t\tresult = append(result, key)\n\t\t\t\t\treturn true\n\t\t\t\t})\n\t\t\t\tif count != 1 {\n\t\t\t\t\tt.Errorf(\"Expected callback to be called exactly once, got %d calls\", count)\n\t\t\t\t}\n\t\t\t\tif len(result) != 1 {\n\t\t\t\t\tt.Errorf(\"Expected exactly one result, got %d items\", len(result))\n\t\t\t\t}\n\t\t\t\tif len(result) \u003e 0 \u0026\u0026 result[0] != tt.expected[0] {\n\t\t\t\t\tt.Errorf(\"Expected first item to be %v, got %v\", tt.expected[0], result[0])\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}\n}\n\nfunc TestTraverseByOffset(t *testing.T) {\n\tsl := []string{\"Alfa\", \"Alfred\", \"Alpha\", \"Alphabet\", \"Beta\", \"Beth\", \"Book\", \"Browser\"}\n\n\t// Insert in reverse order to ensure ordering is independent of insertion order.\n\treversed := make([]string, len(sl))\n\tcopy(reversed, sl)\n\tfor i, j := 0, len(reversed)-1; i \u003c j; i, j = i+1, j-1 {\n\t\treversed[i], reversed[j] = reversed[j], reversed[i]\n\t}\n\n\tt.Run(\"ascending\", func(t *testing.T) {\n\t\ttree := NewBPTreeN(4)\n\t\tfor _, v := range reversed {\n\t\t\ttree.Set(v, nil)\n\t\t}\n\n\t\t// Single-element offset traversal.\n\t\tvar result []string\n\t\tfor i := 0; i \u003c len(sl); i++ {\n\t\t\ttree.IterateByOffset(i, 1, func(key string, value any) bool {\n\t\t\t\tresult = append(result, key)\n\t\t\t\treturn false\n\t\t\t})\n\t\t}\n\t\tassertSliceEqual(t, result, sl)\n\n\t\t// Sliding window.\n\t\tfor l := 2; l \u003c= len(sl); l++ {\n\t\t\tfor i := 0; i \u003c= len(sl); i++ {\n\t\t\t\tmax := i + l\n\t\t\t\tif max \u003e len(sl) {\n\t\t\t\t\tmax = len(sl)\n\t\t\t\t}\n\t\t\t\texp := sl[i:max]\n\t\t\t\tvar actual []string\n\t\t\t\ttree.IterateByOffset(i, l, func(key string, value any) bool {\n\t\t\t\t\tactual = append(actual, key)\n\t\t\t\t\treturn false\n\t\t\t\t})\n\t\t\t\tif len(actual) == 0 {\n\t\t\t\t\tactual = []string{}\n\t\t\t\t}\n\t\t\t\tassertSliceEqual(t, actual, exp)\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"descending\", func(t *testing.T) {\n\t\ttree := NewBPTreeN(4)\n\t\tfor _, v := range reversed {\n\t\t\ttree.Set(v, nil)\n\t\t}\n\n\t\t// The descending order.\n\t\tdesc := make([]string, len(sl))\n\t\tcopy(desc, sl)\n\t\tfor i, j := 0, len(desc)-1; i \u003c j; i, j = i+1, j-1 {\n\t\t\tdesc[i], desc[j] = desc[j], desc[i]\n\t\t}\n\n\t\t// Single-element offset traversal in reverse.\n\t\tvar result []string\n\t\tfor i := 0; i \u003c len(desc); i++ {\n\t\t\ttree.ReverseIterateByOffset(i, 1, func(key string, value any) bool {\n\t\t\t\tresult = append(result, key)\n\t\t\t\treturn false\n\t\t\t})\n\t\t}\n\t\tassertSliceEqual(t, result, desc)\n\n\t\t// Sliding window in descending.\n\t\tfor l := 2; l \u003c= len(desc); l++ {\n\t\t\tfor i := 0; i \u003c= len(desc); i++ {\n\t\t\t\tmax := i + l\n\t\t\t\tif max \u003e len(desc) {\n\t\t\t\t\tmax = len(desc)\n\t\t\t\t}\n\t\t\t\texp := desc[i:max]\n\t\t\t\tvar actual []string\n\t\t\t\ttree.ReverseIterateByOffset(i, l, func(key string, value any) bool {\n\t\t\t\t\tactual = append(actual, key)\n\t\t\t\t\treturn false\n\t\t\t\t})\n\t\t\t\tif len(actual) == 0 {\n\t\t\t\t\tactual = []string{}\n\t\t\t\t}\n\t\t\t\tassertSliceEqual(t, actual, exp)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestBSTProperty(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\tkeys := []string{\"D\", \"B\", \"F\", \"A\", \"C\", \"E\", \"G\"}\n\tfor _, key := range keys {\n\t\ttree.Set(key, nil)\n\t}\n\n\tvar result []string\n\ttree.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\tresult = append(result, key)\n\t\treturn false\n\t})\n\n\tfor i := 1; i \u003c len(result); i++ {\n\t\tif result[i] \u003c result[i-1] {\n\t\t\tt.Errorf(\"Sorted property violated: %s \u003c %s (index %d)\",\n\t\t\t\tresult[i], result[i-1], i)\n\t\t}\n\t}\n}\n\nfunc TestRemoveFromEmptyTree(t *testing.T) {\n\tvar tree BPTree\n\tval, removed := tree.Remove(\"NonExistent\")\n\tif val != nil || removed {\n\t\tt.Errorf(\"Expected no value and removed=false when removing from empty tree\")\n\t}\n}\n\n// Ported from avl tree_test.gno\n\nfunc TestPortedTreeSize(t *testing.T) {\n\ttree := NewBPTree32()\n\tif tree.Size() != 0 {\n\t\tt.Error(\"Expected empty tree size to be 0\")\n\t}\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 TestPortedTreeHas(t *testing.T) {\n\ttree := NewBPTree32()\n\ttree.Set(\"key1\", \"value1\")\n\tif !tree.Has(\"key1\") {\n\t\tt.Error(\"Expected tree to have key1\")\n\t}\n\tif tree.Has(\"key2\") {\n\t\tt.Error(\"Expected tree to not have key2\")\n\t}\n}\n\nfunc TestPortedTreeGet(t *testing.T) {\n\ttree := NewBPTree32()\n\ttree.Set(\"key1\", \"value1\")\n\tif value := tree.Get(\"key1\"); value != \"value1\" {\n\t\tt.Error(\"Expected Get to return value1\")\n\t}\n\tif value := tree.Get(\"key2\"); value != nil {\n\t\tt.Error(\"Expected Get to return nil for non-existent key\")\n\t}\n}\n\nfunc TestPortedTreeGetByIndex(t *testing.T) {\n\ttree := NewBPTree32()\n\ttree.Set(\"key1\", \"value1\")\n\ttree.Set(\"key2\", \"value2\")\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\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\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 TestPortedTreeRemove(t *testing.T) {\n\ttree := NewBPTree32()\n\ttree.Set(\"key1\", \"value1\")\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\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 TestPortedTreeIterate(t *testing.T) {\n\ttree := NewBPTree32()\n\ttree.Set(\"key1\", \"value1\")\n\ttree.Set(\"key2\", \"value2\")\n\ttree.Set(\"key3\", \"value3\")\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\tassertSliceEqual(t, keys, []string{\"key1\", \"key2\", \"key3\"})\n}\n\nfunc TestPortedTreeReverseIterate(t *testing.T) {\n\ttree := NewBPTree32()\n\ttree.Set(\"key1\", \"value1\")\n\ttree.Set(\"key2\", \"value2\")\n\ttree.Set(\"key3\", \"value3\")\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\tassertSliceEqual(t, keys, []string{\"key3\", \"key2\", \"key1\"})\n}\n\nfunc TestPortedTreeIterateByOffset(t *testing.T) {\n\ttree := NewBPTree32()\n\ttree.Set(\"key1\", \"value1\")\n\ttree.Set(\"key2\", \"value2\")\n\ttree.Set(\"key3\", \"value3\")\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\tassertSliceEqual(t, keys, []string{\"key2\", \"key3\"})\n}\n\nfunc TestPortedTreeReverseIterateByOffset(t *testing.T) {\n\ttree := NewBPTree32()\n\ttree.Set(\"key1\", \"value1\")\n\ttree.Set(\"key2\", \"value2\")\n\ttree.Set(\"key3\", \"value3\")\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\tassertSliceEqual(t, keys, []string{\"key2\", \"key1\"})\n}\n\nfunc TestPortedReverseIterateByOffsetVaried(t *testing.T) {\n\ttree := NewBPTree32()\n\ttree.Set(\"a\", 1)\n\ttree.Set(\"b\", 2)\n\ttree.Set(\"c\", 3)\n\ttree.Set(\"d\", 4)\n\ttree.Set(\"e\", 5)\n\n\tcases := []struct {\n\t\toffset int\n\t\tlimit  int\n\t\twant   []string\n\t}{\n\t\t{0, 5, []string{\"e\", \"d\", \"c\", \"b\", \"a\"}},\n\t\t{0, 1, []string{\"e\"}},\n\t\t{0, 3, []string{\"e\", \"d\", \"c\"}},\n\t\t{1, 2, []string{\"d\", \"c\"}},\n\t\t{2, 2, []string{\"c\", \"b\"}},\n\t\t{3, 5, []string{\"b\", \"a\"}},\n\t\t{4, 1, []string{\"a\"}},\n\t\t{4, 10, []string{\"a\"}},\n\t\t{5, 1, nil},\n\t\t{0, 0, nil},\n\t\t{10, 1, nil},\n\t}\n\n\tfor _, tc := range cases {\n\t\tvar got []string\n\t\ttree.ReverseIterateByOffset(tc.offset, tc.limit, func(key string, value any) bool {\n\t\t\tgot = append(got, key)\n\t\t\treturn false\n\t\t})\n\t\tif !slicesEqual(got, tc.want) {\n\t\t\tt.Errorf(\"ReverseIterateByOffset(%d, %d): got %v, want %v\",\n\t\t\t\ttc.offset, tc.limit, got, tc.want)\n\t\t}\n\t}\n\n\t// Early termination.\n\tvar got []string\n\ttree.ReverseIterateByOffset(1, 5, func(key string, value any) bool {\n\t\tgot = append(got, key)\n\t\treturn len(got) \u003e= 2\n\t})\n\tassertSliceEqual(t, got, []string{\"d\", \"c\"})\n}\n\nfunc TestPortedBalanceAfterRemoval(t *testing.T) {\n\t// This tests the behavioral equivalence: after various insert/remove\n\t// patterns, the tree maintains correct sorted order and all keys are\n\t// accessible. (AVL tests checked balance factors; we check correctness.)\n\ttests := []struct {\n\t\tname       string\n\t\tinsertKeys []string\n\t\tremoveKey  string\n\t}{\n\t\t{\"remove right node\", []string{\"B\", \"A\", \"D\", \"C\", \"E\"}, \"E\"},\n\t\t{\"remove left node\", []string{\"D\", \"B\", \"E\", \"A\", \"C\"}, \"A\"},\n\t\t{\"remove after complex insert\", []string{\"C\", \"B\", \"E\", \"A\", \"D\", \"F\"}, \"F\"},\n\t\t{\"descending insert, remove middle\", []string{\"E\", \"D\", \"C\", \"B\", \"A\"}, \"C\"},\n\t\t{\"ascending insert, remove middle\", []string{\"A\", \"B\", \"C\", \"D\", \"E\"}, \"C\"},\n\t\t{\"duplicate insert, remove key\", []string{\"C\", \"B\", \"C\", \"A\", \"D\"}, \"C\"},\n\t\t{\"complex case\", []string{\"H\", \"B\", \"A\", \"C\", \"E\", \"D\", \"F\", \"G\"}, \"B\"},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttree := NewBPTreeN(4)\n\t\t\tfor _, key := range tt.insertKeys {\n\t\t\t\ttree.Set(key, nil)\n\t\t\t}\n\t\t\ttree.Remove(tt.removeKey)\n\n\t\t\t// Verify sorted order.\n\t\t\tvar result []string\n\t\t\ttree.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\t\t\tresult = append(result, key)\n\t\t\t\treturn false\n\t\t\t})\n\t\t\tfor i := 1; i \u003c len(result); i++ {\n\t\t\t\tif result[i] \u003c= result[i-1] {\n\t\t\t\t\tt.Errorf(\"Sorted property violated: %s \u003c= %s\", result[i], result[i-1])\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Verify all expected keys present.\n\t\t\tfor _, key := range tt.insertKeys {\n\t\t\t\tif key == tt.removeKey {\n\t\t\t\t\tif tree.Has(key) {\n\t\t\t\t\t\t// Only check if the key was unique (not duplicated).\n\t\t\t\t\t\t// With duplicates, Set overwrites, so there's only one copy.\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\n//----------------------------------------\n// Structural invariant verification\n\n// verifyInvariants checks all B+ tree structural invariants.\nfunc verifyInvariants(t *testing.T, tree *BPTree) {\n\tt.Helper()\n\tif tree.root == nil {\n\t\tif tree.size != 0 {\n\t\t\tt.Errorf(\"nil root but size=%d\", tree.size)\n\t\t}\n\t\treturn\n\t}\n\n\t// Check leaf depth uniformity.\n\tdepth := leafDepth(tree.root, 0)\n\tif depth == -1 {\n\t\tt.Error(\"leaves are at different depths\")\n\t}\n\n\t// Check separator keys, child count bounds, sizes, ref-count.\n\tseen := make(map[node]bool)\n\tverifyNode(t, tree.root, tree.fanout, true, seen)\n\n\t// Check tree.size matches actual leaf count.\n\tactual := tree.root.nodeSize()\n\tif tree.size != actual {\n\t\tt.Errorf(\"tree.size=%d but root.nodeSize()=%d\", tree.size, actual)\n\t}\n}\n\nfunc leafDepth(n node, depth int) int {\n\tif n.isLeaf() {\n\t\treturn depth\n\t}\n\tinner := n.(*innerNode)\n\td := -1\n\tfor _, child := range inner.children {\n\t\tcd := leafDepth(child, depth+1)\n\t\tif d == -1 {\n\t\t\td = cd\n\t\t} else if cd != d {\n\t\t\treturn -1\n\t\t}\n\t}\n\treturn d\n}\n\nfunc verifyNode(t *testing.T, n node, fanout int, isRoot bool, seen map[node]bool) {\n\tt.Helper()\n\tif seen[n] {\n\t\tt.Errorf(\"node reachable by multiple paths (ref-count \u003e= 2)\")\n\t\treturn\n\t}\n\tseen[n] = true\n\n\tif n.isLeaf() {\n\t\tleaf := n.(*leafNode)\n\t\tif len(leaf.keys) == 0 \u0026\u0026 !isRoot {\n\t\t\tt.Errorf(\"non-root leaf has 0 keys\")\n\t\t}\n\t\tif len(leaf.keys) \u003e fanout {\n\t\t\tt.Errorf(\"leaf has %d keys, max=%d\", len(leaf.keys), fanout)\n\t\t}\n\t\treturn\n\t}\n\n\tinner := n.(*innerNode)\n\n\t// Child count bounds.\n\tminC := fanout / 2\n\tif isRoot {\n\t\tminC = 2\n\t}\n\tif len(inner.children) \u003c minC \u0026\u0026 !isRoot {\n\t\tt.Errorf(\"inner node has %d children, min=%d\", len(inner.children), minC)\n\t}\n\tif len(inner.children) \u003e fanout {\n\t\tt.Errorf(\"inner node has %d children, max=%d\", len(inner.children), fanout)\n\t}\n\n\t// keys/children/sizes length consistency.\n\tif len(inner.keys) != len(inner.children)-1 {\n\t\tt.Errorf(\"len(keys)=%d but len(children)=%d\", len(inner.keys), len(inner.children))\n\t}\n\tif len(inner.sizes) != len(inner.children) {\n\t\tt.Errorf(\"len(sizes)=%d but len(children)=%d\", len(inner.sizes), len(inner.children))\n\t}\n\n\t// Separator key correctness: keys[i] == children[i+1].minKey().\n\tfor i, k := range inner.keys {\n\t\texpected := inner.children[i+1].minKey()\n\t\tif k != expected {\n\t\t\tt.Errorf(\"separator keys[%d]=%q but children[%d].minKey()=%q\", i, k, i+1, expected)\n\t\t}\n\t}\n\n\t// sizes[i] matches child.\n\tfor i, child := range inner.children {\n\t\tactual := child.nodeSize()\n\t\tif inner.sizes[i] != actual {\n\t\t\tt.Errorf(\"sizes[%d]=%d but child.nodeSize()=%d\", i, inner.sizes[i], actual)\n\t\t}\n\t\tverifyNode(t, child, fanout, false, seen)\n\t}\n}\n\nfunc TestInvariantsAfterEveryOperation(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\tkeys := []string{\"m\", \"f\", \"t\", \"b\", \"i\", \"p\", \"w\", \"a\", \"d\", \"g\", \"k\", \"n\", \"r\", \"u\", \"y\"}\n\n\tfor _, k := range keys {\n\t\ttree.Set(k, k)\n\t\tverifyInvariants(t, tree)\n\t}\n\tfor _, k := range keys {\n\t\ttree.Remove(k)\n\t\tverifyInvariants(t, tree)\n\t}\n}\n\n//----------------------------------------\n// Behavioral parity: GetByIndex == IterateByOffset\n\nfunc TestGetByIndexMatchesIterateByOffset(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\tfor _, k := range []string{\"h\", \"d\", \"l\", \"b\", \"f\", \"j\", \"n\", \"a\", \"c\", \"e\", \"g\"} {\n\t\ttree.Set(k, k)\n\t}\n\n\tfor i := 0; i \u003c tree.Size(); i++ {\n\t\tk1, v1 := tree.GetByIndex(i)\n\t\tvar k2 string\n\t\tvar v2 any\n\t\ttree.IterateByOffset(i, 1, func(k string, v any) bool {\n\t\t\tk2 = k\n\t\t\tv2 = v\n\t\t\treturn true\n\t\t})\n\t\tif k1 != k2 || v1 != v2 {\n\t\t\tt.Errorf(\"index %d: GetByIndex=(%q,%v) but IterateByOffset=(%q,%v)\", i, k1, v1, k2, v2)\n\t\t}\n\t}\n}\n\n//----------------------------------------\n// Stress: oscillating tree size\n\nfunc TestOscillatingSize(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\n\t// Insert 100.\n\tfor i := 0; i \u003c 100; i++ {\n\t\ttree.Set(intToKey(i), i)\n\t}\n\tverifyInvariants(t, tree)\n\n\t// Remove 50.\n\tfor i := 0; i \u003c 50; i++ {\n\t\ttree.Remove(intToKey(i))\n\t}\n\tverifyInvariants(t, tree)\n\tif tree.Size() != 50 {\n\t\tt.Errorf(\"Expected size 50, got %d\", tree.Size())\n\t}\n\n\t// Insert 50 new.\n\tfor i := 100; i \u003c 150; i++ {\n\t\ttree.Set(intToKey(i), i)\n\t}\n\tverifyInvariants(t, tree)\n\tif tree.Size() != 100 {\n\t\tt.Errorf(\"Expected size 100, got %d\", tree.Size())\n\t}\n\n\t// Remove all.\n\tfor i := 50; i \u003c 150; i++ {\n\t\ttree.Remove(intToKey(i))\n\t}\n\tverifyInvariants(t, tree)\n\tif tree.Size() != 0 {\n\t\tt.Errorf(\"Expected size 0, got %d\", tree.Size())\n\t}\n\n\t// Insert again from empty.\n\tfor i := 0; i \u003c 20; i++ {\n\t\ttree.Set(intToKey(i), i)\n\t}\n\tverifyInvariants(t, tree)\n\tif tree.Size() != 20 {\n\t\tt.Errorf(\"Expected size 20, got %d\", tree.Size())\n\t}\n}\n\n//----------------------------------------\n// All 6 rebalance paths\n\nfunc TestAllRebalancePaths(t *testing.T) {\n\t// We use fanout=4 so min=2 for leaves.\n\t// Each sub-test constructs a specific tree state and triggers one rebalance path.\n\n\tt.Run(\"leaf redistribute from left\", func(t *testing.T) {\n\t\ttree := NewBPTreeN(4)\n\t\tfor _, k := range []string{\"a\", \"b\", \"c\", \"d\", \"e\"} {\n\t\t\ttree.Set(k, k)\n\t\t}\n\t\t// After 90/10 split: left=[a,b,c], right=[d,e].\n\t\t// Remove \"d\" → right=[e] (1 \u003c min=2). Left has 3 \u003e 2 → redistribute from left.\n\t\ttree.Remove(\"d\")\n\t\tverifyInvariants(t, tree)\n\t\tif !tree.Has(\"e\") {\n\t\t\tt.Error(\"Missing key 'e' after redistribute\")\n\t\t}\n\t})\n\n\tt.Run(\"leaf redistribute from right\", func(t *testing.T) {\n\t\ttree := NewBPTreeN(4)\n\t\tfor _, k := range []string{\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\"} {\n\t\t\ttree.Set(k, k)\n\t\t}\n\t\t// Remove from leftmost leaf until it underflows and must redistribute from right.\n\t\ttree.Remove(\"a\")\n\t\ttree.Remove(\"b\")\n\t\tverifyInvariants(t, tree)\n\t})\n\n\tt.Run(\"leaf redistribute from right, no stale root separator keys\", func(t *testing.T) {\n\t\ttree := NewBPTreeN(4)\n\t\tfor _, k := range []string{\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\"} {\n\t\t\ttree.Set(k, k)\n\t\t}\n\t\ttree.Remove(\"g\") // no underflow\n\t\ttree.Remove(\"h\") // leaf [h,i] underflows and must redistribute from right\n\t\tverifyInvariants(t, tree)\n\t})\n\n\tt.Run(\"leaf redistribute from right, no stale inner node separator keys\", func(t *testing.T) {\n\t\ttree := NewBPTreeN(4)\n\t\tfor _, k := range []string{\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\"} {\n\t\t\ttree.Set(k, k)\n\t\t}\n\t\ttree.Remove(\"g\") // no underflow\n\t\ttree.Remove(\"j\") // no underflow\n\t\ttree.Remove(\"k\") // leaf [k,l] underflows and must redistribute from right\n\t\tverifyInvariants(t, tree)\n\t})\n\n\tt.Run(\"stale separator, middle leaf pos0 redistribute from right\", func(t *testing.T) {\n\t\t// Exercises the core bug: remove pos=0 from a middle leaf (childIdx \u003e 0),\n\t\t// where left sibling is at minimum (can't redistribute left) and right\n\t\t// sibling has surplus (redistribute right fires). Without the fix,\n\t\t// parent.keys[childIdx-1] remains stale.\n\t\t//\n\t\t// After inserting a-k with fanout=4, tree is:\n\t\t//   root keys=[\"d\",\"g\",\"j\"]\n\t\t//   children=[[\"a\",\"b\",\"c\"], [\"d\",\"e\",\"f\"], [\"g\",\"h\",\"i\"], [\"j\",\"k\"]]\n\t\t//\n\t\t// Remove \"a\" thins children[0] to [\"b\",\"c\"] (at minimum).\n\t\t// Remove \"f\" thins children[1] to [\"d\",\"e\"] (at minimum).\n\t\t// Remove \"d\" is pos=0 from children[1], causing underflow to [\"e\"].\n\t\t//   Left sibling [\"b\",\"c\"] has 2 = minKeys, can't spare.\n\t\t//   Right sibling [\"g\",\"h\",\"i\"] has 3 \u003e minKeys, redistribute right fires.\n\t\t//   Without fix: keys[0] stays \"d\" (stale). With fix: updated to \"e\".\n\t\ttree := NewBPTreeN(4)\n\t\tfor _, k := range []string{\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\"} {\n\t\t\ttree.Set(k, k)\n\t\t}\n\t\ttree.Remove(\"a\") // thin left sibling to minimum\n\t\ttree.Remove(\"f\") // thin target leaf to minimum\n\t\ttree.Remove(\"d\") // pos=0, underflow, triggers redistribute from right\n\t\tverifyInvariants(t, tree)\n\t})\n\n\tt.Run(\"leaf merge\", func(t *testing.T) {\n\t\ttree := NewBPTreeN(4)\n\t\tfor _, k := range []string{\"a\", \"b\", \"c\", \"d\", \"e\"} {\n\t\t\ttree.Set(k, k)\n\t\t}\n\t\t// Remove enough to make both siblings at minimum, then one more triggers merge.\n\t\ttree.Remove(\"a\")\n\t\ttree.Remove(\"b\") // left=[c], right=[d,e]. left underflows. right has 2=min. merge.\n\t\tverifyInvariants(t, tree)\n\t\tgot := collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\t\treturn tr.Iterate(\"\", \"\", cb)\n\t\t})\n\t\tassertSliceEqual(t, got, []string{\"c\", \"d\", \"e\"})\n\t})\n\n\tt.Run(\"inner redistribute from left\", func(t *testing.T) {\n\t\t// Build a tree with enough inner nodes, then remove to trigger inner rebalance.\n\t\ttree := NewBPTreeN(4)\n\t\tfor i := 0; i \u003c 30; i++ {\n\t\t\ttree.Set(intToKey(i), i)\n\t\t}\n\t\t// Remove from the right side to underflow a right inner node.\n\t\tfor i := 25; i \u003c 30; i++ {\n\t\t\ttree.Remove(intToKey(i))\n\t\t}\n\t\tverifyInvariants(t, tree)\n\t})\n\n\tt.Run(\"inner redistribute from right\", func(t *testing.T) {\n\t\ttree := NewBPTreeN(4)\n\t\tfor i := 0; i \u003c 30; i++ {\n\t\t\ttree.Set(intToKey(i), i)\n\t\t}\n\t\t// Remove from the left side to underflow a left inner node.\n\t\tfor i := 0; i \u003c 5; i++ {\n\t\t\ttree.Remove(intToKey(i))\n\t\t}\n\t\tverifyInvariants(t, tree)\n\t})\n\n\tt.Run(\"inner merge\", func(t *testing.T) {\n\t\ttree := NewBPTreeN(4)\n\t\tfor i := 0; i \u003c 20; i++ {\n\t\t\ttree.Set(intToKey(i), i)\n\t\t}\n\t\t// Remove enough to trigger inner merge.\n\t\tfor i := 0; i \u003c 15; i++ {\n\t\t\ttree.Remove(intToKey(i))\n\t\t}\n\t\tverifyInvariants(t, tree)\n\t\tif tree.Size() != 5 {\n\t\t\tt.Errorf(\"Expected size 5, got %d\", tree.Size())\n\t\t}\n\t})\n}\n\n//----------------------------------------\n// Value mutation after Get should not affect tree\n\nfunc TestValueMutationIndependence(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\n\t// Store a slice value.\n\torig := []int{1, 2, 3}\n\ttree.Set(\"k\", orig)\n\n\t// Get the value and mutate it.\n\tv := tree.Get(\"k\")\n\tgot := v.([]int)\n\tgot[0] = 999\n\n\t// The tree's stored value should also be affected (since slices are reference types\n\t// and *any holds the same interface). This is the expected Go behavior — not a copy.\n\tv2 := tree.Get(\"k\")\n\tgot2 := v2.([]int)\n\tif got2[0] != 999 {\n\t\tt.Errorf(\"Expected slice mutation to be visible (reference semantics), got %v\", got2)\n\t}\n\n\t// But replacing the value via Set should not affect previous Get results.\n\ttree.Set(\"k\", []int{10, 20, 30})\n\tv3 := tree.Get(\"k\")\n\tgot3 := v3.([]int)\n\tif got3[0] != 10 {\n\t\tt.Errorf(\"Expected new value after Set, got %v\", got3)\n\t}\n\t// The old reference should still have 999.\n\tif got[0] != 999 {\n\t\tt.Errorf(\"Old reference should still be 999, got %v\", got)\n\t}\n}\n\n//----------------------------------------\n// Comprehensive invariant check across fanouts and sizes\n\nfunc TestInvariantsAcrossFanouts(t *testing.T) {\n\tfor _, fanout := range []int{4, 5, 7, 8, 16, 32} {\n\t\ttree := NewBPTreeN(fanout)\n\t\tn := 200\n\n\t\t// Insert all.\n\t\tfor i := 0; i \u003c n; i++ {\n\t\t\ttree.Set(intToKey(i), i)\n\t\t}\n\t\tverifyInvariants(t, tree)\n\n\t\t// Remove every 3rd.\n\t\tfor i := 0; i \u003c n; i += 3 {\n\t\t\ttree.Remove(intToKey(i))\n\t\t}\n\t\tverifyInvariants(t, tree)\n\n\t\t// Remove remaining.\n\t\tfor i := 0; i \u003c n; i++ {\n\t\t\ttree.Remove(intToKey(i))\n\t\t}\n\t\tverifyInvariants(t, tree)\n\t\tif tree.Size() != 0 {\n\t\t\tt.Errorf(\"fanout=%d: expected size 0, got %d\", fanout, tree.Size())\n\t\t}\n\t}\n}\n\n//----------------------------------------\n// Deep stack unwinding\n\nfunc TestDeepStackUnwinding(t *testing.T) {\n\t// With fanout=4 and 500 keys, the tree is 4-5 levels deep.\n\t// Iterating across subtree boundaries forces advanceLeaf/retreatLeaf\n\t// to pop multiple stack levels.\n\ttree := NewBPTreeN(4)\n\tn := 500\n\tfor i := 0; i \u003c n; i++ {\n\t\ttree.Set(intToKey(i), i)\n\t}\n\n\t// Full ascending iteration — every leaf boundary is crossed.\n\tcount := 0\n\tprev := \"\"\n\ttree.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\tif k \u003c= prev \u0026\u0026 prev != \"\" {\n\t\t\tt.Errorf(\"ascending order broken: %q after %q\", k, prev)\n\t\t}\n\t\tprev = k\n\t\tcount++\n\t\treturn false\n\t})\n\tif count != n {\n\t\tt.Errorf(\"ascending: visited %d, want %d\", count, n)\n\t}\n\n\t// Full descending iteration.\n\tcount = 0\n\tprev = \"\"\n\ttree.ReverseIterate(\"\", \"\", func(k string, v any) bool {\n\t\tif prev != \"\" \u0026\u0026 k \u003e= prev {\n\t\t\tt.Errorf(\"descending order broken: %q after %q\", k, prev)\n\t\t}\n\t\tprev = k\n\t\tcount++\n\t\treturn false\n\t})\n\tif count != n {\n\t\tt.Errorf(\"descending: visited %d, want %d\", count, n)\n\t}\n\n\t// Offset-based iteration crossing deep boundaries.\n\t// Start from the middle, iterate to the end.\n\tcount = 0\n\ttree.IterateByOffset(250, 250, func(k string, v any) bool {\n\t\tcount++\n\t\treturn false\n\t})\n\tif count != 250 {\n\t\tt.Errorf(\"IterateByOffset(250,250): visited %d, want 250\", count)\n\t}\n\n\t// Reverse offset from middle.\n\tcount = 0\n\ttree.ReverseIterateByOffset(250, 250, func(k string, v any) bool {\n\t\tcount++\n\t\treturn false\n\t})\n\tif count != 250 {\n\t\tt.Errorf(\"ReverseIterateByOffset(250,250): visited %d, want 250\", count)\n\t}\n\n\tverifyInvariants(t, tree)\n}\n\n//----------------------------------------\n// Height invariant\n\nfunc treeHeight(n node) int {\n\tif n == nil {\n\t\treturn 0\n\t}\n\tif n.isLeaf() {\n\t\treturn 1\n\t}\n\treturn 1 + treeHeight(n.(*innerNode).children[0])\n}\n\nfunc TestHeightInvariant(t *testing.T) {\n\t// B+ tree with fanout F should have height \u003c= 1 + log_{ceil(F/2)}(n).\n\tfor _, fanout := range []int{4, 8, 32} {\n\t\ttree := NewBPTreeN(fanout)\n\t\tn := 1000\n\t\tfor i := 0; i \u003c n; i++ {\n\t\t\ttree.Set(intToKey(i), i)\n\t\t}\n\n\t\th := treeHeight(tree.root)\n\t\t// Compute max height: log base ceil(fanout/2) of n, plus 1 for root.\n\t\tminFill := fanout / 2\n\t\tif minFill \u003c 2 {\n\t\t\tminFill = 2\n\t\t}\n\t\tmaxH := 1\n\t\tcapacity := 1\n\t\tfor capacity \u003c n {\n\t\t\tcapacity *= minFill\n\t\t\tmaxH++\n\t\t}\n\n\t\tif h \u003e maxH {\n\t\t\tt.Errorf(\"fanout=%d, n=%d: height=%d exceeds max=%d\", fanout, n, h, maxH)\n\t\t}\n\t}\n}\n\n//----------------------------------------\n// Empty string as separator key\n\nfunc TestEmptyStringSeparator(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\n\t// Insert \"\" first, then other keys. With sequential inserts,\n\t// \"\" will end up in the leftmost leaf and could become a separator.\n\ttree.Set(\"\", \"empty\")\n\ttree.Set(\"a\", \"a\")\n\ttree.Set(\"b\", \"b\")\n\ttree.Set(\"c\", \"c\")\n\ttree.Set(\"d\", \"d\") // triggers split; \"\" should be in left leaf\n\n\tverifyInvariants(t, tree)\n\n\t// Verify all keys accessible.\n\tif v := tree.Get(\"\"); v != \"empty\" {\n\t\tt.Errorf(\"Get('')=%v, want empty\", v)\n\t}\n\tfor _, k := range []string{\"a\", \"b\", \"c\", \"d\"} {\n\t\tif !tree.Has(k) {\n\t\t\tt.Errorf(\"missing key %q\", k)\n\t\t}\n\t}\n\n\t// Iterate should include \"\".\n\tgot := collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"\", \"\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"\", \"a\", \"b\", \"c\", \"d\"})\n\n\t// ReverseIterate should include \"\".\n\tgot = collectKeys(tree, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.ReverseIterate(\"\", \"\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"d\", \"c\", \"b\", \"a\", \"\"})\n\n\t// Remove \"\" and verify tree is still valid.\n\tv, ok := tree.Remove(\"\")\n\tif !ok || v != \"empty\" {\n\t\tt.Errorf(\"Remove('')=(%v,%v), want (empty,true)\", v, ok)\n\t}\n\tverifyInvariants(t, tree)\n\tif tree.Has(\"\") {\n\t\tt.Error(\"'' should be gone after remove\")\n\t}\n\n\t// Now insert more keys with \"\" to force it into a separator position.\n\t// Build a tree where \"\" is between two inner node children.\n\ttree2 := NewBPTreeN(4)\n\t// Insert keys that will sort before and after \"\".\n\t// In ASCII, \"\" \u003c everything. So \"\" is always the smallest key.\n\t// To make \"\" a separator, we need it to be the minKey of a right child.\n\t// That happens when the leaf containing \"\" splits and \"\" ends up\n\t// as right.keys[0] (the promoted separator).\n\t// With 50/50 split: left gets lower half, right gets upper half.\n\t// Since \"\" is the smallest, it will always be in the left leaf.\n\t// With 90/10 on append: \"\" would be in the left leaf too.\n\t// So \"\" can become a separator only if it's the minKey of a right child\n\t// after a split where \"\" is in the right half.\n\t// Insert in reverse order so \"\" ends up in the right half of a split:\n\ttree2.Set(\"d\", \"d\")\n\ttree2.Set(\"c\", \"c\")\n\ttree2.Set(\"b\", \"b\")\n\ttree2.Set(\"a\", \"a\")\n\ttree2.Set(\"\", \"empty\") // inserted at position 0 (not append), 50/50 split\n\n\tverifyInvariants(t, tree2)\n\tgot = collectKeys(tree2, func(tr *BPTree, cb IterCbFn) bool {\n\t\treturn tr.Iterate(\"\", \"\", cb)\n\t})\n\tassertSliceEqual(t, got, []string{\"\", \"a\", \"b\", \"c\", \"d\"})\n}\n\n//----------------------------------------\n// Pointer independence after split\n\nfunc TestPointerIndependenceAfterSplit(t *testing.T) {\n\ttree := NewBPTreeN(4)\n\n\t// Insert 5 keys to trigger a split.\n\ttree.Set(\"a\", \"val_a\")\n\ttree.Set(\"b\", \"val_b\")\n\ttree.Set(\"c\", \"val_c\")\n\ttree.Set(\"d\", \"val_d\")\n\ttree.Set(\"e\", \"val_e\") // triggers split\n\n\t// Get values from both halves of the split.\n\tvLeft := tree.Get(\"a\")\n\tvRight := tree.Get(\"d\")\n\n\tif vLeft != \"val_a\" {\n\t\tt.Errorf(\"left value: got %v, want val_a\", vLeft)\n\t}\n\tif vRight != \"val_d\" {\n\t\tt.Errorf(\"right value: got %v, want val_d\", vRight)\n\t}\n\n\t// Update a value in the left half — should not affect right half.\n\ttree.Set(\"a\", \"new_a\")\n\tvLeft2 := tree.Get(\"a\")\n\tvRight2 := tree.Get(\"d\")\n\tif vLeft2 != \"new_a\" {\n\t\tt.Errorf(\"updated left: got %v, want new_a\", vLeft2)\n\t}\n\tif vRight2 != \"val_d\" {\n\t\tt.Errorf(\"right should be unchanged: got %v, want val_d\", vRight2)\n\t}\n\n\t// Update a value in the right half — should not affect left half.\n\ttree.Set(\"d\", \"new_d\")\n\tvLeft3 := tree.Get(\"a\")\n\tvRight3 := tree.Get(\"d\")\n\tif vLeft3 != \"new_a\" {\n\t\tt.Errorf(\"left should be unchanged: got %v, want new_a\", vLeft3)\n\t}\n\tif vRight3 != \"new_d\" {\n\t\tt.Errorf(\"updated right: got %v, want new_d\", vRight3)\n\t}\n\n\t// Verify that the *any pointers in the two leaves are different objects.\n\t// Access internals to check.\n\tinner := tree.root.(*innerNode)\n\tleftLeaf := inner.children[0].(*leafNode)\n\trightLeaf := inner.children[1].(*leafNode)\n\n\t// Each value pointer should be unique.\n\tseen := make(map[*any]bool)\n\tfor _, vp := range leftLeaf.values {\n\t\tif seen[vp] {\n\t\t\tt.Error(\"duplicate *any pointer in left leaf\")\n\t\t}\n\t\tseen[vp] = true\n\t}\n\tfor _, vp := range rightLeaf.values {\n\t\tif seen[vp] {\n\t\t\tt.Error(\"*any pointer shared between left and right leaves after split\")\n\t\t}\n\t\tseen[vp] = true\n\t}\n}\n\n//----------------------------------------\n// Helpers\n\nfunc slicesEqual(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 intToKey(i int) string {\n\t// Zero-padded 4-digit string for correct lexicographic ordering.\n\ts := \"0000\"\n\tn := i\n\tb := []byte(s)\n\tfor j := 3; j \u003e= 0; j-- {\n\t\tb[j] = byte('0' + n%10)\n\t\tn /= 10\n\t}\n\treturn string(b)\n}\n\nfunc collectKeys(tree *BPTree, fn func(*BPTree, IterCbFn) bool) []string {\n\tvar keys []string\n\tfn(tree, func(k string, v any) bool {\n\t\tkeys = append(keys, k)\n\t\treturn false\n\t})\n\treturn keys\n}\n\nfunc assertSliceEqual(t *testing.T, got, want []string) {\n\tt.Helper()\n\tif len(got) != len(want) {\n\t\tt.Errorf(\"got %v, want %v\", got, want)\n\t\treturn\n\t}\n\tfor i := range got {\n\t\tif got[i] != want[i] {\n\t\t\tt.Errorf(\"got %v, want %v\", got, want)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc assertPanics(t *testing.T, name string, fn func()) {\n\tt.Helper()\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Errorf(\"%s: expected panic, got none\", name)\n\t\t}\n\t}()\n\tfn()\n}\n\n//----------------------------------------\n// Stress tests\n\n// TestAVLCrossValidation runs identical random operations on both avl.Tree\n// and BPTree and compares every return value.\nfunc TestAVLCrossValidation(t *testing.T) {\n\trng := rand.New(rand.NewPCG(12345, 0))\n\tat := avl.NewTree()\n\tbt := NewBPTree32()\n\n\tconst nOps = 5000\n\tconst keyRange = 200\n\n\tfor i := 0; i \u003c nOps; i++ {\n\t\tkey := intToKey(rng.IntN(keyRange))\n\t\top := rng.IntN(3)\n\t\tswitch op {\n\t\tcase 0: // Set\n\t\t\taUpd := at.Set(key, i)\n\t\t\tbUpd := bt.Set(key, i)\n\t\t\tif aUpd != bUpd {\n\t\t\t\tt.Fatalf(\"op %d: Set(%q) updated avl=%v bpt=%v\", i, key, aUpd, bUpd)\n\t\t\t}\n\t\tcase 1: // Remove\n\t\t\taVal, aOk := at.Remove(key)\n\t\t\tbVal, bOk := bt.Remove(key)\n\t\t\tif aOk != bOk {\n\t\t\t\tt.Fatalf(\"op %d: Remove(%q) avl=%v bpt=%v\", i, key, aOk, bOk)\n\t\t\t}\n\t\t\tif aOk \u0026\u0026 aVal != bVal {\n\t\t\t\tt.Fatalf(\"op %d: Remove(%q) value avl=%v bpt=%v\", i, key, aVal, bVal)\n\t\t\t}\n\t\tcase 2: // Get\n\t\t\taVal := at.Get(key)\n\t\t\taOk := at.Has(key)\n\t\t\tbVal := bt.Get(key)\n\t\t\tbOk := bt.Has(key)\n\t\t\tif aOk != bOk {\n\t\t\t\tt.Fatalf(\"op %d: exists avl=%v bpt=%v\", i, aOk, bOk)\n\t\t\t}\n\t\t\tif aOk \u0026\u0026 aVal != bVal {\n\t\t\t\tt.Fatalf(\"op %d: Get(%q) value avl=%v bpt=%v\", i, key, aVal, bVal)\n\t\t\t}\n\t\t}\n\t\tif at.Size() != bt.Size() {\n\t\t\tt.Fatalf(\"op %d: size avl=%d bpt=%d\", i, at.Size(), bt.Size())\n\t\t}\n\t}\n\n\t// Compare full iteration.\n\tvar aKeys, bKeys []string\n\tat.Iterate(\"\", \"\", func(k string, v any) bool { aKeys = append(aKeys, k); return false })\n\tbt.Iterate(\"\", \"\", func(k string, v any) bool { bKeys = append(bKeys, k); return false })\n\tassertSliceEqual(t, bKeys, aKeys)\n}\n\n// TestExhaustiveRemovalPermutations inserts N keys then tries all N!\n// permutations of removal order, verifying invariants after each remove.\nfunc TestExhaustiveRemovalPermutations(t *testing.T) {\n\tkeys := []string{\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\"}\n\tn := len(keys)\n\n\tperm := make([]int, n)\n\tfor i := range perm {\n\t\tperm[i] = i\n\t}\n\n\tcount := 0\n\tpermute(perm, 0, func(order []int) {\n\t\ttree := NewBPTreeN(4)\n\t\tfor _, k := range keys {\n\t\t\ttree.Set(k, k)\n\t\t}\n\t\tfor _, idx := range order {\n\t\t\ttree.Remove(keys[idx])\n\t\t\tverifyInvariants(t, tree)\n\t\t}\n\t\tif tree.Size() != 0 {\n\t\t\tt.Fatalf(\"perm %d: tree not empty after removing all keys\", count)\n\t\t}\n\t\tcount++\n\t})\n}\n\n// permute generates all permutations of arr[start:] and calls fn for each.\nfunc permute(arr []int, start int, fn func([]int)) {\n\tif start == len(arr) {\n\t\tfn(arr)\n\t\treturn\n\t}\n\tfor i := start; i \u003c len(arr); i++ {\n\t\tarr[start], arr[i] = arr[i], arr[start]\n\t\tpermute(arr, start+1, fn)\n\t\tarr[start], arr[i] = arr[i], arr[start]\n\t}\n}\n\n// TestMultiFanoutStress runs the same operation sequence across different\n// fanouts and verifies all produce identical results.\nfunc TestMultiFanoutStress(t *testing.T) {\n\tfanouts := []int{4, 5, 6, 7, 8, 16, 32}\n\tconst nOps = 2000\n\tconst keyRange = 100\n\n\t// Record expected results from the first fanout.\n\ttype result struct {\n\t\tsetUpdated bool\n\t\tgetVal     any\n\t\tgetOk      bool\n\t\trmVal      any\n\t\trmOk       bool\n\t}\n\n\trng0 := rand.New(rand.NewPCG(99999, 0))\n\ttype op struct {\n\t\tkind int // 0=set, 1=remove, 2=get\n\t\tkey  string\n\t\tval  int\n\t}\n\tops := make([]op, nOps)\n\tfor i := range ops {\n\t\tops[i] = op{\n\t\t\tkind: rng0.IntN(3),\n\t\t\tkey:  intToKey(rng0.IntN(keyRange)),\n\t\t\tval:  i,\n\t\t}\n\t}\n\n\t// Run on each fanout and collect final keys.\n\tvar referenceKeys []string\n\tfor fi, fanout := range fanouts {\n\t\ttree := NewBPTreeN(fanout)\n\t\tfor _, o := range ops {\n\t\t\tswitch o.kind {\n\t\t\tcase 0:\n\t\t\t\ttree.Set(o.key, o.val)\n\t\t\tcase 1:\n\t\t\t\ttree.Remove(o.key)\n\t\t\tcase 2:\n\t\t\t\ttree.Get(o.key)\n\t\t\t}\n\t\t}\n\t\tverifyInvariants(t, tree)\n\n\t\tvar keys []string\n\t\ttree.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\t\tkeys = append(keys, k)\n\t\t\treturn false\n\t\t})\n\n\t\tif fi == 0 {\n\t\t\treferenceKeys = keys\n\t\t} else {\n\t\t\tassertSliceEqual(t, keys, referenceKeys)\n\t\t}\n\t}\n}\n\n// TestSequentialInsertReverseRemove inserts keys 0..N-1 sequentially\n// (triggering 90/10 splits) then removes them in reverse order\n// (triggering cascading merges from the right).\nfunc TestSequentialInsertReverseRemove(t *testing.T) {\n\tfor _, fanout := range []int{4, 6, 8, 32} {\n\t\ttree := NewBPTreeN(fanout)\n\t\tn := 500\n\t\tfor i := 0; i \u003c n; i++ {\n\t\t\ttree.Set(intToKey(i), i)\n\t\t}\n\t\tverifyInvariants(t, tree)\n\t\tif tree.Size() != n {\n\t\t\tt.Errorf(\"fanout=%d: expected size %d, got %d\", fanout, n, tree.Size())\n\t\t}\n\n\t\tfor i := n - 1; i \u003e= 0; i-- {\n\t\t\tval, ok := tree.Remove(intToKey(i))\n\t\t\tif !ok {\n\t\t\t\tt.Fatalf(\"fanout=%d: Remove(%s) returned false\", fanout, intToKey(i))\n\t\t\t}\n\t\t\tif val != i {\n\t\t\t\tt.Fatalf(\"fanout=%d: Remove(%s) value=%v want %d\", fanout, intToKey(i), val, i)\n\t\t\t}\n\t\t\tverifyInvariants(t, tree)\n\t\t}\n\t\tif tree.Size() != 0 {\n\t\t\tt.Errorf(\"fanout=%d: expected empty tree, got size %d\", fanout, tree.Size())\n\t\t}\n\t}\n}\n\n// TestRandomOpsWithPeriodicVerification does 10K random Set/Remove calls,\n// verifying invariants and sorted iteration every 100 ops.\nfunc TestRandomOpsWithPeriodicVerification(t *testing.T) {\n\trng := rand.New(rand.NewPCG(54321, 0))\n\ttree := NewBPTreeN(4)\n\n\tconst nOps = 10000\n\tconst keyRange = 300\n\tconst checkEvery = 100\n\n\t// Track expected keys in a sorted slice for comparison.\n\tpresent := make(map[string]bool)\n\n\tfor i := 0; i \u003c nOps; i++ {\n\t\tkey := intToKey(rng.IntN(keyRange))\n\t\tif rng.IntN(3) == 0 { // ~33% removes\n\t\t\t_, ok := tree.Remove(key)\n\t\t\tif ok {\n\t\t\t\tdelete(present, key)\n\t\t\t}\n\t\t} else { // ~67% sets\n\t\t\ttree.Set(key, i)\n\t\t\tpresent[key] = true\n\t\t}\n\n\t\tif (i+1)%checkEvery == 0 {\n\t\t\tverifyInvariants(t, tree)\n\n\t\t\t// Check size.\n\t\t\tif tree.Size() != len(present) {\n\t\t\t\tt.Fatalf(\"op %d: size mismatch tree=%d map=%d\", i, tree.Size(), len(present))\n\t\t\t}\n\n\t\t\t// Check iteration matches sorted keys.\n\t\t\tvar expected []string\n\t\t\tfor k := range present {\n\t\t\t\texpected = append(expected, k)\n\t\t\t}\n\t\t\tsort.Strings(expected)\n\n\t\t\tvar got []string\n\t\t\ttree.Iterate(\"\", \"\", func(k string, v any) bool {\n\t\t\t\tgot = append(got, k)\n\t\t\t\treturn false\n\t\t\t})\n\t\t\tassertSliceEqual(t, got, expected)\n\t\t}\n\t}\n}\n\n// TestGetByIndexIterateByOffsetConsistency verifies that GetByIndex(i)\n// matches IterateByOffset(i, 1) for every valid index.\nfunc TestGetByIndexIterateByOffsetConsistency(t *testing.T) {\n\trng := rand.New(rand.NewPCG(77777, 0))\n\ttree := NewBPTreeN(4)\n\n\t// Build a tree with random insertions and removals.\n\tconst nOps = 1000\n\tconst keyRange = 200\n\tfor i := 0; i \u003c nOps; i++ {\n\t\tkey := intToKey(rng.IntN(keyRange))\n\t\tif rng.IntN(4) == 0 {\n\t\t\ttree.Remove(key)\n\t\t} else {\n\t\t\ttree.Set(key, i)\n\t\t}\n\t}\n\n\tn := tree.Size()\n\tfor i := 0; i \u003c n; i++ {\n\t\tgKey, gVal := tree.GetByIndex(i)\n\n\t\tvar iKey string\n\t\tvar iVal any\n\t\ttree.IterateByOffset(i, 1, func(k string, v any) bool {\n\t\t\tiKey = k\n\t\t\tiVal = v\n\t\t\treturn true\n\t\t})\n\n\t\tif gKey != iKey {\n\t\t\tt.Fatalf(\"index %d: GetByIndex key=%q IterateByOffset key=%q\", i, gKey, iKey)\n\t\t}\n\t\tif gVal != iVal {\n\t\t\tt.Fatalf(\"index %d: GetByIndex val=%v IterateByOffset val=%v\", i, gVal, iVal)\n\t\t}\n\t}\n\n\t// Also check ReverseIterateByOffset consistency.\n\tfor i := 0; i \u003c n; i++ {\n\t\tgKey, gVal := tree.GetByIndex(n - 1 - i)\n\n\t\tvar rKey string\n\t\tvar rVal any\n\t\ttree.ReverseIterateByOffset(i, 1, func(k string, v any) bool {\n\t\t\trKey = k\n\t\t\trVal = v\n\t\t\treturn true\n\t\t})\n\n\t\tif gKey != rKey {\n\t\t\tt.Fatalf(\"rev index %d: GetByIndex key=%q ReverseIterateByOffset key=%q\", i, gKey, rKey)\n\t\t}\n\t\tif gVal != rVal {\n\t\t\tt.Fatalf(\"rev index %d: GetByIndex val=%v ReverseIterateByOffset val=%v\", i, gVal, rVal)\n\t\t}\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"tpSMVLQq6RBWKDRvD4a/7NqehcOaraEREzy7TkQ0zCxgdYnybG0vtqouS3+62EuBpoVMaUnzf+dCWb9dDUG2cg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"boards","path":"gno.land/p/gnoland/boards","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":"board_test.gno","body":"package boards_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n\n\t\"gno.land/p/gnoland/boards\"\n)\n\nfunc TestNew(t *testing.T) {\n\tboard := boards.New(42)\n\n\turequire.Equal(t, 42, int(board.ID), \"expect board ID to match\")\n\turequire.True(t, board.Threads != nil, \"expect board to support threads\")\n\turequire.True(t, board.ThreadsSequence != nil, \"expect board to initialize a thread ID generator\")\n\turequire.False(t, board.CreatedAt.IsZero(), \"expect board to have a creation date\")\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":"flag_storage_test.gno","body":"package boards_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n\n\t\"gno.land/p/gnoland/boards\"\n)\n\nfunc TestFlagStorageExists(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\tsetup  func() boards.FlagStorage\n\t\tuser   address\n\t\texists bool\n\t}{\n\t\t{\n\t\t\tname: \"found\",\n\t\t\tsetup: func() boards.FlagStorage {\n\t\t\t\ts := boards.NewFlagStorage()\n\t\t\t\ts.Add(boards.Flag{User: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tuser:   \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\texists: true,\n\t\t},\n\t\t{\n\t\t\tname: \"not found\",\n\t\t\tsetup: func() boards.FlagStorage {\n\t\t\t\treturn boards.NewFlagStorage()\n\t\t\t},\n\t\t\tuser:   \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\texists: 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\ts := tt.setup()\n\n\t\t\turequire.Equal(t, tt.exists, s.Exists(tt.user))\n\t\t})\n\t}\n}\n\nfunc TestFlagStorageAdd(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\tsetup  func() boards.FlagStorage\n\t\tflag   boards.Flag\n\t\terrMsg string\n\t}{\n\t\t{\n\t\t\tname: \"ok\",\n\t\t\tsetup: func() boards.FlagStorage {\n\t\t\t\treturn boards.NewFlagStorage()\n\t\t\t},\n\t\t\tflag: boards.Flag{User: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"},\n\t\t},\n\t\t{\n\t\t\tname: \"flag exists\",\n\t\t\tsetup: func() boards.FlagStorage {\n\t\t\t\ts := boards.NewFlagStorage()\n\t\t\t\ts.Add(boards.Flag{User: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tflag:   boards.Flag{User: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"},\n\t\t\terrMsg: \"flag from user already exists: g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid user address\",\n\t\t\tsetup: func() boards.FlagStorage {\n\t\t\t\treturn boards.NewFlagStorage()\n\t\t\t},\n\t\t\tflag:   boards.Flag{User: \"foo\"},\n\t\t\terrMsg: \"post flagging error, invalid user address: foo\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ts := tt.setup()\n\n\t\t\terr := s.Add(tt.flag)\n\n\t\t\tif tt.errMsg != \"\" {\n\t\t\t\turequire.Error(t, err, \"expect an error\")\n\t\t\t\turequire.ErrorContains(t, err, tt.errMsg, \"expect error to match\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.NoError(t, err, \"expect no error\")\n\t\t\turequire.True(t, s.Exists(tt.flag.User), \"expect flag to be added\")\n\t\t})\n\t}\n}\n\nfunc TestFlagStorageRemove(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tsetup   func() boards.FlagStorage\n\t\taddress address\n\t\tremoved bool\n\t}{\n\t\t{\n\t\t\tname: \"ok\",\n\t\t\tsetup: func() boards.FlagStorage {\n\t\t\t\ts := boards.NewFlagStorage()\n\t\t\t\ts.Add(boards.Flag{User: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\taddress: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\tremoved: true,\n\t\t},\n\t\t{\n\t\t\tname: \"not found\",\n\t\t\tsetup: func() boards.FlagStorage {\n\t\t\t\treturn boards.NewFlagStorage()\n\t\t\t},\n\t\t\taddress: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ts := tt.setup()\n\n\t\t\turequire.Equal(t, tt.removed, s.Remove(tt.address))\n\t\t})\n\t}\n}\n\nfunc TestFlagStorageSize(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tsetup func() boards.FlagStorage\n\t\tsize  int\n\t}{\n\t\t{\n\t\t\tname: \"empty\",\n\t\t\tsetup: func() boards.FlagStorage {\n\t\t\t\treturn boards.NewFlagStorage()\n\t\t\t},\n\t\t\tsize: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"one flag\",\n\t\t\tsetup: func() boards.FlagStorage {\n\t\t\t\ts := boards.NewFlagStorage()\n\t\t\t\ts.Add(boards.Flag{User: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tsize: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"multiple flags\",\n\t\t\tsetup: func() boards.FlagStorage {\n\t\t\t\ts := boards.NewFlagStorage()\n\t\t\t\ts.Add(boards.Flag{User: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"})\n\t\t\t\ts.Add(boards.Flag{User: \"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\"})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tsize: 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\ts := tt.setup()\n\n\t\t\turequire.Equal(t, tt.size, s.Size())\n\t\t})\n\t}\n}\n\nfunc TestFlagStorageIterate(t *testing.T) {\n\tflags := []boards.Flag{\n\t\t{\n\t\t\tUser:   \"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\",\n\t\t\tReason: \"a\",\n\t\t},\n\t\t{\n\t\t\tUser:   \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\tReason: \"b\",\n\t\t},\n\t}\n\ttests := []struct {\n\t\tname    string\n\t\tsetup   func() boards.FlagStorage\n\t\treverse bool\n\t\tflags   []boards.Flag\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\tsetup: func() boards.FlagStorage {\n\t\t\t\ts := boards.NewFlagStorage()\n\t\t\t\ts.Add(flags[0])\n\t\t\t\ts.Add(flags[1])\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tflags: flags,\n\t\t},\n\t\t{\n\t\t\tname: \"reverse\",\n\t\t\tsetup: func() boards.FlagStorage {\n\t\t\t\ts := boards.NewFlagStorage()\n\t\t\t\ts.Add(flags[0])\n\t\t\t\ts.Add(flags[1])\n\t\t\t\treturn s\n\t\t\t},\n\t\t\treverse: true,\n\t\t\tflags:   []boards.Flag{flags[1], flags[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\ts := tt.setup()\n\t\t\tcount := s.Size()\n\t\t\tif tt.reverse {\n\t\t\t\tcount = -count\n\t\t\t}\n\n\t\t\tvar i int\n\t\t\ts.Iterate(0, count, func(f boards.Flag) bool {\n\t\t\t\turequire.Equal(t, tt.flags[i].User, f.User, \"expect user to match\")\n\t\t\t\turequire.Equal(t, tt.flags[i].Reason, f.Reason, \"expect reason to match\")\n\n\t\t\t\ti++\n\t\t\t\treturn false\n\t\t\t})\n\t\t})\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/gnoland/boards\"\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":"id_test.gno","body":"package boards_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n\n\t\"gno.land/p/gnoland/boards\"\n)\n\nfunc TestID(t *testing.T) {\n\tid := boards.ID(42)\n\n\turequire.Equal(t, \"42\", id.String(), \"expect string to match\")\n\turequire.Equal(t, \"0000000042\", id.PaddedString(), \"expect padded string to match\")\n\turequire.Equal(t, \"000001a\", id.Key(), \"expect key to match\")\n}\n\nfunc TestIdentifierGenerator(t *testing.T) {\n\tg := boards.NewIdentifierGenerator()\n\n\turequire.Equal(t, uint64(0), uint64(g.Last()), \"expect default to be 0\")\n\turequire.Equal(t, uint64(1), uint64(g.Next()), \"expect next to be 1\")\n\turequire.Equal(t, uint64(1), uint64(g.Last()), \"expect last to be 1\")\n\turequire.Equal(t, uint64(2), uint64(g.Next()), \"expect next to be 2\")\n\turequire.Equal(t, uint64(2), uint64(g.Last()), \"expect last to be 2\")\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":"permission_set_test.gno","body":"package boards\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestNewPermissionSet(t *testing.T) {\n\tcases := []struct {\n\t\tname  string\n\t\tperms []Permission\n\t\tcheck []Permission\n\t\twant  bool\n\t}{\n\t\t{\n\t\t\tname:  \"empty\",\n\t\t\tcheck: []Permission{0},\n\t\t\twant:  false,\n\t\t},\n\t\t{\n\t\t\tname:  \"single permission\",\n\t\t\tperms: []Permission{0},\n\t\t\tcheck: []Permission{0},\n\t\t\twant:  true,\n\t\t},\n\t\t{\n\t\t\tname:  \"multiple permissions\",\n\t\t\tperms: []Permission{1, 3, 5},\n\t\t\tcheck: []Permission{1, 3, 5},\n\t\t\twant:  true,\n\t\t},\n\t\t{\n\t\t\tname:  \"high permission value\",\n\t\t\tperms: []Permission{100},\n\t\t\tcheck: []Permission{100},\n\t\t\twant:  true,\n\t\t},\n\t\t{\n\t\t\tname:  \"missing permission\",\n\t\t\tperms: []Permission{100},\n\t\t\tcheck: []Permission{0},\n\t\t\twant:  false,\n\t\t},\n\t\t{\n\t\t\tname:  \"multiple missing permissions\",\n\t\t\tperms: []Permission{1, 3, 5},\n\t\t\tcheck: []Permission{0, 2, 4},\n\t\t\twant:  false,\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\ts := NewPermissionSet(tc.perms...)\n\n\t\t\tfor _, p := range tc.check {\n\t\t\t\tuassert.Equal(t, tc.want, s.Has(p))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestPermissionSetHas(t *testing.T) {\n\tcases := []struct {\n\t\tname  string\n\t\tset   PermissionSet\n\t\tcheck Permission\n\t\twant  bool\n\t}{\n\t\t{\n\t\t\tname:  \"out of range\",\n\t\t\tset:   NewPermissionSet(0),\n\t\t\tcheck: 100,\n\t\t\twant:  false,\n\t\t},\n\t\t{\n\t\t\tname:  \"nil set\",\n\t\t\tcheck: 0,\n\t\t\twant:  false,\n\t\t},\n\t\t{\n\t\t\tname:  \"permission present\",\n\t\t\tset:   NewPermissionSet(5),\n\t\t\tcheck: 5,\n\t\t\twant:  true,\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, tc.want, tc.set.Has(tc.check))\n\t\t})\n\t}\n}\n\nfunc TestPermissionSetIsEmpty(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tset  PermissionSet\n\t\twant bool\n\t}{\n\t\t{\n\t\t\tname: \"nil set\",\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"non-empty set\",\n\t\t\tset:  NewPermissionSet(0),\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"empty allocated set\",\n\t\t\tset:  make(PermissionSet, 1),\n\t\t\twant: true,\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tuassert.Equal(t, tc.want, tc.set.IsEmpty())\n\t\t})\n\t}\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":"post_storage_test.gno","body":"package boards_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n\n\t\"gno.land/p/gnoland/boards\"\n)\n\nfunc TestPostStorageGet(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\tsetup  func() boards.PostStorage\n\t\tpostID boards.ID\n\t\tfound  bool\n\t}{\n\t\t{\n\t\t\tname: \"single post\",\n\t\t\tsetup: func() boards.PostStorage {\n\t\t\t\ts := boards.NewPostStorage()\n\t\t\t\ts.Add(\u0026boards.Post{ID: 1})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tpostID: 1,\n\t\t\tfound:  true,\n\t\t},\n\t\t{\n\t\t\tname: \"multiple posts\",\n\t\t\tsetup: func() boards.PostStorage {\n\t\t\t\ts := boards.NewPostStorage()\n\t\t\t\ts.Add(\u0026boards.Post{ID: 1})\n\t\t\t\ts.Add(\u0026boards.Post{ID: 2})\n\t\t\t\ts.Add(\u0026boards.Post{ID: 3})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tpostID: 2,\n\t\t\tfound:  true,\n\t\t},\n\t\t{\n\t\t\tname: \"not found\",\n\t\t\tsetup: func() boards.PostStorage {\n\t\t\t\treturn boards.NewPostStorage()\n\t\t\t},\n\t\t\tpostID: 404,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ts := tt.setup()\n\n\t\t\tpost, found := s.Get(tt.postID)\n\n\t\t\tif !tt.found {\n\t\t\t\turequire.False(t, found, \"expect post not to be found\")\n\t\t\t\turequire.True(t, post == nil, \"expect post to be nil\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.True(t, found, \"expect post to be found\")\n\t\t\turequire.False(t, post == nil, \"expect post not to be nil\")\n\t\t\turequire.Equal(t, tt.postID.String(), post.ID.String(), \"expect post ID to match\")\n\t\t})\n\t}\n}\n\nfunc TestPostStorageRemove(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tsetup   func() boards.PostStorage\n\t\tpostID  boards.ID\n\t\tremoved bool\n\t}{\n\t\t{\n\t\t\tname: \"ok\",\n\t\t\tsetup: func() boards.PostStorage {\n\t\t\t\ts := boards.NewPostStorage()\n\t\t\t\ts.Add(\u0026boards.Post{ID: 1})\n\t\t\t\ts.Add(\u0026boards.Post{ID: 2})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tpostID:  2,\n\t\t\tremoved: true,\n\t\t},\n\t\t{\n\t\t\tname: \"not found\",\n\t\t\tsetup: func() boards.PostStorage {\n\t\t\t\treturn boards.NewPostStorage()\n\t\t\t},\n\t\t\tpostID: 404,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ts := tt.setup()\n\n\t\t\tpost, removed := s.Remove(tt.postID)\n\n\t\t\tif !tt.removed {\n\t\t\t\turequire.False(t, removed, \"expect post not to be removed\")\n\t\t\t\turequire.True(t, post == nil, \"expect post to be nil\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.True(t, removed, \"expect post to be removed\")\n\t\t\turequire.False(t, post == nil, \"expect post not to be nil\")\n\t\t\turequire.Equal(t, tt.postID.String(), post.ID.String(), \"expect post ID to match\")\n\n\t\t\t_, found := s.Get(tt.postID)\n\t\t\turequire.False(t, found, \"expect post not to be found\")\n\t\t})\n\t}\n}\n\nfunc TestPostStorageAdd(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\tpost   *boards.Post\n\t\terrMsg string\n\t}{\n\t\t{\n\t\t\tname: \"ok\",\n\t\t\tpost: \u0026boards.Post{ID: 1},\n\t\t},\n\t\t{\n\t\t\tname:   \"nil post\",\n\t\t\tpost:   nil,\n\t\t\terrMsg: \"saving nil posts is not allowed\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ts := boards.NewPostStorage()\n\n\t\t\terr := s.Add(tt.post)\n\n\t\t\tif tt.errMsg != \"\" {\n\t\t\t\turequire.Error(t, err, \"expect an error\")\n\t\t\t\turequire.ErrorContains(t, err, tt.errMsg, \"expect error to match\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.NoError(t, err, \"expect no error\")\n\n\t\t\t_, found := s.Get(tt.post.ID)\n\t\t\turequire.True(t, found, \"expect post to be found\")\n\t\t})\n\t}\n}\n\nfunc TestPostStorageSize(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tsetup func() boards.PostStorage\n\t\tsize  int\n\t}{\n\t\t{\n\t\t\tname: \"empty\",\n\t\t\tsetup: func() boards.PostStorage {\n\t\t\t\treturn boards.NewPostStorage()\n\t\t\t},\n\t\t\tsize: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"one post\",\n\t\t\tsetup: func() boards.PostStorage {\n\t\t\t\ts := boards.NewPostStorage()\n\t\t\t\ts.Add(\u0026boards.Post{ID: 1})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tsize: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"multiple posts\",\n\t\t\tsetup: func() boards.PostStorage {\n\t\t\t\ts := boards.NewPostStorage()\n\t\t\t\ts.Add(\u0026boards.Post{ID: 1})\n\t\t\t\ts.Add(\u0026boards.Post{ID: 2})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tsize: 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\ts := tt.setup()\n\n\t\t\turequire.Equal(t, tt.size, s.Size())\n\t\t})\n\t}\n}\n\nfunc TestPostStorageIterate(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tsetup   func() boards.PostStorage\n\t\treverse bool\n\t\tids     []boards.ID\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\tsetup: func() boards.PostStorage {\n\t\t\t\ts := boards.NewPostStorage()\n\t\t\t\ts.Add(\u0026boards.Post{ID: 1})\n\t\t\t\ts.Add(\u0026boards.Post{ID: 2})\n\t\t\t\ts.Add(\u0026boards.Post{ID: 3})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tids: []boards.ID{1, 2, 3},\n\t\t},\n\t\t{\n\t\t\tname: \"reverse\",\n\t\t\tsetup: func() boards.PostStorage {\n\t\t\t\ts := boards.NewPostStorage()\n\t\t\t\ts.Add(\u0026boards.Post{ID: 1})\n\t\t\t\ts.Add(\u0026boards.Post{ID: 2})\n\t\t\t\ts.Add(\u0026boards.Post{ID: 3})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\treverse: true,\n\t\t\tids:     []boards.ID{3, 2, 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\ts := tt.setup()\n\t\t\tcount := s.Size()\n\t\t\tif tt.reverse {\n\t\t\t\tcount = -count\n\t\t\t}\n\n\t\t\tvar i int\n\t\t\ts.Iterate(0, count, func(p *boards.Post) bool {\n\t\t\t\turequire.True(t, tt.ids[i] == p.ID, \"expect post ID to match\")\n\n\t\t\t\ti++\n\t\t\t\treturn false\n\t\t\t})\n\t\t})\n\t}\n}\n"},{"name":"post_test.gno","body":"package boards_test\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n\n\t\"gno.land/p/gnoland/boards\"\n)\n\nfunc TestPostSummary(t *testing.T) {\n\tpost := \u0026boards.Post{ID: 1, Body: strings.Repeat(\"X\", 900)}\n\tsummary := post.Summary()\n\turequire.True(t, strings.HasSuffix(summary, \"...\"), \"expect dotted suffix\")\n\turequire.True(t, len(summary) == 80, \"expect summary length to match\")\n}\n\nfunc TestIsThread(t *testing.T) {\n\tpost := \u0026boards.Post{ID: 1, ThreadID: 1} // IDs match\n\turequire.True(t, boards.IsThread(post), \"expect post to be a thread\")\n\turequire.False(t, boards.IsThread(nil), \"expect nil not to be a thread\")\n\n\tpost = \u0026boards.Post{ID: 2, ThreadID: 1} // IDs doesn't match\n\turequire.False(t, boards.IsThread(post), \"expect post not to be a thread\")\n}\n\nfunc TestIsRepost(t *testing.T) {\n\tpost := \u0026boards.Post{ID: 1, OriginalBoardID: 1} // Original board ID available\n\turequire.True(t, boards.IsRepost(post), \"expect post to be a repost\")\n\turequire.False(t, boards.IsRepost(nil), \"expect nil not to be a repost\")\n\n\tpost = \u0026boards.Post{ID: 1} // Original board ID not available\n\turequire.False(t, boards.IsRepost(post), \"expect post not to be a repost\")\n}\n\nfunc TestSummaryOf(t *testing.T) {\n\tsummary := boards.SummaryOf(strings.Repeat(\"X\", 90), 80)\n\turequire.True(t, strings.HasSuffix(summary, \"...\"), \"expect dotted suffix\")\n\turequire.True(t, len(summary) == 80, \"expect summary length to match\")\n\n\tsummary = boards.SummaryOf(strings.Repeat(\" \", 90), 80)\n\turequire.Empty(t, summary, \"expect summary to be empty\")\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":"reply_test.gno","body":"package boards_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n\n\t\"gno.land/p/gnoland/boards\"\n)\n\nfunc TestNewReply(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tparent  func() *boards.Post\n\t\tcreator address\n\t\tbody    string\n\t\terrMsg  string\n\t}{\n\t\t{\n\t\t\tname: \"ok\",\n\t\t\tparent: func() *boards.Post {\n\t\t\t\tboard := boards.New(1)\n\t\t\t\tid := board.ThreadsSequence.Next()\n\t\t\t\treturn \u0026boards.Post{\n\t\t\t\t\tID:       id,\n\t\t\t\t\tThreadID: id,\n\t\t\t\t\tBoard:    board,\n\t\t\t\t}\n\t\t\t},\n\t\t\tcreator: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\tbody:    \"Foo\",\n\t\t},\n\t\t{\n\t\t\tname:   \"nil parent\",\n\t\t\tparent: func() *boards.Post { return nil },\n\t\t\terrMsg: \"reply requires a parent thread or reply\",\n\t\t},\n\t\t{\n\t\t\tname: \"parent without thread ID\",\n\t\t\tparent: func() *boards.Post {\n\t\t\t\treturn \u0026boards.Post{ID: 1}\n\t\t\t},\n\t\t\terrMsg: \"parent has no thread ID assigned\",\n\t\t},\n\t\t{\n\t\t\tname: \"parent without board\",\n\t\t\tparent: func() *boards.Post {\n\t\t\t\treturn \u0026boards.Post{ID: 1, ThreadID: 1}\n\t\t\t},\n\t\t\terrMsg: \"parent has no board assigned\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid creator\",\n\t\t\tparent: func() *boards.Post {\n\t\t\t\treturn \u0026boards.Post{ID: 1, ThreadID: 1, Board: boards.New(1)}\n\t\t\t},\n\t\t\tcreator: \"foo\",\n\t\t\terrMsg:  \"invalid reply creator address: foo\",\n\t\t},\n\t\t{\n\t\t\tname: \"empty body\",\n\t\t\tparent: func() *boards.Post {\n\t\t\t\treturn \u0026boards.Post{ID: 1, ThreadID: 1, Board: boards.New(1)}\n\t\t\t},\n\t\t\tcreator: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\tbody:    \"\",\n\t\t\terrMsg:  \"reply body is required\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tparent := tt.parent()\n\n\t\t\treply, err := boards.NewReply(parent, tt.creator, tt.body)\n\n\t\t\tif tt.errMsg != \"\" {\n\t\t\t\turequire.Error(t, err, \"expect an error\")\n\t\t\t\turequire.ErrorContains(t, err, tt.errMsg, \"expect error to match\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.NoError(t, err, \"expect no error\")\n\t\t\turequire.True(t, parent.Board.ThreadsSequence.Last() == reply.ID, \"expect ID to match\")\n\t\t\turequire.True(t, parent.ID == reply.ParentID, \"expect parent ID to match\")\n\t\t\turequire.True(t, parent.ThreadID == reply.ThreadID, \"expect thread ID to match\")\n\t\t\turequire.False(t, reply.Board == nil, \"expect board to be assigned\")\n\t\t\turequire.True(t, parent.Board.ID == reply.Board.ID, \"expect board ID to match\")\n\t\t\turequire.Equal(t, tt.body, reply.Body, \"expect body to match\")\n\t\t\turequire.True(t, reply.Replies != nil, \"expect reply to support sub-replies\")\n\t\t\turequire.True(t, reply.Flags != nil, \"expect reply to support flagging\")\n\t\t\turequire.Equal(t, tt.creator, reply.Creator, \"expect creator to match\")\n\t\t\turequire.False(t, reply.CreatedAt.IsZero(), \"expect creation date to be assigned\")\n\t\t})\n\t}\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":"repost_storage_test.gno","body":"package boards_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n\n\t\"gno.land/p/gnoland/boards\"\n)\n\nfunc TestRepostStorageGet(t *testing.T) {\n\ttests := []struct {\n\t\tname              string\n\t\tsetup             func() boards.RepostStorage\n\t\tboardID, repostID boards.ID\n\t\tfound             bool\n\t}{\n\t\t{\n\t\t\tname: \"single repost\",\n\t\t\tsetup: func() boards.RepostStorage {\n\t\t\t\ts := boards.NewRepostStorage()\n\t\t\t\ts.Add(\u0026boards.Post{\n\t\t\t\t\tID:    1,\n\t\t\t\t\tBoard: \u0026boards.Board{ID: 1},\n\t\t\t\t})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tboardID:  1,\n\t\t\trepostID: 1,\n\t\t\tfound:    true,\n\t\t},\n\t\t{\n\t\t\tname: \"multiple reposts\",\n\t\t\tsetup: func() boards.RepostStorage {\n\t\t\t\ts := boards.NewRepostStorage()\n\t\t\t\ts.Add(\u0026boards.Post{\n\t\t\t\t\tID:    2,\n\t\t\t\t\tBoard: \u0026boards.Board{ID: 1},\n\t\t\t\t})\n\t\t\t\ts.Add(\u0026boards.Post{\n\t\t\t\t\tID:    5,\n\t\t\t\t\tBoard: \u0026boards.Board{ID: 2},\n\t\t\t\t})\n\t\t\t\ts.Add(\u0026boards.Post{\n\t\t\t\t\tID:    10,\n\t\t\t\t\tBoard: \u0026boards.Board{ID: 3},\n\t\t\t\t})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tboardID:  1,\n\t\t\trepostID: 2,\n\t\t\tfound:    true,\n\t\t},\n\t\t{\n\t\t\tname: \"not found\",\n\t\t\tsetup: func() boards.RepostStorage {\n\t\t\t\treturn boards.NewRepostStorage()\n\t\t\t},\n\t\t\tboardID: 404,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ts := tt.setup()\n\n\t\t\trepostID, found := s.Get(tt.boardID)\n\n\t\t\tif !tt.found {\n\t\t\t\turequire.False(t, found, \"expect repost not to be found\")\n\t\t\t\turequire.True(t, int(repostID) == 0, \"expect repost ID to be 0\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.True(t, found, \"expect post to be found\")\n\t\t\turequire.Equal(t, tt.repostID.String(), repostID.String(), \"expect repost ID to match\")\n\t\t})\n\t}\n}\n\nfunc TestRepostStorageAdd(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\trepost *boards.Post\n\t\terrMsg string\n\t}{\n\t\t{\n\t\t\tname: \"ok\",\n\t\t\trepost: \u0026boards.Post{\n\t\t\t\tID:    1,\n\t\t\t\tBoard: \u0026boards.Board{ID: 1},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:   \"nil repost\",\n\t\t\trepost: nil,\n\t\t\terrMsg: \"saving nil reposts is not allowed\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ts := boards.NewRepostStorage()\n\n\t\t\terr := s.Add(tt.repost)\n\n\t\t\tif tt.errMsg != \"\" {\n\t\t\t\turequire.Error(t, err, \"expect an error\")\n\t\t\t\turequire.ErrorContains(t, err, tt.errMsg, \"expect error to match\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.NoError(t, err, \"expect no error\")\n\n\t\t\t_, found := s.Get(tt.repost.ID)\n\t\t\turequire.True(t, found, \"expect repost to be found\")\n\t\t})\n\t}\n}\n\nfunc TestRepostStorageRemove(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tsetup   func() boards.RepostStorage\n\t\tboardID boards.ID\n\t\tremoved bool\n\t}{\n\t\t{\n\t\t\tname: \"ok\",\n\t\t\tsetup: func() boards.RepostStorage {\n\t\t\t\ts := boards.NewRepostStorage()\n\t\t\t\ts.Add(\u0026boards.Post{\n\t\t\t\t\tID:    100,\n\t\t\t\t\tBoard: \u0026boards.Board{ID: 1},\n\t\t\t\t})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tboardID: 1,\n\t\t\tremoved: true,\n\t\t},\n\t\t{\n\t\t\tname: \"not found\",\n\t\t\tsetup: func() boards.RepostStorage {\n\t\t\t\treturn boards.NewRepostStorage()\n\t\t\t},\n\t\t\tboardID: 404,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ts := tt.setup()\n\n\t\t\tremoved := s.Remove(tt.boardID)\n\n\t\t\tif !tt.removed {\n\t\t\t\turequire.False(t, removed, \"expect repost not to be removed\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.True(t, removed, \"expect repost to be removed\")\n\n\t\t\t_, found := s.Get(tt.boardID)\n\t\t\turequire.False(t, found, \"expect repost not to be found\")\n\t\t})\n\t}\n}\n\nfunc TestRepostStorageSize(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tsetup func() boards.RepostStorage\n\t\tsize  int\n\t}{\n\t\t{\n\t\t\tname: \"empty\",\n\t\t\tsetup: func() boards.RepostStorage {\n\t\t\t\treturn boards.NewRepostStorage()\n\t\t\t},\n\t\t\tsize: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"one repost\",\n\t\t\tsetup: func() boards.RepostStorage {\n\t\t\t\ts := boards.NewRepostStorage()\n\t\t\t\ts.Add(\u0026boards.Post{\n\t\t\t\t\tID:    1,\n\t\t\t\t\tBoard: \u0026boards.Board{ID: 1},\n\t\t\t\t})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tsize: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"multiple reposts\",\n\t\t\tsetup: func() boards.RepostStorage {\n\t\t\t\ts := boards.NewRepostStorage()\n\t\t\t\ts.Add(\u0026boards.Post{\n\t\t\t\t\tID:    1,\n\t\t\t\t\tBoard: \u0026boards.Board{ID: 1},\n\t\t\t\t})\n\t\t\t\ts.Add(\u0026boards.Post{\n\t\t\t\t\tID:    1,\n\t\t\t\t\tBoard: \u0026boards.Board{ID: 2},\n\t\t\t\t})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tsize: 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\ts := tt.setup()\n\n\t\t\turequire.Equal(t, tt.size, s.Size())\n\t\t})\n\t}\n}\n\nfunc TestRepostStorageIterate(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tsetup   func() boards.RepostStorage\n\t\treverse bool\n\t\tids     [][2]boards.ID\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\tsetup: func() boards.RepostStorage {\n\t\t\t\ts := boards.NewRepostStorage()\n\t\t\t\ts.Add(\u0026boards.Post{\n\t\t\t\t\tID:    10,\n\t\t\t\t\tBoard: \u0026boards.Board{ID: 1},\n\t\t\t\t})\n\t\t\t\ts.Add(\u0026boards.Post{\n\t\t\t\t\tID:    20,\n\t\t\t\t\tBoard: \u0026boards.Board{ID: 2},\n\t\t\t\t})\n\t\t\t\ts.Add(\u0026boards.Post{\n\t\t\t\t\tID:    30,\n\t\t\t\t\tBoard: \u0026boards.Board{ID: 3},\n\t\t\t\t})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tids: [][2]boards.ID{\n\t\t\t\t{1, 10},\n\t\t\t\t{2, 20},\n\t\t\t\t{3, 30},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"reverse\",\n\t\t\tsetup: func() boards.RepostStorage {\n\t\t\t\ts := boards.NewRepostStorage()\n\t\t\t\ts.Add(\u0026boards.Post{\n\t\t\t\t\tID:    10,\n\t\t\t\t\tBoard: \u0026boards.Board{ID: 1},\n\t\t\t\t})\n\t\t\t\ts.Add(\u0026boards.Post{\n\t\t\t\t\tID:    20,\n\t\t\t\t\tBoard: \u0026boards.Board{ID: 2},\n\t\t\t\t})\n\t\t\t\ts.Add(\u0026boards.Post{\n\t\t\t\t\tID:    30,\n\t\t\t\t\tBoard: \u0026boards.Board{ID: 3},\n\t\t\t\t})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\treverse: true,\n\t\t\tids: [][2]boards.ID{\n\t\t\t\t{3, 30},\n\t\t\t\t{2, 20},\n\t\t\t\t{1, 10},\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\ts := tt.setup()\n\t\t\tcount := s.Size()\n\t\t\tif tt.reverse {\n\t\t\t\tcount = -count\n\t\t\t}\n\n\t\t\tvar i int\n\t\t\ts.Iterate(0, count, func(boardID, repostID boards.ID) bool {\n\t\t\t\turequire.True(t, tt.ids[i][0] == boardID, \"expect board ID to match\")\n\t\t\t\turequire.True(t, tt.ids[i][1] == repostID, \"expect repost ID to match\")\n\n\t\t\t\ti++\n\t\t\t\treturn false\n\t\t\t})\n\t\t})\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":"storage_test.gno","body":"package boards_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n\n\t\"gno.land/p/gnoland/boards\"\n)\n\nfunc TestStorageGet(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tsetup   func() boards.Storage\n\t\tboardID boards.ID\n\t\tfound   bool\n\t}{\n\t\t{\n\t\t\tname: \"single board\",\n\t\t\tsetup: func() boards.Storage {\n\t\t\t\ts := boards.NewStorage()\n\t\t\t\ts.Add(\u0026boards.Board{ID: 1})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tboardID: 1,\n\t\t\tfound:   true,\n\t\t},\n\t\t{\n\t\t\tname: \"multiple boards\",\n\t\t\tsetup: func() boards.Storage {\n\t\t\t\ts := boards.NewStorage()\n\t\t\t\ts.Add(\u0026boards.Board{ID: 1})\n\t\t\t\ts.Add(\u0026boards.Board{ID: 2})\n\t\t\t\ts.Add(\u0026boards.Board{ID: 3})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tboardID: 2,\n\t\t\tfound:   true,\n\t\t},\n\t\t{\n\t\t\tname: \"not found\",\n\t\t\tsetup: func() boards.Storage {\n\t\t\t\treturn boards.NewStorage()\n\t\t\t},\n\t\t\tboardID: 404,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ts := tt.setup()\n\n\t\t\tboard, found := s.Get(tt.boardID)\n\n\t\t\tif !tt.found {\n\t\t\t\turequire.False(t, found, \"expect board not to be found\")\n\t\t\t\turequire.True(t, board == nil, \"expect board to be nil\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.True(t, found, \"expect board to be found\")\n\t\t\turequire.False(t, board == nil, \"expect board not to be nil\")\n\t\t\turequire.Equal(t, tt.boardID.String(), board.ID.String(), \"expect board ID to match\")\n\t\t})\n\t}\n}\n\nfunc TestStorageGetByName(t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tsetup     func() boards.Storage\n\t\tboardName string\n\t\tfound     bool\n\t}{\n\t\t{\n\t\t\tname: \"single board\",\n\t\t\tsetup: func() boards.Storage {\n\t\t\t\ts := boards.NewStorage()\n\t\t\t\ts.Add(\u0026boards.Board{ID: 1, Name: \"A\"})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tboardName: \"A\",\n\t\t\tfound:     true,\n\t\t},\n\t\t{\n\t\t\tname: \"multiple boards\",\n\t\t\tsetup: func() boards.Storage {\n\t\t\t\ts := boards.NewStorage()\n\t\t\t\ts.Add(\u0026boards.Board{ID: 1, Name: \"A\"})\n\t\t\t\ts.Add(\u0026boards.Board{ID: 2, Name: \"B\"})\n\t\t\t\ts.Add(\u0026boards.Board{ID: 3, Name: \"C\"})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tboardName: \"B\",\n\t\t\tfound:     true,\n\t\t},\n\t\t{\n\t\t\tname: \"not found\",\n\t\t\tsetup: func() boards.Storage {\n\t\t\t\treturn boards.NewStorage()\n\t\t\t},\n\t\t\tboardName: \"foo\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ts := tt.setup()\n\n\t\t\tboard, found := s.GetByName(tt.boardName)\n\n\t\t\tif !tt.found {\n\t\t\t\turequire.False(t, found, \"expect board not to be found\")\n\t\t\t\turequire.True(t, board == nil, \"expect board to be nil\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.True(t, found, \"expect board to be found\")\n\t\t\turequire.False(t, board == nil, \"expect board not to be nil\")\n\t\t\turequire.Equal(t, tt.boardName, board.Name, \"expect board name to match\")\n\t\t})\n\t}\n}\n\nfunc TestStorageRemove(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\tsetup      func() boards.Storage\n\t\tboardID    boards.ID\n\t\tboardNames []string\n\t\tremoved    bool\n\t}{\n\t\t{\n\t\t\tname: \"ok\",\n\t\t\tsetup: func() boards.Storage {\n\t\t\t\ts := boards.NewStorage()\n\t\t\t\ts.Add(\u0026boards.Board{ID: 1, Name: \"A\"})\n\t\t\t\ts.Add(\u0026boards.Board{ID: 2, Name: \"B\"})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tboardID:    2,\n\t\t\tboardNames: []string{\"B\"},\n\t\t\tremoved:    true,\n\t\t},\n\t\t{\n\t\t\tname: \"ok with aliases\",\n\t\t\tsetup: func() boards.Storage {\n\t\t\t\ts := boards.NewStorage()\n\t\t\t\ts.Add(\u0026boards.Board{ID: 1, Name: \"A\"})\n\n\t\t\t\tb := \u0026boards.Board{ID: 2, Name: \"B\"}\n\t\t\t\ts.Add(b)\n\n\t\t\t\tb.Aliases = []string{\"A\"}\n\t\t\t\tb.Name = \"C\"\n\t\t\t\ts.Add(b)\n\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tboardID:    2,\n\t\t\tboardNames: []string{\"B\", \"C\"},\n\t\t\tremoved:    true,\n\t\t},\n\t\t{\n\t\t\tname: \"not found\",\n\t\t\tsetup: func() boards.Storage {\n\t\t\t\treturn boards.NewStorage()\n\t\t\t},\n\t\t\tboardID: 404,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ts := tt.setup()\n\n\t\t\tboard, removed := s.Remove(tt.boardID)\n\n\t\t\tif !tt.removed {\n\t\t\t\turequire.False(t, removed, \"expect board not to be removed\")\n\t\t\t\turequire.True(t, board == nil, \"expect board to be nil\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.True(t, removed, \"expect board to be removed\")\n\t\t\turequire.False(t, board == nil, \"expect board not to be nil\")\n\t\t\turequire.Equal(t, tt.boardID.String(), board.ID.String(), \"expect board ID to match\")\n\n\t\t\t_, found := s.Get(tt.boardID)\n\t\t\turequire.False(t, found, \"expect board not to be found by ID\")\n\n\t\t\tfor _, name := range tt.boardNames {\n\t\t\t\t_, found = s.GetByName(name)\n\t\t\t\turequire.False(t, found, \"expect board not to be found by name: \"+name)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestStorageAdd(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\tsetup  func() boards.Storage\n\t\tboard  *boards.Board\n\t\terrMsg string\n\t}{\n\t\t{\n\t\t\tname:  \"ok\",\n\t\t\tboard: \u0026boards.Board{ID: 1, Name: \"A\"},\n\t\t},\n\t\t{\n\t\t\tname:   \"nil board\",\n\t\t\tboard:  nil,\n\t\t\terrMsg: \"adding nil boards to the storage is not allowed\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ts := boards.NewStorage()\n\n\t\t\terr := s.Add(tt.board)\n\n\t\t\tif tt.errMsg != \"\" {\n\t\t\t\turequire.Error(t, err, \"expect an error\")\n\t\t\t\turequire.ErrorContains(t, err, tt.errMsg, \"expect error to match\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.NoError(t, err, \"expect no error\")\n\n\t\t\t_, found := s.Get(tt.board.ID)\n\t\t\turequire.True(t, found, \"expect board to be found by ID\")\n\n\t\t\t_, found = s.GetByName(tt.board.Name)\n\t\t\turequire.True(t, found, \"expect board to be found by name\")\n\t\t})\n\t}\n}\n\nfunc TestStorageSize(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tsetup func() boards.Storage\n\t\tsize  int\n\t}{\n\t\t{\n\t\t\tname: \"empty\",\n\t\t\tsetup: func() boards.Storage {\n\t\t\t\treturn boards.NewStorage()\n\t\t\t},\n\t\t\tsize: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"one board\",\n\t\t\tsetup: func() boards.Storage {\n\t\t\t\ts := boards.NewStorage()\n\t\t\t\ts.Add(\u0026boards.Board{ID: 1})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tsize: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"multiple boards\",\n\t\t\tsetup: func() boards.Storage {\n\t\t\t\ts := boards.NewStorage()\n\t\t\t\ts.Add(\u0026boards.Board{ID: 1})\n\t\t\t\ts.Add(\u0026boards.Board{ID: 2})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tsize: 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\ts := tt.setup()\n\n\t\t\turequire.Equal(t, tt.size, s.Size())\n\t\t})\n\t}\n}\n\nfunc TestStorageIterate(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tsetup   func() boards.Storage\n\t\treverse bool\n\t\tids     []boards.ID\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\tsetup: func() boards.Storage {\n\t\t\t\ts := boards.NewStorage()\n\t\t\t\ts.Add(\u0026boards.Board{ID: 1})\n\t\t\t\ts.Add(\u0026boards.Board{ID: 2})\n\t\t\t\ts.Add(\u0026boards.Board{ID: 3})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\tids: []boards.ID{1, 2, 3},\n\t\t},\n\t\t{\n\t\t\tname: \"reverse\",\n\t\t\tsetup: func() boards.Storage {\n\t\t\t\ts := boards.NewStorage()\n\t\t\t\ts.Add(\u0026boards.Board{ID: 1})\n\t\t\t\ts.Add(\u0026boards.Board{ID: 2})\n\t\t\t\ts.Add(\u0026boards.Board{ID: 3})\n\t\t\t\treturn s\n\t\t\t},\n\t\t\treverse: true,\n\t\t\tids:     []boards.ID{3, 2, 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\ts := tt.setup()\n\t\t\tcount := s.Size()\n\t\t\tif tt.reverse {\n\t\t\t\tcount = -count\n\t\t\t}\n\n\t\t\tvar i int\n\t\t\ts.Iterate(0, count, func(p *boards.Board) bool {\n\t\t\t\turequire.True(t, tt.ids[i] == p.ID, \"expect board ID to match\")\n\n\t\t\t\ti++\n\t\t\t\treturn false\n\t\t\t})\n\t\t})\n\t}\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"},{"name":"thread_test.gno","body":"package boards_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n\n\t\"gno.land/p/gnoland/boards\"\n)\n\nfunc TestNewThread(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tboard       *boards.Board\n\t\tcreator     address\n\t\ttitle, body string\n\t\terrMsg      string\n\t}{\n\t\t{\n\t\t\tname:    \"ok\",\n\t\t\tboard:   boards.New(1),\n\t\t\tcreator: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\ttitle:   \"Test\",\n\t\t\tbody:    \"Foo\",\n\t\t},\n\t\t{\n\t\t\tname:   \"nil board\",\n\t\t\tboard:  nil,\n\t\t\terrMsg: \"thread requires a parent board\",\n\t\t},\n\t\t{\n\t\t\tname:    \"invalid creator\",\n\t\t\tboard:   boards.New(1),\n\t\t\tcreator: \"foo\",\n\t\t\terrMsg:  \"invalid thread creator address: foo\",\n\t\t},\n\t\t{\n\t\t\tname:    \"empty title\",\n\t\t\tboard:   boards.New(1),\n\t\t\tcreator: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\ttitle:   \"\",\n\t\t\terrMsg:  \"thread title is required\",\n\t\t},\n\t\t{\n\t\t\tname:    \"empty body\",\n\t\t\tboard:   boards.New(1),\n\t\t\tcreator: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\ttitle:   \"Test\",\n\t\t\tbody:    \"\",\n\t\t\terrMsg:  \"thread body is required\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tthread, err := boards.NewThread(tt.board, tt.creator, tt.title, tt.body)\n\n\t\t\tif tt.errMsg != \"\" {\n\t\t\t\turequire.Error(t, err, \"expect an error\")\n\t\t\t\turequire.ErrorContains(t, err, tt.errMsg, \"expect error to match\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.NoError(t, err, \"expect no error\")\n\t\t\turequire.True(t, tt.board.ThreadsSequence.Last() == thread.ID, \"expect ID to match\")\n\t\t\turequire.True(t, thread.ThreadID == thread.ID, \"expect thread ID to match\")\n\t\t\turequire.False(t, thread.Board == nil, \"expect board to be assigned\")\n\t\t\turequire.True(t, tt.board.ID == thread.Board.ID, \"expect board ID to match\")\n\t\t\turequire.Equal(t, tt.title, thread.Title, \"expect title to match\")\n\t\t\turequire.Equal(t, tt.body, thread.Body, \"expect body to match\")\n\t\t\turequire.True(t, thread.Replies != nil, \"expect thread to support sub-replies\")\n\t\t\turequire.True(t, thread.Reposts != nil, \"expect thread to support reposts\")\n\t\t\turequire.True(t, thread.Flags != nil, \"expect thread to support flagging\")\n\t\t\turequire.Equal(t, tt.creator, thread.Creator, \"expect creator to match\")\n\t\t\turequire.False(t, thread.CreatedAt.IsZero(), \"expect creation date to be assigned\")\n\t\t})\n\t}\n}\n\nfunc TestNewRepost(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\torigThread *boards.Post\n\t\tdstBoard   *boards.Board\n\t\tcreator    address\n\t\terrMsg     string\n\t}{\n\t\t{\n\t\t\tname: \"ok\",\n\t\t\torigThread: boards.MustNewThread(\n\t\t\t\tboards.New(1),\n\t\t\t\t\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\t\t\"Title\",\n\t\t\t\t\"Body\",\n\t\t\t),\n\t\t\tdstBoard: boards.New(2),\n\t\t\tcreator:  \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t},\n\t\t{\n\t\t\tname:       \"nil original thread\",\n\t\t\torigThread: nil,\n\t\t\terrMsg:     \"thread to repost is required\",\n\t\t},\n\t\t{\n\t\t\tname:       \"original thread without board\",\n\t\t\torigThread: \u0026boards.Post{ID: 1},\n\t\t\terrMsg:     \"original thread has no board assigned\",\n\t\t},\n\t\t{\n\t\t\tname: \"nil destination board\",\n\t\t\torigThread: boards.MustNewThread(\n\t\t\t\tboards.New(1),\n\t\t\t\t\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\t\t\"Title\",\n\t\t\t\t\"Body\",\n\t\t\t),\n\t\t\tdstBoard: nil,\n\t\t\terrMsg:   \"thread repost requires a destination board\",\n\t\t},\n\t\t{\n\t\t\tname: \"original thread is not a thread\",\n\t\t\torigThread: \u0026boards.Post{\n\t\t\t\tID:       1,\n\t\t\t\tThreadID: 2,\n\t\t\t\tBoard:    boards.New(1),\n\t\t\t},\n\t\t\tdstBoard: boards.New(2),\n\t\t\terrMsg:   \"post must be a thread to be reposted to another board\",\n\t\t},\n\t\t{\n\t\t\tname: \"original thread is a repost\",\n\t\t\torigThread: \u0026boards.Post{\n\t\t\t\tID:              1,\n\t\t\t\tThreadID:        1,\n\t\t\t\tOriginalBoardID: 1,\n\t\t\t\tBoard:           boards.New(1),\n\t\t\t},\n\t\t\tdstBoard: boards.New(2),\n\t\t\terrMsg:   \"reposting a thread that is a repost is not allowed\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid creator\",\n\t\t\torigThread: boards.MustNewThread(\n\t\t\t\tboards.New(1),\n\t\t\t\t\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\t\t\"Title\",\n\t\t\t\t\"Body\",\n\t\t\t),\n\t\t\tdstBoard: boards.New(2),\n\t\t\tcreator:  \"foo\",\n\t\t\terrMsg:   \"invalid thread repost creator address: foo\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tthread, err := boards.NewRepost(tt.origThread, tt.dstBoard, tt.creator)\n\n\t\t\tif tt.errMsg != \"\" {\n\t\t\t\turequire.Error(t, err, \"expect an error\")\n\t\t\t\turequire.ErrorContains(t, err, tt.errMsg, \"expect error to match\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.NoError(t, err, \"expect no error\")\n\t\t\turequire.True(t, thread.ID == tt.dstBoard.ThreadsSequence.Last(), \"expect ID to match\")\n\t\t\turequire.True(t, thread.ThreadID == thread.ID, \"expect thread ID to match\")\n\t\t\turequire.True(t, thread.ParentID == tt.origThread.ID, \"expect parent ID to match\")\n\t\t\turequire.True(t, thread.OriginalBoardID == tt.origThread.Board.ID, \"expect original board ID to match\")\n\t\t\turequire.False(t, thread.Board == nil, \"expect board to be assigned\")\n\t\t\turequire.True(t, thread.Board.ID == tt.dstBoard.ID, \"expect board ID to match\")\n\t\t\turequire.Empty(t, thread.Title, \"expect title to be empty\")\n\t\t\turequire.Empty(t, thread.Body, \"expect body to be empty\")\n\t\t\turequire.True(t, thread.Replies != nil, \"expect thread to support sub-replies\")\n\t\t\turequire.True(t, thread.Reposts != nil, \"expect thread to support reposts\")\n\t\t\turequire.True(t, thread.Flags != nil, \"expect thread to support flagging\")\n\t\t\turequire.Equal(t, tt.creator, thread.Creator, \"expect creator to match\")\n\t\t\turequire.False(t, thread.CreatedAt.IsZero(), \"expect creation date to be assigned\")\n\t\t})\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"8baW7e1oPNsH6iexJm3wARnkSg6bcCXFFCgUA41lfgQIj4At+4FOdrM/s0WK9d8qRvO7XhRofeMqi7a2F4KH5A=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1manfred47kzduec920z88wfr64ylksmdcedlf5","package":{"name":"addrset","path":"gno.land/p/moul/addrset","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\"\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":"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\"\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"},{"name":"readonly_test.gno","body":"package addrset\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestReadonlySet(t *testing.T) {\n\taddr1 := address(\"addr1\")\n\taddr2 := address(\"addr2\")\n\taddr3 := address(\"addr3\")\n\n\tvar set Set\n\tset.Add(addr1)\n\tset.Add(addr2)\n\n\tro := set.Readonly()\n\tuassert.Equal(t, 2, ro.Size())\n\tuassert.True(t, ro.Has(addr1))\n\tuassert.True(t, ro.Has(addr2))\n\tuassert.False(t, ro.Has(addr3))\n\n\t// NewReadonlySet is equivalent to Set.Readonly.\n\tro2 := NewReadonlySet(\u0026set)\n\tuassert.Equal(t, 2, ro2.Size())\n\tuassert.True(t, ro2.Has(addr1))\n\n\t// The view is a live handle, not a snapshot.\n\tset.Add(addr3)\n\tuassert.Equal(t, 3, ro.Size())\n\tuassert.True(t, ro.Has(addr3))\n\tset.Remove(addr1)\n\tuassert.False(t, ro.Has(addr1))\n}\n\nfunc TestReadonlySetIterateByOffset(t *testing.T) {\n\tvar set Set\n\tset.Add(address(\"addr2\"))\n\tset.Add(address(\"addr1\"))\n\tset.Add(address(\"addr3\"))\n\tro := set.Readonly()\n\n\tvar got []address\n\tstopped := ro.IterateByOffset(0, 10, func(a address) bool {\n\t\tgot = append(got, a)\n\t\treturn false\n\t})\n\tuassert.False(t, stopped)\n\tuassert.Equal(t, 3, len(got))\n\tuassert.Equal(t, address(\"addr1\"), got[0]) // sorted order\n\tuassert.Equal(t, address(\"addr2\"), got[1])\n\tuassert.Equal(t, address(\"addr3\"), got[2])\n\n\t// offset/count window.\n\tgot = nil\n\tro.IterateByOffset(1, 1, func(a address) bool {\n\t\tgot = append(got, a)\n\t\treturn false\n\t})\n\tuassert.Equal(t, 1, len(got))\n\tuassert.Equal(t, address(\"addr2\"), got[0])\n\n\t// Early stop is reported, and iteration actually halts.\n\tcount := 0\n\tstopped = ro.IterateByOffset(0, 10, func(a address) bool {\n\t\tcount++\n\t\treturn true\n\t})\n\tuassert.True(t, stopped)\n\tuassert.Equal(t, 1, count)\n\n\t// Empty set: callback never runs, not stopped.\n\tvar empty Set\n\tstopped = empty.Readonly().IterateByOffset(0, 10, func(a address) bool { return true })\n\tuassert.False(t, stopped)\n}\n\nfunc TestReadonlySetReverseIterateByOffset(t *testing.T) {\n\tvar set Set\n\tset.Add(address(\"addr1\"))\n\tset.Add(address(\"addr2\"))\n\tset.Add(address(\"addr3\"))\n\tro := set.Readonly()\n\n\tvar got []address\n\tstopped := ro.ReverseIterateByOffset(0, 10, func(a address) bool {\n\t\tgot = append(got, a)\n\t\treturn false\n\t})\n\tuassert.False(t, stopped)\n\tuassert.Equal(t, 3, len(got))\n\tuassert.Equal(t, address(\"addr3\"), got[0]) // descending order\n\tuassert.Equal(t, address(\"addr2\"), got[1])\n\tuassert.Equal(t, address(\"addr1\"), got[2])\n\n\t// offset/count window (offset from the end).\n\tgot = nil\n\tro.ReverseIterateByOffset(1, 1, func(a address) bool {\n\t\tgot = append(got, a)\n\t\treturn false\n\t})\n\tuassert.Equal(t, 1, len(got))\n\tuassert.Equal(t, address(\"addr2\"), got[0])\n\n\t// Early stop is reported, and iteration actually halts.\n\tcount := 0\n\tstopped = ro.ReverseIterateByOffset(0, 10, func(a address) bool {\n\t\tcount++\n\t\treturn true\n\t})\n\tuassert.True(t, stopped)\n\tuassert.Equal(t, 1, count)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"0bx+aASOPgOkk+4FuchQtt1O/jwvdkLVPV011s63yikmih/+vPT58G3WNl8yG+MIwCy1DNe7uTBvPXyQCcRcbQ=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g15ge0ae9077eh40erwrn2eq0xw6wupwqthpv34l","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\"\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":"groups_test.gno","body":"package groups\n\nimport (\n\t\"strconv\"\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\nvar (\n\taddr0 = address(\"addr0\")\n\taddr1 = address(\"addr1\")\n\taddr2 = address(\"addr2\")\n\taddr3 = address(\"addr3\")\n\taddr4 = address(\"addr4\")\n\taddr5 = address(\"addr5\")\n\taddr6 = address(\"addr6\")\n)\n\n// newTestGroup builds the fixture used across tests:\n//\n//\tbase:   addr0, addr1, addr3, addr5\n//\tadmins: addr2, addr3, addr5\n//\tmods:   addr1, addr4, addr5\n//\n// Overlap topology: addr0 base-only, addr2 admins-only, addr4 mods-only,\n// addr1 base+mods, addr3 base+admins, addr5 base+both roles.\n// Distinct addresses: addr0..addr5 (addr6 is never a member).\nfunc newTestGroup(t *testing.T) *Group {\n\tt.Helper()\n\tg := NewGroup()\n\tg.Add(addr0)\n\tg.Add(addr1)\n\tg.Add(addr3)\n\tg.Add(addr5)\n\n\tadmins, err := g.AddRole(\"admins\")\n\turequire.NoError(t, err)\n\tadmins.Members().Add(addr2)\n\tadmins.Members().Add(addr3)\n\tadmins.Members().Add(addr5)\n\n\tmods, err := g.AddRole(\"mods\")\n\turequire.NoError(t, err)\n\tmods.Members().Add(addr1)\n\tmods.Members().Add(addr4)\n\tmods.Members().Add(addr5)\n\treturn g\n}\n\nfunc joinAddrs(addrs []address) string {\n\tstrs := make([]string, 0, len(addrs))\n\tfor _, a := range addrs {\n\t\tstrs = append(strs, string(a))\n\t}\n\treturn strings.Join(strs, \",\")\n}\n\nfunc TestBaseSet(t *testing.T) {\n\tg := NewGroup()\n\tuassert.Equal(t, 0, g.Size())\n\tuassert.False(t, g.Has(addr1))\n\n\tuassert.True(t, g.Add(addr1))\n\tuassert.False(t, g.Add(addr1)) // duplicate\n\tuassert.True(t, g.Add(addr2))\n\tuassert.Equal(t, 2, g.Size())\n\tuassert.True(t, g.Has(addr1))\n\tuassert.False(t, g.Has(addr3))\n\n\tuassert.True(t, g.Remove(addr1))\n\tuassert.False(t, g.Remove(addr1)) // already gone\n\tuassert.Equal(t, 1, g.Size())\n\tuassert.False(t, g.Has(addr1))\n}\n\nfunc TestIterate(t *testing.T) {\n\tg := NewGroup()\n\tg.Add(addr2)\n\tg.Add(addr1)\n\tg.Add(addr3)\n\n\tvar got []address\n\tstopped := g.Iterate(0, 10, func(a address) bool {\n\t\tgot = append(got, a)\n\t\treturn false\n\t})\n\tuassert.False(t, stopped)\n\tuassert.Equal(t, \"addr1,addr2,addr3\", joinAddrs(got)) // sorted order\n\n\tgot = nil\n\tg.Iterate(1, 1, func(a address) bool {\n\t\tgot = append(got, a)\n\t\treturn false\n\t})\n\tuassert.Equal(t, \"addr2\", joinAddrs(got))\n\n\t// Early stop halts iteration, not just the return value.\n\tvisited := 0\n\tstopped = g.Iterate(0, 10, func(a address) bool {\n\t\tvisited++\n\t\treturn true\n\t})\n\tuassert.True(t, stopped)\n\tuassert.Equal(t, 1, visited)\n\n\t// Roles are never consulted.\n\tgg := newTestGroup(t)\n\tgot = nil\n\tgg.Iterate(0, 10, func(a address) bool {\n\t\tgot = append(got, a)\n\t\treturn false\n\t})\n\tuassert.Equal(t, \"addr0,addr1,addr3,addr5\", joinAddrs(got))\n}\n\nfunc TestAddRole(t *testing.T) {\n\tg := NewGroup()\n\n\tr, err := g.AddRole(\"admins\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"admins\", r.Name())\n\tuassert.Equal(t, 0, r.Members().Size())\n\tuassert.Equal(t, 1, g.RoleCount())\n\n\t_, err = g.AddRole(\"admins\")\n\tuassert.ErrorIs(t, err, ErrRoleExists)\n\n\t_, err = g.AddRole(\"\")\n\tuassert.ErrorIs(t, err, ErrEmptyName)\n\n\tuassert.Equal(t, 1, g.RoleCount())\n}\n\nfunc TestGetRoleHasRole(t *testing.T) {\n\tg := newTestGroup(t)\n\n\tr, found := g.GetRole(\"admins\")\n\tuassert.True(t, found)\n\tuassert.Equal(t, \"admins\", r.Name())\n\tuassert.True(t, r.Members().Has(addr2))\n\n\t_, found = g.GetRole(\"nope\")\n\tuassert.False(t, found)\n\n\tuassert.True(t, g.HasRole(\"mods\"))\n\tuassert.False(t, g.HasRole(\"nope\"))\n}\n\nfunc TestRemoveRole(t *testing.T) {\n\tg := newTestGroup(t)\n\n\tuassert.True(t, g.RemoveRole(\"admins\"))\n\tuassert.False(t, g.RemoveRole(\"admins\")) // already gone\n\tuassert.Equal(t, 1, g.RoleCount())\n\tuassert.False(t, g.HasRole(\"admins\"))\n\n\t// Members of the removed role stay in the base set and other roles.\n\tuassert.True(t, g.Has(addr3))     // base\n\tuassert.True(t, g.HasAny(addr5))  // still in base + mods\n\tuassert.False(t, g.HasAny(addr2)) // was only in admins\n}\n\nfunc TestIterateRoles(t *testing.T) {\n\tg := newTestGroup(t)\n\n\tvar names []string\n\tstopped := g.IterateRoles(0, 10, func(rr *ReadonlyRole) bool {\n\t\tnames = append(names, rr.Name())\n\t\treturn false\n\t})\n\tuassert.False(t, stopped)\n\tuassert.Equal(t, \"admins,mods\", strings.Join(names, \",\"))\n\n\t// offset/count window.\n\tnames = nil\n\tg.IterateRoles(1, 1, func(rr *ReadonlyRole) bool {\n\t\tnames = append(names, rr.Name())\n\t\treturn false\n\t})\n\tuassert.Equal(t, \"mods\", strings.Join(names, \",\"))\n\n\t// Early stop halts iteration, not just the return value.\n\tnames = nil\n\tstopped = g.IterateRoles(0, 10, func(rr *ReadonlyRole) bool {\n\t\tnames = append(names, rr.Name())\n\t\treturn true\n\t})\n\tuassert.True(t, stopped)\n\tuassert.Equal(t, \"admins\", strings.Join(names, \",\"))\n\n\t// Mutation path: capture names during iteration, revisit via GetRole.\n\tnames = nil\n\tg.IterateRoles(0, 10, func(rr *ReadonlyRole) bool {\n\t\tnames = append(names, rr.Name())\n\t\treturn false\n\t})\n\tfor _, name := range names {\n\t\tr, found := g.GetRole(name)\n\t\turequire.True(t, found)\n\t\tr.Members().Add(addr6)\n\t}\n\tuassert.Equal(t, \"admins,mods\", strings.Join(g.RolesContaining(addr6), \",\"))\n}\n\nfunc TestRoleMeta(t *testing.T) {\n\tg := NewGroup()\n\tr, err := g.AddRole(\"admins\")\n\turequire.NoError(t, err)\n\n\tuassert.Nil(t, r.Meta())\n\tr.SetMeta(\"quorum=2/3\")\n\tuassert.Equal(t, \"quorum=2/3\", r.Meta())\n\tuassert.Equal(t, \"quorum=2/3\", r.Readonly().Meta())\n\tr.SetMeta(nil)\n\tuassert.Nil(t, r.Meta())\n}\n\nfunc TestHasAny(t *testing.T) {\n\tg := newTestGroup(t)\n\n\tuassert.True(t, g.HasAny(addr0))  // base only\n\tuassert.True(t, g.HasAny(addr1))  // base + mods\n\tuassert.True(t, g.HasAny(addr2))  // admins only\n\tuassert.True(t, g.HasAny(addr4))  // mods only\n\tuassert.True(t, g.HasAny(addr5))  // base + both roles\n\tuassert.False(t, g.HasAny(addr6)) // nowhere\n\n\t// Base-only member, no roles registered at all.\n\tg2 := NewGroup()\n\tg2.Add(addr1)\n\tuassert.True(t, g2.HasAny(addr1))\n\tuassert.False(t, g2.HasAny(addr2))\n}\n\nfunc TestTotalSize(t *testing.T) {\n\tuassert.Equal(t, 0, NewGroup().TotalSize())\n\n\tg := newTestGroup(t)\n\tuassert.Equal(t, 4, g.Size())      // base only\n\tuassert.Equal(t, 6, g.TotalSize()) // addr0..addr5, deduplicated\n}\n\nfunc TestIterateAll(t *testing.T) {\n\tg := newTestGroup(t)\n\n\tcollect := func(offset, count int) (addrs []address, stopped bool) {\n\t\tstopped = g.IterateAll(offset, count, func(a address) bool {\n\t\t\taddrs = append(addrs, a)\n\t\t\treturn false\n\t\t})\n\t\treturn addrs, stopped\n\t}\n\n\t// Order: base first (sorted), then roles in name order, deduplicated.\n\tgot, stopped := collect(0, 10)\n\tuassert.False(t, stopped)\n\tuassert.Equal(t, \"addr0,addr1,addr3,addr5,addr2,addr4\", joinAddrs(got))\n\n\t// offset/count window over the deduplicated output.\n\tgot, _ = collect(1, 2)\n\tuassert.Equal(t, \"addr1,addr3\", joinAddrs(got))\n\tgot, _ = collect(3, 10)\n\tuassert.Equal(t, \"addr5,addr2,addr4\", joinAddrs(got))\n\t// Window straddling skipped duplicates: count applies to deduplicated\n\t// output, not to scanned items.\n\tgot, _ = collect(4, 2)\n\tuassert.Equal(t, \"addr2,addr4\", joinAddrs(got))\n\n\t// Degenerate parameters.\n\tgot, stopped = collect(6, 10) // offset == total\n\tuassert.False(t, stopped)\n\tuassert.Equal(t, 0, len(got))\n\tgot, _ = collect(0, 0)\n\tuassert.Equal(t, 0, len(got))\n\tgot, _ = collect(-1, 2) // negative offset counts as zero\n\tuassert.Equal(t, \"addr0,addr1\", joinAddrs(got))\n\n\t// Early stop halts iteration, not just the return value.\n\tvisited := 0\n\tstopped = g.IterateAll(0, 10, func(a address) bool {\n\t\tvisited++\n\t\treturn true\n\t})\n\tuassert.True(t, stopped)\n\tuassert.Equal(t, 1, visited)\n}\n\n// TestIterateAllWindows pins the pagination contract exhaustively: every\n// (offset, count) window over the deduplicated walk must equal the\n// corresponding slice of the full walk.\nfunc TestIterateAllWindows(t *testing.T) {\n\tg := newTestGroup(t)\n\n\tvar full []address\n\tg.IterateAll(0, 100, func(a address) bool {\n\t\tfull = append(full, a)\n\t\treturn false\n\t})\n\turequire.Equal(t, 6, len(full))\n\n\tfor offset := 0; offset \u003c= len(full); offset++ {\n\t\tfor count := 1; count \u003c= len(full)+1; count++ {\n\t\t\tvar page []address\n\t\t\tg.IterateAll(offset, count, func(a address) bool {\n\t\t\t\tpage = append(page, a)\n\t\t\t\treturn false\n\t\t\t})\n\t\t\tend := offset + count\n\t\t\tif end \u003e len(full) {\n\t\t\t\tend = len(full)\n\t\t\t}\n\t\t\tlabel := \"offset=\" + strconv.Itoa(offset) + \" count=\" + strconv.Itoa(count)\n\t\t\tuassert.Equal(t, joinAddrs(full[offset:end]), joinAddrs(page), label)\n\t\t}\n\t}\n}\n\nfunc TestRolesContaining(t *testing.T) {\n\tg := newTestGroup(t)\n\n\tuassert.Equal(t, \"admins,mods\", strings.Join(g.RolesContaining(addr5), \",\"))\n\tuassert.Equal(t, \"admins\", strings.Join(g.RolesContaining(addr2), \",\"))\n\tuassert.Equal(t, \"mods\", strings.Join(g.RolesContaining(addr1), \",\")) // base not consulted\n\tuassert.Equal(t, 0, len(g.RolesContaining(addr0)))                    // base-only member\n\tuassert.Equal(t, 0, len(g.RolesContaining(addr6)))\n}\n\nfunc TestRemoveFromAll(t *testing.T) {\n\tg := newTestGroup(t)\n\n\tuassert.True(t, g.RemoveFromAll(addr5)) // base + both roles\n\tuassert.False(t, g.HasAny(addr5))\n\n\tuassert.True(t, g.RemoveFromAll(addr0)) // base-only: removed reflects the base hit alone\n\tuassert.False(t, g.HasAny(addr0))\n\n\tuassert.True(t, g.RemoveFromAll(addr2)) // role-only\n\tuassert.False(t, g.HasAny(addr2))\n\n\tuassert.False(t, g.RemoveFromAll(addr6)) // nowhere\n\n\tuassert.Equal(t, 3, g.TotalSize()) // addr1, addr3, addr4 remain\n\tuassert.Equal(t, 2, g.RoleCount()) // roles themselves are kept\n}\n\n// TestRemoveRoleStaleHandle pins the aliasing semantics: a *Role handle\n// held across RemoveRole keeps working as a detached object, but its\n// mutations no longer affect the group, and re-adding the name creates a\n// fresh, independent role.\nfunc TestRemoveRoleStaleHandle(t *testing.T) {\n\tg := newTestGroup(t)\n\tstale, found := g.GetRole(\"admins\")\n\turequire.True(t, found)\n\n\tuassert.True(t, g.RemoveRole(\"admins\"))\n\n\t// The detached role still works as an orphan object...\n\tuassert.Equal(t, \"admins\", stale.Name())\n\tstale.Members().Add(addr6)\n\tuassert.True(t, stale.Members().Has(addr6))\n\n\t// ...but no longer affects the group.\n\tuassert.False(t, g.HasAny(addr6))\n\tuassert.Equal(t, 0, len(g.RolesContaining(addr6)))\n\tuassert.False(t, g.HasAny(addr2))  // addr2 was admins-only\n\tuassert.Equal(t, 5, g.TotalSize()) // fixture minus admins-only addr2\n\n\t// Re-adding the name yields a fresh empty role, not the stale one.\n\tfresh, err := g.AddRole(\"admins\")\n\turequire.NoError(t, err)\n\tuassert.Equal(t, 0, fresh.Members().Size())\n\tuassert.False(t, g.HasAny(addr6))\n}\n\nfunc TestReadonlyGroup(t *testing.T) {\n\tg := newTestGroup(t)\n\trg := g.Readonly()\n\n\t// Base reads.\n\tuassert.True(t, rg.Has(addr0))\n\tuassert.False(t, rg.Has(addr2))\n\tuassert.Equal(t, 4, rg.Size())\n\tvar got []address\n\tstopped := rg.Iterate(0, 10, func(a address) bool {\n\t\tgot = append(got, a)\n\t\treturn false\n\t})\n\tuassert.False(t, stopped)\n\tuassert.Equal(t, \"addr0,addr1,addr3,addr5\", joinAddrs(got))\n\n\t// Role registry reads.\n\tuassert.True(t, rg.HasRole(\"admins\"))\n\tuassert.False(t, rg.HasRole(\"nope\"))\n\tuassert.Equal(t, 2, rg.RoleCount())\n\tvar names []string\n\tstopped = rg.IterateRoles(0, 10, func(rr *ReadonlyRole) bool {\n\t\tnames = append(names, rr.Name())\n\t\treturn false\n\t})\n\tuassert.False(t, stopped)\n\tuassert.Equal(t, \"admins,mods\", strings.Join(names, \",\"))\n\n\trr, found := rg.GetRole(\"admins\")\n\tuassert.True(t, found)\n\tuassert.Equal(t, \"admins\", rr.Name())\n\tuassert.True(t, rr.Members().Has(addr2))\n\tuassert.Equal(t, 3, rr.Members().Size())\n\t_, found = rg.GetRole(\"nope\")\n\tuassert.False(t, found)\n\n\t// Aggregated reads.\n\tuassert.True(t, rg.HasAny(addr4))\n\tuassert.False(t, rg.HasAny(addr6))\n\tuassert.Equal(t, 6, rg.TotalSize())\n\tgot = nil\n\tstopped = rg.IterateAll(0, 10, func(a address) bool {\n\t\tgot = append(got, a)\n\t\treturn false\n\t})\n\tuassert.False(t, stopped)\n\tuassert.Equal(t, \"addr0,addr1,addr3,addr5,addr2,addr4\", joinAddrs(got))\n\tuassert.True(t, rg.IterateAll(0, 10, func(a address) bool { return true }))\n\tuassert.Equal(t, \"admins,mods\", strings.Join(rg.RolesContaining(addr5), \",\"))\n}\n\nfunc TestReadonlyViewsAreLive(t *testing.T) {\n\tg := newTestGroup(t)\n\trg := g.Readonly()\n\tadmins, found := g.GetRole(\"admins\")\n\turequire.True(t, found)\n\trr := admins.Readonly()\n\n\t// Views are thin handles, not snapshots: mutations through the owning\n\t// side are immediately visible through previously created views.\n\tg.Add(addr6)\n\tuassert.Equal(t, 5, rg.Size())\n\tuassert.True(t, rg.Has(addr6))\n\n\tadmins.Members().Add(addr6)\n\tuassert.Equal(t, 4, rr.Members().Size())\n\tuassert.True(t, rr.Members().Has(addr6))\n}\n"},{"name":"readonly.gno","body":"package groups\n\nimport \"gno.land/p/moul/addrset\"\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\"\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"},{"name":"z_readme_filetest.gno","body":"// End-to-end scenario from the package README: a group with a base set and\n// three roles, exercising base vs aggregated semantics, dedup, role\n// removal, and readonly views.\npackage main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/nt/groups/v0\"\n)\n\nvar (\n\talice = address(\"alice\") // base only\n\tbob   = address(\"bob\")   // base + council\n\tcarol = address(\"carol\") // base + admin\n\tdave  = address(\"dave\")  // council only\n\teve   = address(\"eve\")   // admin + moderator\n\tfrank = address(\"frank\") // moderator only\n\tgrace = address(\"grace\") // admin only\n\tzed   = address(\"zed\")   // not a member\n)\n\nfunc main() {\n\t// 1. A group with a base set and three named roles.\n\tg := groups.NewGroup()\n\tg.Add(alice)\n\tg.Add(bob)\n\tg.Add(carol)\n\n\tadmin, _ := g.AddRole(\"admin\")\n\tadmin.Members().Add(carol)\n\tadmin.Members().Add(eve)\n\tadmin.Members().Add(grace)\n\n\tcouncil, _ := g.AddRole(\"council\")\n\tcouncil.Members().Add(bob)\n\tcouncil.Members().Add(dave)\n\n\tmoderator, _ := g.AddRole(\"moderator\")\n\tmoderator.Members().Add(eve)\n\tmoderator.Members().Add(frank)\n\n\t// 2. Has (base only) vs HasAny (base + roles).\n\tprintln(\"Has(alice):\", g.Has(alice))     // base member\n\tprintln(\"Has(dave):\", g.Has(dave))       // council only, not base\n\tprintln(\"HasAny(dave):\", g.HasAny(dave)) // somewhere in the group\n\tprintln(\"HasAny(zed):\", g.HasAny(zed))   // nowhere\n\n\t// 3. Size (base only) vs TotalSize (deduplicated across everything).\n\tprintln(\"Size:\", g.Size())\n\tprintln(\"TotalSize:\", g.TotalSize())\n\n\t// 4. Iterate walks the base set; IterateAll walks base then roles in\n\t// name order, yielding each distinct address once.\n\tprint(\"Iterate:\")\n\tg.Iterate(0, 10, func(a address) bool {\n\t\tprint(\" \" + string(a))\n\t\treturn false\n\t})\n\tprintln()\n\tprint(\"IterateAll:\")\n\tg.IterateAll(0, 10, func(a address) bool {\n\t\tprint(\" \" + string(a))\n\t\treturn false\n\t})\n\tprintln()\n\n\t// 5. RolesContaining lists role names in lexicographic order; the\n\t// base set is not a role.\n\tprintln(\"RolesContaining(eve):\", strings.Join(g.RolesContaining(eve), \",\"))\n\tprintln(\"RolesContaining(alice):\", strings.Join(g.RolesContaining(alice), \",\"))\n\n\t// 6. Removing a role discards only the role: its members survive in\n\t// the base set and in other roles.\n\tg.RemoveRole(\"admin\")\n\tprintln(\"after RemoveRole(admin):\")\n\tprintln(\"Has(carol):\", g.Has(carol))       // still a base member\n\tprintln(\"HasAny(eve):\", g.HasAny(eve))     // still a moderator\n\tprintln(\"HasAny(grace):\", g.HasAny(grace)) // was admin only, now gone\n\tprintln(\"TotalSize:\", g.TotalSize())\n\n\t// 7. A readonly view mirrors every read and exposes no mutators; it\n\t// is the only handle meant to cross a realm boundary.\n\trg := g.Readonly()\n\tprintln(\"readonly Size:\", rg.Size())\n\tprintln(\"readonly HasAny(dave):\", rg.HasAny(dave))\n\trr, _ := rg.GetRole(\"moderator\")\n\tprintln(\"readonly moderator members:\", rr.Members().Size())\n}\n\n// Output:\n// Has(alice): true\n// Has(dave): false\n// HasAny(dave): true\n// HasAny(zed): false\n// Size: 3\n// TotalSize: 7\n// Iterate: alice bob carol\n// IterateAll: alice bob carol eve grace dave frank\n// RolesContaining(eve): admin,moderator\n// RolesContaining(alice):\n// after RemoveRole(admin):\n// Has(carol): true\n// HasAny(eve): true\n// HasAny(grace): false\n// TotalSize: 6\n// readonly Size: 3\n// readonly HasAny(dave): true\n// readonly moderator members: 2\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"O9SpF87stZ+9SZZ1uL86drdLvJoAftvcgIR3wIsiJrBWDt1g0Rx1mGTrr0iajQYcVbQPNWVM4xngSTWI4lfawA=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"permissions","path":"gno.land/p/gnoland/boards/exts/permissions","files":[{"name":"README.md","body":"# Boards Permissions Extension\n\nThis is a `gno.land/p/gnoland/boards` 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\"\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":"example_test.gno","body":"package permissions\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/gnoland/boards\"\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"},{"name":"gnomod.toml","body":"module = \"gno.land/p/gnoland/boards/exts/permissions\"\ngno = \"0.9\"\n"},{"name":"options.gno","body":"package permissions\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/gnoland/boards\"\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\"\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` 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"},{"name":"permissions_test.gno","body":"package permissions\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\n// Test permission constants\nconst (\n\ttestPermA boards.Permission = iota\n\ttestPermB\n\ttestPermC\n)\n\nvar _ boards.Permissions = (*Permissions)(nil)\n\nfunc TestBasicPermissionsWithPermission(cur realm, t *testing.T) {\n\tcases := []struct {\n\t\tname       string\n\t\tuser       address\n\t\tpermission boards.Permission\n\t\targs       boards.Args\n\t\tsetup      func() *Permissions\n\t\terr        string\n\t\tcalled     bool\n\t}{\n\t\t{\n\t\t\tname:       \"ok\",\n\t\t\tuser:       \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\tpermission: testPermA,\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"foo\", testPermA)\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", \"foo\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t\tcalled: true,\n\t\t},\n\t\t{\n\t\t\tname:       \"ok with arguments\",\n\t\t\tuser:       \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\tpermission: testPermA,\n\t\t\targs:       boards.Args{\"a\", \"b\"},\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"foo\", testPermA)\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", \"foo\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t\tcalled: true,\n\t\t},\n\t\t{\n\t\t\tname:       \"no permission\",\n\t\t\tuser:       \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\tpermission: testPermA,\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"foo\", testPermA)\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t\terr: \"unauthorized, user g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 doesn't have the required permission\",\n\t\t},\n\t\t{\n\t\t\tname:       \"is not a member\",\n\t\t\tuser:       \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\tpermission: testPermA,\n\t\t\tsetup: func() *Permissions {\n\t\t\t\treturn New()\n\t\t\t},\n\t\t\terr: \"unauthorized, user g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 doesn't have the required permission\",\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tvar called bool\n\n\t\t\tperms := tc.setup()\n\t\t\ttestCaseFn := func() {\n\t\t\t\tperms.WithPermission(tc.user, tc.permission, tc.args, func() {\n\t\t\t\t\tcalled = true\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif tc.err != \"\" {\n\t\t\t\turequire.PanicsWithMessage(t, cur, tc.err, testCaseFn, \"expect panic with message\")\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\turequire.NotPanics(t, cur, testCaseFn, \"expect no panic\")\n\t\t\t}\n\n\t\t\turequire.Equal(t, tc.called, called, \"expect callback to be called\")\n\t\t})\n\t}\n}\n\nfunc TestBasicPermissionsSetPublicPermissions(t *testing.T) {\n\tuser := address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\tperms := New()\n\n\t// Add a new role with permissions\n\tperms.AddRole(\"adminRole\", testPermA, testPermB, testPermC)\n\turequire.False(t, perms.HasPermission(user, testPermA))\n\turequire.False(t, perms.HasPermission(user, testPermB))\n\turequire.False(t, perms.HasPermission(user, testPermC))\n\n\t// Assign a couple of public permissions\n\tperms.SetPublicPermissions(testPermA, testPermC)\n\turequire.True(t, perms.HasPermission(user, testPermA))\n\turequire.False(t, perms.HasPermission(user, testPermB))\n\turequire.True(t, perms.HasPermission(user, testPermC))\n\n\t// Clear all public permissions\n\tperms.SetPublicPermissions()\n\turequire.False(t, perms.HasPermission(user, testPermA))\n\turequire.False(t, perms.HasPermission(user, testPermB))\n\turequire.False(t, perms.HasPermission(user, testPermC))\n}\n\nfunc TestBasicPermissionsGetUserRoles(t *testing.T) {\n\tcases := []struct {\n\t\tname  string\n\t\tuser  address\n\t\troles []string\n\t\tsetup func() *Permissions\n\t}{\n\t\t{\n\t\t\tname:  \"single role\",\n\t\t\tuser:  \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\troles: []string{\"admin\"},\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"admin\", testPermA)\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", \"admin\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:  \"multiple roles\",\n\t\t\tuser:  \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\troles: []string{\"admin\", \"bar\", \"foo\"},\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"admin\", testPermA)\n\t\t\t\tperms.AddRole(\"foo\", testPermA)\n\t\t\t\tperms.AddRole(\"bar\", testPermA)\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", \"admin\", \"foo\", \"bar\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"without roles\",\n\t\t\tuser: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"not a user\",\n\t\t\tuser: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\tsetup: func() *Permissions {\n\t\t\t\treturn New()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:  \"multiple users\",\n\t\t\tuser:  \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\troles: []string{\"admin\"},\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"admin\", testPermA)\n\t\t\t\tperms.AddRole(\"bar\", testPermA)\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", \"admin\")\n\t\t\t\tperms.SetUserRoles(\"g1w4ek2u33ta047h6lta047h6lta047h6ldvdwpn\", \"admin\")\n\t\t\t\tperms.SetUserRoles(\"g1w4ek2u3jta047h6lta047h6lta047h6l9huexc\", \"admin\", \"bar\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tperms := tc.setup()\n\t\t\troles := perms.GetUserRoles(tc.user)\n\n\t\t\turequire.Equal(t, len(tc.roles), len(roles), \"user role count\")\n\t\t\tfor i, r := range roles {\n\t\t\t\tuassert.Equal(t, tc.roles[i], string(r))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestBasicPermissionsHasRole(t *testing.T) {\n\tcases := []struct {\n\t\tname  string\n\t\tuser  address\n\t\trole  boards.Role\n\t\tsetup func() *Permissions\n\t\twant  bool\n\t}{\n\t\t{\n\t\t\tname: \"ok\",\n\t\t\tuser: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\trole: \"admin\",\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"admin\", testPermA)\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", \"admin\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"ok with multiple roles\",\n\t\t\tuser: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\trole: \"foo\",\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"admin\", testPermA)\n\t\t\t\tperms.AddRole(\"foo\", testPermA)\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", \"admin\", \"foo\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"user without roles\",\n\t\t\tuser: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"has no role\",\n\t\t\tuser: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\trole: \"bar\",\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"foo\", testPermA)\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", \"foo\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tperms := tc.setup()\n\t\t\tgot := perms.HasRole(tc.user, tc.role)\n\t\t\tuassert.Equal(t, tc.want, got)\n\t\t})\n\t}\n}\n\nfunc TestBasicPermissionsHasPermission(t *testing.T) {\n\tcases := []struct {\n\t\tname       string\n\t\tuser       address\n\t\tpermission boards.Permission\n\t\tsetup      func() *Permissions\n\t\twant       bool\n\t}{\n\t\t{\n\t\t\tname:       \"ok\",\n\t\t\tuser:       \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\tpermission: testPermA,\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"foo\", testPermA)\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", \"foo\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname:       \"ok with multiple users\",\n\t\t\tuser:       \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\tpermission: testPermA,\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"foo\", testPermA)\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", \"foo\")\n\t\t\t\tperms.SetUserRoles(\"g1w4ek2u33ta047h6lta047h6lta047h6ldvdwpn\", \"foo\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname:       \"ok with multiple roles\",\n\t\t\tuser:       \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\tpermission: testPermB,\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"foo\", testPermA)\n\t\t\t\tperms.AddRole(\"baz\", testPermB)\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", \"foo\", \"baz\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname:       \"no permission\",\n\t\t\tuser:       \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\tpermission: testPermB,\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"foo\", testPermA)\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", \"foo\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tperms := tc.setup()\n\t\t\tgot := perms.HasPermission(tc.user, tc.permission)\n\t\t\tuassert.Equal(t, tc.want, got)\n\t\t})\n\t}\n}\n\nfunc TestBasicPermissionsSetUserRoles(cur realm, t *testing.T) {\n\tcases := []struct {\n\t\tname          string\n\t\tuser          address\n\t\texpectedRoles []boards.Role\n\t\tsetup         func() *Permissions\n\t\terr           string\n\t}{\n\t\t{\n\t\t\tname:          \"add user\",\n\t\t\tuser:          address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"),\n\t\t\texpectedRoles: []boards.Role{\"a\"},\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"a\", testPermA)\n\t\t\t\treturn perms\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:          \"add user with multiple roles\",\n\t\t\tuser:          address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"),\n\t\t\texpectedRoles: []boards.Role{\"a\", \"b\"},\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"a\", testPermA)\n\t\t\t\tperms.AddRole(\"b\", testPermB)\n\t\t\t\treturn perms\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:          \"add when other users exists\",\n\t\t\tuser:          address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"),\n\t\t\texpectedRoles: []boards.Role{\"a\"},\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"a\", testPermA)\n\t\t\t\tperms.SetUserRoles(\"g1w4ek2u33ta047h6lta047h6lta047h6ldvdwpn\", \"a\")\n\t\t\t\tperms.SetUserRoles(\"g1w4ek2u3jta047h6lta047h6lta047h6l9huexc\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:          \"add user using single role\",\n\t\t\tuser:          address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"),\n\t\t\texpectedRoles: []boards.Role{\"a\"},\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New(UseSingleUserRole())\n\t\t\t\tperms.AddRole(\"a\", testPermA)\n\t\t\t\treturn perms\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:          \"update user roles\",\n\t\t\tuser:          address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"),\n\t\t\texpectedRoles: []boards.Role{\"a\", \"b\"},\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"a\", testPermA)\n\t\t\t\tperms.AddRole(\"b\", testPermB)\n\t\t\t\tperms.AddRole(\"c\", testPermB)\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", \"c\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:          \"update user roles using single role\",\n\t\t\tuser:          address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"),\n\t\t\texpectedRoles: []boards.Role{\"b\"},\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New(UseSingleUserRole())\n\t\t\t\tperms.AddRole(\"a\", testPermA)\n\t\t\t\tperms.AddRole(\"b\", testPermB)\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", \"a\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:          \"clear user roles\",\n\t\t\tuser:          address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"),\n\t\t\texpectedRoles: []boards.Role{},\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"a\", testPermA)\n\t\t\t\tperms.AddRole(\"b\", testPermB)\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", \"a\", \"b\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:          \"set invalid role\",\n\t\t\tuser:          address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"),\n\t\t\texpectedRoles: []boards.Role{\"a\", \"foo\"},\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.AddRole(\"a\", testPermA)\n\t\t\t\treturn perms\n\t\t\t},\n\t\t\terr: \"invalid role: foo\",\n\t\t},\n\t\t{\n\t\t\tname:          \"use single role error\",\n\t\t\tuser:          address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"),\n\t\t\texpectedRoles: []boards.Role{\"a\", \"b\"},\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New(UseSingleUserRole())\n\t\t\t\tperms.AddRole(\"a\", testPermA)\n\t\t\t\tperms.AddRole(\"b\", testPermB)\n\t\t\t\treturn perms\n\t\t\t},\n\t\t\terr: \"user can only have one role\",\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tperms := tc.setup()\n\n\t\t\tsetUserRoles := func() {\n\t\t\t\tperms.SetUserRoles(tc.user, tc.expectedRoles...)\n\t\t\t}\n\n\t\t\tif tc.err != \"\" {\n\t\t\t\turequire.PanicsWithMessage(t, cur, tc.err, setUserRoles, \"expected an error\")\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\turequire.NotPanics(t, cur, setUserRoles, \"expected no error\")\n\t\t\t}\n\n\t\t\troles := perms.GetUserRoles(tc.user)\n\t\t\tuassert.Equal(t, len(tc.expectedRoles), len(roles))\n\t\t\tfor i, r := range roles {\n\t\t\t\turequire.Equal(t, string(tc.expectedRoles[i]), string(r))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestBasicPermissionsAddRoleOverwrite(t *testing.T) {\n\tuser := address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\n\tperms := New()\n\tperms.AddRole(\"foo\", testPermA)\n\tperms.SetUserRoles(user, \"foo\")\n\n\t// Re-adding an existing role replaces its permissions and keeps members\n\tperms.AddRole(\"foo\", testPermB)\n\tuassert.True(t, perms.HasRole(user, \"foo\"), \"expect role members to be kept\")\n\tuassert.False(t, perms.HasPermission(user, testPermA), \"expect old permissions to be revoked\")\n\tuassert.True(t, perms.HasPermission(user, testPermB), \"expect new permissions to be granted\")\n}\n\nfunc TestBasicPermissionsAddRoleEmptyName(cur realm, t *testing.T) {\n\turequire.PanicsWithMessage(t, cur, \"role name is required\", func() {\n\t\tNew().AddRole(\"  \", testPermA)\n\t}, \"expect whitespace only role names to be rejected\")\n\n\turequire.PanicsWithMessage(t, cur, \"permissions super role name is required\", func() {\n\t\tNew(WithSuperRole(\"  \"))\n\t}, \"expect whitespace only super role names to be rejected\")\n\n\t// The empty string is rejected before the superRole sentinel check, so\n\t// the outcome doesn't depend on whether a super role is configured.\n\turequire.PanicsWithMessage(t, cur, \"role name is required\", func() {\n\t\tNew().AddRole(\"\", testPermA)\n\t}, \"expect empty role name to be rejected without a super role\")\n\turequire.PanicsWithMessage(t, cur, \"role name is required\", func() {\n\t\tNew(WithSuperRole(\"owner\")).AddRole(\"\", testPermA)\n\t}, \"expect empty role name to be rejected with a super role\")\n}\n\nfunc TestBasicPermissionsSuperRole(t *testing.T) {\n\tuser := address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\tsuper := boards.Role(\"owner\")\n\n\tperms := New(WithSuperRole(super))\n\turequire.True(t, perms.RoleExists(super), \"expect super role to exist\")\n\turequire.False(t, perms.RoleExists(\"unknown\"))\n\n\t// Super role members get every permission without explicit mapping\n\tperms.SetUserRoles(user, super)\n\turequire.True(t, perms.HasRole(user, super))\n\tuassert.True(t, perms.HasUser(user))\n\tuassert.True(t, perms.HasPermission(user, testPermA))\n\tuassert.True(t, perms.HasPermission(user, testPermC))\n\n\t// AddRole on the super role is a no-op: the super role branch grants\n\t// every permission regardless of any meta a mapping would set\n\tperms.AddRole(super, testPermB)\n\tuassert.True(t, perms.HasPermission(user, testPermA), \"expect super role to keep all permissions\")\n}\n\nfunc TestBasicPermissionsHasUserUsersCount(t *testing.T) {\n\tmember := address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\tguest := address(\"g1w4ek2u33ta047h6lta047h6lta047h6ldvdwpn\")\n\n\tperms := New()\n\tperms.AddRole(\"foo\", testPermA)\n\turequire.Equal(t, 0, perms.UsersCount())\n\turequire.False(t, perms.HasUser(member))\n\n\t// A user added only through a role counts as a user\n\tperms.SetUserRoles(member, \"foo\")\n\turequire.True(t, perms.HasUser(member), \"expect role holder to be a user\")\n\turequire.Equal(t, 1, perms.UsersCount())\n\n\t// A guest without roles counts as a user\n\tperms.SetUserRoles(guest)\n\turequire.True(t, perms.HasUser(guest))\n\turequire.Equal(t, 2, perms.UsersCount())\n\n\t// Clearing roles keeps the user and doesn't change the count\n\tperms.SetUserRoles(member)\n\turequire.True(t, perms.HasUser(member), \"expect user to remain after roles are cleared\")\n\turequire.Equal(t, 2, perms.UsersCount())\n\n\t// Re-assigning roles must not double count\n\tperms.SetUserRoles(member, \"foo\")\n\turequire.Equal(t, 2, perms.UsersCount())\n}\n\nfunc TestBasicPermissionsSetUserRolesPanicKeepsState(cur realm, t *testing.T) {\n\tuser := address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\n\tperms := New()\n\tperms.AddRole(\"a\", testPermA)\n\tperms.SetUserRoles(user, \"a\")\n\n\turequire.PanicsWithMessage(t, cur, \"invalid role: nope\", func() {\n\t\tperms.SetUserRoles(user, \"nope\")\n\t}, \"expect invalid role to panic\")\n\n\t// The failed call must not have mutated state\n\tuassert.True(t, perms.HasUser(user))\n\tuassert.True(t, perms.HasRole(user, \"a\"))\n\tuassert.Equal(t, 1, perms.UsersCount())\n}\n\nfunc TestBasicPermissionsRemoveUser(t *testing.T) {\n\tcases := []struct {\n\t\tname  string\n\t\tuser  address\n\t\tsetup func() *Permissions\n\t\twant  bool\n\t}{\n\t\t{\n\t\t\tname: \"ok\",\n\t\t\tuser: address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"),\n\t\t\tsetup: func() *Permissions {\n\t\t\t\tperms := New()\n\t\t\t\tperms.SetUserRoles(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\t\t\t\treturn perms\n\t\t\t},\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"user not found\",\n\t\t\tuser: address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"),\n\t\t\tsetup: func() *Permissions {\n\t\t\t\treturn New()\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tperms := tc.setup()\n\t\t\tgot := perms.RemoveUser(tc.user)\n\t\t\tuassert.Equal(t, tc.want, got)\n\t\t})\n\t}\n}\n\nfunc TestBasicPermissionsRemoveUserWithRoles(t *testing.T) {\n\tuser := address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\n\tperms := New()\n\tperms.AddRole(\"foo\", testPermA)\n\tperms.AddRole(\"bar\", testPermB)\n\tperms.SetUserRoles(user, \"foo\", \"bar\")\n\n\turequire.True(t, perms.RemoveUser(user), \"expect role holder to be removed\")\n\n\tuassert.False(t, perms.HasUser(user), \"expect removed user to not exist\")\n\tuassert.False(t, perms.HasRole(user, \"foo\"), \"expect removed user to keep no roles\")\n\tuassert.False(t, perms.HasPermission(user, testPermA), \"expect removed user to keep no permissions\")\n\tuassert.Equal(t, 0, len(perms.GetUserRoles(user)))\n\tuassert.Equal(t, 0, perms.UsersCount())\n\tuassert.False(t, perms.RemoveUser(user), \"expect second removal to report user not found\")\n}\n\nfunc TestBasicPermissionsIterateUsers(t *testing.T) {\n\t// Users are listed sorted by address, including a roleless guest.\n\tusers := []boards.User{\n\t\t{\n\t\t\tAddress: \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\",\n\t\t\tRoles:   []boards.Role{\"foo\"},\n\t\t},\n\t\t{\n\t\t\tAddress: \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\",\n\t\t\tRoles:   []boards.Role{\"bar\", \"foo\"},\n\t\t},\n\t\t{\n\t\t\tAddress: \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\",\n\t\t\tRoles:   []boards.Role{\"bar\"},\n\t\t},\n\t\t{\n\t\t\tAddress: \"g1w4ek2u33ta047h6lta047h6lta047h6ldvdwpn\",\n\t\t},\n\t}\n\n\tperms := New()\n\tperms.AddRole(\"foo\", testPermA)\n\tperms.AddRole(\"bar\", testPermB)\n\t// Add users in reverse order to pin that iteration is address-sorted,\n\t// not insertion-ordered.\n\tfor i := len(users) - 1; i \u003e= 0; i-- {\n\t\tperms.SetUserRoles(users[i].Address, users[i].Roles...)\n\t}\n\n\tcases := []struct {\n\t\tname               string\n\t\tstart, count, want int\n\t}{\n\t\t{\n\t\t\tname:  \"exceed users count\",\n\t\t\tcount: 50,\n\t\t\twant:  4,\n\t\t},\n\t\t{\n\t\t\tname:  \"exact users count\",\n\t\t\tcount: 4,\n\t\t\twant:  4,\n\t\t},\n\t\t{\n\t\t\tname:  \"two users\",\n\t\t\tstart: 1,\n\t\t\tcount: 2,\n\t\t\twant:  2,\n\t\t},\n\t\t{\n\t\t\tname:  \"one user\",\n\t\t\tstart: 1,\n\t\t\tcount: 1,\n\t\t\twant:  1,\n\t\t},\n\t\t{\n\t\t\tname:  \"no iteration\",\n\t\t\tstart: 50,\n\t\t\tcount: 1,\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tvar visited int\n\t\t\tstopped := perms.IterateUsers(tc.start, tc.count, func(u boards.User) bool {\n\t\t\t\ti := tc.start + visited\n\t\t\t\turequire.True(t, i \u003c len(users), \"expect iterator to respect number of users\")\n\t\t\t\tuassert.Equal(t, users[i].Address, u.Address)\n\n\t\t\t\turequire.Equal(t, len(users[i].Roles), len(u.Roles), \"expect number of roles to match\")\n\t\t\t\tfor j := range u.Roles {\n\t\t\t\t\tuassert.Equal(t, string(users[i].Roles[j]), string(u.Roles[j]))\n\t\t\t\t}\n\n\t\t\t\tvisited++\n\t\t\t\treturn false\n\t\t\t})\n\n\t\t\tuassert.False(t, stopped, \"expect full iteration not to report an early stop\")\n\t\t\tuassert.Equal(t, tc.want, visited, \"expect iterator to visit the windowed users\")\n\t\t})\n\t}\n\n\t// Early stop is reported, and iteration actually halts.\n\tvar visited int\n\tstopped := perms.IterateUsers(0, 10, func(boards.User) bool {\n\t\tvisited++\n\t\treturn true\n\t})\n\tuassert.True(t, stopped, \"expect early stop to be reported\")\n\tuassert.Equal(t, 1, visited, \"expect iteration to halt on early stop\")\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"Cy2gu9S+1TexuA6CeAL1H+Jxs8e+RbGDSIgl/lx80/wN2Eycb/eph1nrJhWZRsLmSUKQo20ii5eFga3isKhFHA=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"hub","path":"gno.land/p/gnoland/boards/exts/hub","files":[{"name":"README.md","body":"# hub\n\nSimplified, read-only view types over `gno.land/p/gnoland/boards` 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\"\n    hubexts \"gno.land/p/gnoland/boards/exts/hub\"\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\"\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":"board_test.gno","body":"package hub_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\t\"gno.land/p/gnoland/boards/exts/hub\"\n\t\"gno.land/p/gnoland/boards/exts/permissions\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc TestNewSafeBoard(t *testing.T) {\n\ttests := []struct {\n\t\tname                     string\n\t\tsetup                    func() *boards.Board\n\t\tthreadCount, memberCount int\n\t\tcreatedAt                int64\n\t}{\n\t\t{\n\t\t\tname:      \"new board\",\n\t\t\tsetup:     func() *boards.Board { return boards.New(1) },\n\t\t\tcreatedAt: testTime,\n\t\t},\n\t\t{\n\t\t\tname: \"with threads\",\n\t\t\tsetup: func() *boards.Board {\n\t\t\t\tb := boards.New(1)\n\t\t\t\tb.Threads.Add(boards.MustNewThread(b, alice, \"Title 1\", \"Body 1\"))\n\t\t\t\tb.Threads.Add(boards.MustNewThread(b, bob, \"Title 2\", \"Body 2\"))\n\t\t\t\treturn b\n\t\t\t},\n\t\t\tthreadCount: 2,\n\t\t\tcreatedAt:   testTime,\n\t\t},\n\t\t{\n\t\t\tname: \"with members\",\n\t\t\tsetup: func() *boards.Board {\n\t\t\t\tb := boards.New(1)\n\t\t\t\tperms := permissions.New()\n\t\t\t\tperms.SetUserRoles(alice)\n\t\t\t\tperms.SetUserRoles(bob)\n\t\t\t\tb.Permissions = perms\n\t\t\t\treturn b\n\t\t\t},\n\t\t\tmemberCount: 2,\n\t\t\tcreatedAt:   testTime,\n\t\t},\n\t\t{\n\t\t\t// A board with no storages assigned must not panic: the counts\n\t\t\t// are skipped and the zero creation time maps to a zero Unix time.\n\t\t\tname:  \"bare board without storages\",\n\t\t\tsetup: func() *boards.Board { return \u0026boards.Board{ID: 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\tref := tt.setup()\n\t\t\tref.Name = \"test123\"\n\t\t\tref.Creator = alice\n\n\t\t\tboard := hub.NewSafeBoard(ref)\n\n\t\t\turequire.Equal(t, uint64(1), board.ID(), \"expect ID to match\")\n\t\t\turequire.Equal(t, \"test123\", board.Name(), \"expect name to match\")\n\t\t\turequire.Equal(t, alice, board.Creator(), \"expect creator to match\")\n\t\t\turequire.False(t, board.Readonly(), \"expect board not to be readonly\")\n\t\t\turequire.Equal(t, tt.threadCount, board.ThreadCount(), \"expect thread count to match\")\n\t\t\turequire.Equal(t, tt.memberCount, board.MemberCount(), \"expect member count to match\")\n\t\t\turequire.Equal(t, tt.createdAt, board.CreatedAt(), \"expect creation time to match\")\n\t\t\turequire.Equal(t, int64(0), board.UpdatedAt(), \"expect zero update time to map to zero\")\n\t\t})\n\t}\n}\n\n// TestNewSafeBoardSnapshotsAliases asserts the invariant this package exists\n// for: a safe type is a snapshot, so later writes to the source board must not\n// be observable through a value already handed to a caller.\nfunc TestNewSafeBoardSnapshotsAliases(t *testing.T) {\n\tref := boards.New(1)\n\tref.Name = \"current\"\n\tref.Aliases = []string{\"previous\"}\n\n\tboard := hub.NewSafeBoard(ref)\n\n\tref.Aliases[0] = \"mutated\"\n\tref.Aliases = append(ref.Aliases, \"added\")\n\tref.Name = \"renamed\"\n\tref.Readonly = true\n\n\taliases := board.Aliases()\n\turequire.Equal(t, 1, len(aliases), \"expect alias count to be unaffected\")\n\turequire.Equal(t, \"previous\", aliases[0], \"expect alias to be unaffected\")\n\turequire.Equal(t, \"current\", board.Name(), \"expect name to be unaffected\")\n\turequire.False(t, board.Readonly(), \"expect readonly to be unaffected\")\n}\n\nfunc TestNewSafeBoardNilRef(cur realm, t *testing.T) {\n\turequire.PanicsWithMessage(t, cur, \"board reference is nil\", func() {\n\t\thub.NewSafeBoard(nil)\n\t}, \"expect a nil board reference to be rejected\")\n}\n"},{"name":"comment.gno","body":"package hub\n\nimport (\n\t\"gno.land/p/gnoland/boards\"\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":"comment_test.gno","body":"package hub_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\t\"gno.land/p/gnoland/boards/exts/hub\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\n// Addresses and the fixed time the test VM reports for time.Now().\nconst (\n\talice    address = \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"\n\tbob      address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\ttestTime int64   = 1234567890\n)\n\nfunc TestNewSafeComment(t *testing.T) {\n\tboard := boards.New(1)\n\tthread := boards.MustNewThread(board, alice, \"Title\", \"Body\")\n\tref := boards.MustNewReply(thread, bob, \"Comment\")\n\tref.Flags.Add(boards.Flag{User: alice, Reason: \"Spam\"})\n\n\tcomment := hub.NewSafeComment(ref)\n\n\turequire.Equal(t, uint64(ref.ID), comment.ID(), \"expect ID to match\")\n\turequire.Equal(t, uint64(1), comment.BoardID(), \"expect board ID to match\")\n\turequire.Equal(t, uint64(thread.ID), comment.ThreadID(), \"expect thread ID to match\")\n\turequire.Equal(t, \"Comment\", comment.Body(), \"expect body to match\")\n\turequire.Equal(t, bob, comment.Creator(), \"expect creator to match\")\n\turequire.False(t, comment.Hidden(), \"expect comment not to be hidden\")\n\turequire.Equal(t, 0, comment.ReplyCount(), \"expect no replies\")\n\turequire.Equal(t, 1, comment.FlagCount(), \"expect one flag\")\n\turequire.Equal(t, testTime, comment.CreatedAt(), \"expect creation time to match\")\n\turequire.Equal(t, int64(0), comment.UpdatedAt(), \"expect zero update time to map to zero\")\n}\n\n// TestNewSafeCommentParentID documents that a top level comment reports its\n// thread as parent rather than a zero parent, so callers must compare\n// ParentID against ThreadID to tell comments and replies apart.\nfunc TestNewSafeCommentParentID(t *testing.T) {\n\tboard := boards.New(1)\n\tthread := boards.MustNewThread(board, alice, \"Title\", \"Body\")\n\tcommentRef := boards.MustNewReply(thread, bob, \"Comment\")\n\treplyRef := boards.MustNewReply(commentRef, alice, \"Reply\")\n\n\tcomment := hub.NewSafeComment(commentRef)\n\treply := hub.NewSafeComment(replyRef)\n\n\turequire.Equal(t, comment.ThreadID(), comment.ParentID(), \"expect a comment's parent to be its thread\")\n\turequire.Equal(t, comment.ID(), reply.ParentID(), \"expect a reply's parent to be its comment\")\n\turequire.Equal(t, comment.ThreadID(), reply.ThreadID(), \"expect a reply to keep the thread ID\")\n}\n\nfunc TestNewSafeCommentReplyCount(t *testing.T) {\n\tboard := boards.New(1)\n\tthread := boards.MustNewThread(board, alice, \"Title\", \"Body\")\n\tref := boards.MustNewReply(thread, bob, \"Comment\")\n\tref.Replies.Add(boards.MustNewReply(ref, alice, \"Reply 1\"))\n\tref.Replies.Add(boards.MustNewReply(ref, alice, \"Reply 2\"))\n\n\tcomment := hub.NewSafeComment(ref)\n\n\turequire.Equal(t, 2, comment.ReplyCount(), \"expect reply count to match\")\n}\n\n// TestNewSafeCommentNilStorages covers the branches that skip counting when a\n// post carries no reply or flag storage.\nfunc TestNewSafeCommentNilStorages(t *testing.T) {\n\tref := \u0026boards.Post{ID: 2, ParentID: 1, ThreadID: 1, Board: boards.New(1)}\n\n\tcomment := hub.NewSafeComment(ref)\n\n\turequire.Equal(t, 0, comment.ReplyCount(), \"expect no replies\")\n\turequire.Equal(t, 0, comment.FlagCount(), \"expect no flags\")\n\turequire.Equal(t, int64(0), comment.CreatedAt(), \"expect zero creation time to map to zero\")\n}\n\nfunc TestNewSafeCommentRejectsInvalidRefs(cur realm, t *testing.T) {\n\tboard := boards.New(1)\n\tthread := boards.MustNewThread(board, alice, \"Title\", \"Body\")\n\n\turequire.PanicsWithMessage(t, cur, \"post reference is nil\", func() {\n\t\thub.NewSafeComment(nil)\n\t}, \"expect a nil post reference to be rejected\")\n\n\turequire.PanicsWithMessage(t, cur, \"post is not a comment or reply\", func() {\n\t\thub.NewSafeComment(thread)\n\t}, \"expect a thread to be rejected\")\n}\n"},{"name":"flag.gno","body":"package hub\n\nimport (\n\t\"gno.land/p/gnoland/boards\"\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\"\ngno = \"0.9\"\n"},{"name":"member.gno","body":"package hub\n\nimport (\n\t\"gno.land/p/gnoland/boards\"\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":"member_test.gno","body":"package hub_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\t\"gno.land/p/gnoland/boards/exts/hub\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc TestNewSafeMember(t *testing.T) {\n\tref := boards.User{\n\t\tAddress: alice,\n\t\tRoles:   []boards.Role{\"owner\", \"admin\"},\n\t}\n\n\tmember := hub.NewSafeMember(ref)\n\n\turequire.Equal(t, alice.String(), member.Address().String(), \"expect address to match\")\n\turequire.Equal(t, 2, len(member.Roles()), \"expect role count to match\")\n\turequire.Equal(t, \"owner\", member.Roles()[0], \"expect first role to match\")\n\turequire.Equal(t, \"admin\", member.Roles()[1], \"expect second role to match\")\n}\n\nfunc TestNewSafeMemberWithoutRoles(t *testing.T) {\n\tmember := hub.NewSafeMember(boards.User{Address: bob})\n\n\turequire.Equal(t, bob.String(), member.Address().String(), \"expect address to match\")\n\turequire.Equal(t, 0, len(member.Roles()), \"expect no roles\")\n}\n\nfunc TestSafeMemberIsASnapshot(t *testing.T) {\n\troles := []boards.Role{\"owner\"}\n\tmember := hub.NewSafeMember(boards.User{Address: alice, Roles: roles})\n\n\t// Mutating the source must not change what the member reports.\n\troles[0] = \"guest\"\n\turequire.Equal(t, \"owner\", member.Roles()[0], \"expect source mutation to be ignored\")\n\n\t// Mutating a returned slice must not change what the member reports.\n\tmember.Roles()[0] = \"guest\"\n\turequire.Equal(t, \"owner\", member.Roles()[0], \"expect returned slice to be a copy\")\n}\n"},{"name":"thread.gno","body":"package hub\n\nimport (\n\t\"gno.land/p/gnoland/boards\"\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"},{"name":"thread_test.gno","body":"package hub_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\t\"gno.land/p/gnoland/boards/exts/hub\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc TestNewSafeThread(t *testing.T) {\n\tboard := boards.New(1)\n\tref := boards.MustNewThread(board, alice, \"Title\", \"Body\")\n\tref.Flags.Add(boards.Flag{User: bob, Reason: \"Spam\"})\n\n\tthread := hub.NewSafeThread(ref)\n\n\turequire.Equal(t, uint64(ref.ID), thread.ID(), \"expect ID to match\")\n\turequire.Equal(t, uint64(1), thread.BoardID(), \"expect board ID to match\")\n\turequire.Equal(t, \"Title\", thread.Title(), \"expect title to match\")\n\turequire.Equal(t, \"Body\", thread.Body(), \"expect body to match\")\n\turequire.Equal(t, alice, thread.Creator(), \"expect creator to match\")\n\turequire.False(t, thread.Hidden(), \"expect thread not to be hidden\")\n\turequire.False(t, thread.Readonly(), \"expect thread not to be readonly\")\n\turequire.Equal(t, 0, thread.CommentCount(), \"expect no comments\")\n\turequire.Equal(t, 0, thread.RepostCount(), \"expect no reposts\")\n\turequire.Equal(t, 1, thread.FlagCount(), \"expect one flag\")\n\turequire.Equal(t, testTime, thread.CreatedAt(), \"expect creation time to match\")\n\turequire.Equal(t, int64(0), thread.UpdatedAt(), \"expect zero update time to map to zero\")\n}\n\nfunc TestNewSafeThreadCounts(t *testing.T) {\n\tboard := boards.New(1)\n\tref := boards.MustNewThread(board, alice, \"Title\", \"Body\")\n\tref.Replies.Add(boards.MustNewReply(ref, bob, \"Comment 1\"))\n\tref.Replies.Add(boards.MustNewReply(ref, bob, \"Comment 2\"))\n\n\tthread := hub.NewSafeThread(ref)\n\n\turequire.Equal(t, 2, thread.CommentCount(), \"expect comment count to match\")\n\turequire.Equal(t, 0, thread.FlagCount(), \"expect no flags\")\n}\n\n// TestNewSafeThreadNilStorages covers the branches that skip counting when a\n// post carries no reply, repost or flag storage.\nfunc TestNewSafeThreadNilStorages(t *testing.T) {\n\tref := \u0026boards.Post{ID: 1, ThreadID: 1, Board: boards.New(1)}\n\n\tthread := hub.NewSafeThread(ref)\n\n\turequire.Equal(t, 0, thread.CommentCount(), \"expect no comments\")\n\turequire.Equal(t, 0, thread.RepostCount(), \"expect no reposts\")\n\turequire.Equal(t, 0, thread.FlagCount(), \"expect no flags\")\n\turequire.Equal(t, int64(0), thread.CreatedAt(), \"expect zero creation time to map to zero\")\n}\n\nfunc TestNewSafeThreadRejectsInvalidRefs(cur realm, t *testing.T) {\n\tboard := boards.New(1)\n\tthread := boards.MustNewThread(board, alice, \"Title\", \"Body\")\n\tcomment := boards.MustNewReply(thread, alice, \"Comment\")\n\n\turequire.PanicsWithMessage(t, cur, \"post reference is nil\", func() {\n\t\thub.NewSafeThread(nil)\n\t}, \"expect a nil post reference to be rejected\")\n\n\turequire.PanicsWithMessage(t, cur, \"post is not a thread\", func() {\n\t\thub.NewSafeThread(comment)\n\t}, \"expect a comment to be rejected\")\n}\n\nfunc TestNewSafeFlag(t *testing.T) {\n\tflag := hub.NewSafeFlag(boards.Flag{User: alice, Reason: \"Spam\"})\n\n\turequire.Equal(t, alice, flag.User(), \"expect user to match\")\n\turequire.Equal(t, \"Spam\", flag.Reason(), \"expect reason to match\")\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"vmUEE8/x8OXdRu8DoxRcAHt6tOELbEB6LoHGf9VIiOcY6rIx0lE2Uc99gWZpDCx/M5Z3fRxMMK2S7Ye61cC2wA=="}],"memo":""}},{"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":"allowancesender_test.gno","body":"package allowancesender\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\n// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\n\n// mockBanker implements banker.Banker for unit testing without\n// touching real bank state. Records every SendCoins call.\n//\n// Since the public New constructor rejects non-canonical bankers via\n// banker.IsCanonical, mockBanker cannot flow through New. Tests that\n// need a controllable mock build the AllowanceSender via newWithMock,\n// which uses in-package struct-literal construction. Same-package\n// authorship is the trust boundary; the public API remains unforgeable\n// to other packages.\ntype mockBanker struct {\n\tsends    []sendCall\n\tfailNext bool   // if true, next SendCoins panics\n\tfailMsg  string // panic message for failNext\n}\n\ntype sendCall struct {\n\tfrom, to address\n\tamt      chain.Coins\n}\n\nfunc (m *mockBanker) GetCoins(addr address) chain.Coins        { return nil }\nfunc (m *mockBanker) GetCoin(addr address, denom string) int64 { return 0 }\nfunc (m *mockBanker) SendCoins(from, to address, amt chain.Coins) {\n\tif m.failNext {\n\t\tm.failNext = false\n\t\tpanic(m.failMsg)\n\t}\n\tm.sends = append(m.sends, sendCall{from, to, amt})\n}\nfunc (m *mockBanker) TotalCoin(denom string) int64                        { return 0 }\nfunc (m *mockBanker) IssueCoin(addr address, denom string, amount int64)  {}\nfunc (m *mockBanker) RemoveCoin(addr address, denom string, amount int64) {}\n\n// newWithMock constructs an *AllowanceSender wrapping a mockBanker via\n// struct-literal initialization, bypassing New (which would reject the\n// mock as non-canonical). Used only in this test file.\nfunc newWithMock(mb *mockBanker, p address, limit chain.Coins) *AllowanceSender {\n\treturn \u0026AllowanceSender{\n\t\tinner: mb,\n\t\tpayer: p,\n\t\tlimit: limit,\n\t}\n}\n\nvar (\n\tpayer = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\tbob   = address(\"g1mtmrdmqfu0aryqfl4aw65n35haw2wdjkh5p4cp\")\n\tcarol = address(\"g16dverxg6s6vzha89k22c3zusx6sug5ycjyjq2j\")\n)\n\n// ---------------------------------------------------------------------\n// Constructor tests\n// ---------------------------------------------------------------------\n\nfunc TestNew_Valid(t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tlimit := chain.NewCoins(chain.NewCoin(\"ugnot\", 1000))\n\tal := newWithMock(mb, payer, limit)\n\n\tuassert.Equal(t, false, al.Closed())\n\tuassert.Equal(t, payer.String(), al.Payer().String())\n\tuassert.Equal(t, limit.String(), al.Cap().String())\n}\n\nfunc TestNew_NonCanonicalBanker(cur realm, t *testing.T) {\n\t// A hand-rolled banker.Banker (mockBanker) is not the canonical\n\t// chain/banker.Banker; New must reject it. This is the security\n\t// hole the IsCanonical gate closes — without it, a malicious caller\n\t// could pass a no-op banker and cause AllowanceSender.Send to\n\t// silently succeed without moving real coins.\n\tmb := \u0026mockBanker{}\n\tuassert.PanicsWithMessage(t, cur,\n\t\t\"allowancesender: inner banker is not the canonical chain/banker.Banker\",\n\t\tfunc() {\n\t\t\tNew(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 1)))\n\t\t})\n}\n\nfunc TestNew_NilInner(cur realm, t *testing.T) {\n\t// Nil also fails IsCanonical (nil interface assertion is false).\n\tuassert.PanicsWithMessage(t, cur,\n\t\t\"allowancesender: inner banker is not the canonical chain/banker.Banker\",\n\t\tfunc() {\n\t\t\tNew(nil, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 1)))\n\t\t})\n}\n\nfunc TestNew_EmptyCap(t *testing.T) {\n\t// Empty cap is valid at construction (every Send will panic with\n\t// \"cap exceeded\"). Useful for \"preallocated zero-allowance\" cases.\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.Coins{})\n\tuassert.Equal(t, false, al.Closed())\n}\n\n// ---------------------------------------------------------------------\n// Send happy-path tests\n// ---------------------------------------------------------------------\n\nfunc TestSend_WithinCap(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\n\turequire.NotPanics(t, cur, func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 400)))\n\t})\n\n\tuassert.Equal(t, 1, len(mb.sends))\n\tuassert.Equal(t, payer.String(), mb.sends[0].from.String())\n\tuassert.Equal(t, bob.String(), mb.sends[0].to.String())\n\tuassert.Equal(t, int64(400), mb.sends[0].amt.AmountOf(\"ugnot\"))\n}\n\nfunc TestSend_MultipleWithinCap(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\n\turequire.NotPanics(t, cur, func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 300)))\n\t})\n\turequire.NotPanics(t, cur, func() {\n\t\tal.Send(carol, chain.NewCoins(chain.NewCoin(\"ugnot\", 600)))\n\t})\n\n\tuassert.Equal(t, 2, len(mb.sends))\n\tuassert.Equal(t, int64(900), al.Spent().AmountOf(\"ugnot\"))\n\tuassert.Equal(t, int64(100), al.Remaining().AmountOf(\"ugnot\"))\n}\n\nfunc TestSend_ExactlyAtCap(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\n\turequire.NotPanics(t, cur, func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\t})\n\tuassert.Equal(t, int64(1000), al.Spent().AmountOf(\"ugnot\"))\n\tuassert.Equal(t, 0, len(al.Remaining()))\n}\n\n// ---------------------------------------------------------------------\n// Send rejection tests\n// ---------------------------------------------------------------------\n\nfunc TestSend_ExceedsCapInOneCall(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\n\tuassert.PanicsWithMessage(t, cur, \"allowancesender: cap exceeded for denom ugnot\", func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 1001)))\n\t})\n\t// State must not change on rejection.\n\tuassert.Equal(t, 0, len(mb.sends))\n\tuassert.Equal(t, int64(0), al.Spent().AmountOf(\"ugnot\"))\n}\n\nfunc TestSend_ExceedsCapAcrossCalls(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\n\turequire.NotPanics(t, cur, func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 700)))\n\t})\n\tuassert.PanicsWithMessage(t, cur, \"allowancesender: cap exceeded for denom ugnot\", func() {\n\t\tal.Send(carol, chain.NewCoins(chain.NewCoin(\"ugnot\", 400)))\n\t})\n\t// First send happened, second didn't.\n\tuassert.Equal(t, 1, len(mb.sends))\n\tuassert.Equal(t, int64(700), al.Spent().AmountOf(\"ugnot\"))\n}\n\nfunc TestSend_DenomNotInCap(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\n\t// \"atom\" is not in cap; capAmt=0; any positive amount panics.\n\tuassert.PanicsWithMessage(t, cur, \"allowancesender: cap exceeded for denom atom\", func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"atom\", 1)))\n\t})\n}\n\nfunc TestSend_ZeroCap(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.Coins{}) // empty cap\n\n\tuassert.PanicsWithMessage(t, cur, \"allowancesender: cap exceeded for denom ugnot\", func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 1)))\n\t})\n}\n\nfunc TestSend_AfterClose(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\n\tal.Close()\n\tuassert.True(t, al.Closed())\n\n\tuassert.PanicsWithMessage(t, cur, \"allowancesender: closed\", func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 100)))\n\t})\n\tuassert.Equal(t, 0, len(mb.sends))\n}\n\n// ---------------------------------------------------------------------\n// Multi-denom tests\n// ---------------------------------------------------------------------\n\nfunc TestSend_MultiDenomCap(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.NewCoins(\n\t\tchain.NewCoin(\"ugnot\", 1000),\n\t\tchain.NewCoin(\"foo\", 50),\n\t))\n\n\t// Spend on both denoms within their caps.\n\turequire.NotPanics(t, cur, func() {\n\t\tal.Send(bob, chain.NewCoins(\n\t\t\tchain.NewCoin(\"ugnot\", 600),\n\t\t\tchain.NewCoin(\"foo\", 30),\n\t\t))\n\t})\n\n\tuassert.Equal(t, int64(600), al.Spent().AmountOf(\"ugnot\"))\n\tuassert.Equal(t, int64(30), al.Spent().AmountOf(\"foo\"))\n\n\trem := al.Remaining()\n\tuassert.Equal(t, int64(400), rem.AmountOf(\"ugnot\"))\n\tuassert.Equal(t, int64(20), rem.AmountOf(\"foo\"))\n}\n\nfunc TestSend_OneDenomExceedsBlocksAll(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.NewCoins(\n\t\tchain.NewCoin(\"ugnot\", 1000),\n\t\tchain.NewCoin(\"foo\", 50),\n\t))\n\n\t// foo would exceed (51 \u003e 50); whole send rejected, ugnot doesn't go through.\n\tuassert.PanicsWithMessage(t, cur, \"allowancesender: cap exceeded for denom foo\", func() {\n\t\tal.Send(bob, chain.NewCoins(\n\t\t\tchain.NewCoin(\"ugnot\", 100),\n\t\t\tchain.NewCoin(\"foo\", 51),\n\t\t))\n\t})\n\n\t// Neither denom should have been spent.\n\tuassert.Equal(t, int64(0), al.Spent().AmountOf(\"ugnot\"))\n\tuassert.Equal(t, int64(0), al.Spent().AmountOf(\"foo\"))\n\tuassert.Equal(t, 0, len(mb.sends))\n}\n\n// ---------------------------------------------------------------------\n// Close behavior\n// ---------------------------------------------------------------------\n\nfunc TestClose_Idempotent(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\n\tal.Close()\n\turequire.NotPanics(t, cur, func() { al.Close() })\n\turequire.NotPanics(t, cur, func() { al.Close() })\n\tuassert.True(t, al.Closed())\n}\n\nfunc TestClose_DoesNotInterfereWithReadMethods(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tlimit := chain.NewCoins(chain.NewCoin(\"ugnot\", 1000))\n\tal := newWithMock(mb, payer, limit)\n\n\turequire.NotPanics(t, cur, func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 250)))\n\t})\n\tal.Close()\n\n\t// Read methods must keep working after close.\n\tuassert.Equal(t, limit.String(), al.Cap().String())\n\tuassert.Equal(t, int64(250), al.Spent().AmountOf(\"ugnot\"))\n\tuassert.Equal(t, int64(750), al.Remaining().AmountOf(\"ugnot\"))\n\tuassert.True(t, al.Closed())\n}\n\n// ---------------------------------------------------------------------\n// Inner-banker panic tests\n// ---------------------------------------------------------------------\n\nfunc TestSend_InnerPanicRollsBackSpent(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{failNext: true, failMsg: \"insufficient funds\"}\n\tal := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\n\tuassert.PanicsWithMessage(t, cur, \"insufficient funds\", func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 500)))\n\t})\n\n\t// On inner panic, spent must be rolled back.\n\tuassert.Equal(t, int64(0), al.Spent().AmountOf(\"ugnot\"))\n\tuassert.Equal(t, int64(1000), al.Remaining().AmountOf(\"ugnot\"))\n\n\t// And subsequent valid Send still works.\n\turequire.NotPanics(t, cur, func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 200)))\n\t})\n\tuassert.Equal(t, int64(200), al.Spent().AmountOf(\"ugnot\"))\n}\n\n// ---------------------------------------------------------------------\n// Remaining / Spent edge cases\n// ---------------------------------------------------------------------\n\nfunc TestRemaining_EmptyCap(t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.Coins{})\n\n\tuassert.Equal(t, 0, len(al.Remaining()))\n}\n\nfunc TestRemaining_FullySpent(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 100)))\n\n\turequire.NotPanics(t, cur, func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 100)))\n\t})\n\tuassert.Equal(t, 0, len(al.Remaining()))\n}\n\nfunc TestRemaining_PartialAcrossDenoms(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.NewCoins(\n\t\tchain.NewCoin(\"ugnot\", 1000),\n\t\tchain.NewCoin(\"foo\", 50),\n\t))\n\n\t// Spend all of foo, half of ugnot.\n\turequire.NotPanics(t, cur, func() {\n\t\tal.Send(bob, chain.NewCoins(\n\t\t\tchain.NewCoin(\"ugnot\", 500),\n\t\t\tchain.NewCoin(\"foo\", 50),\n\t\t))\n\t})\n\n\trem := al.Remaining()\n\t// foo should be omitted (zero remainder); ugnot has 500 left.\n\tuassert.Equal(t, 1, len(rem))\n\tuassert.Equal(t, int64(500), rem.AmountOf(\"ugnot\"))\n\tuassert.Equal(t, int64(0), rem.AmountOf(\"foo\"))\n}\n\n// ---------------------------------------------------------------------\n// Pointer semantics: shared state across copies\n// ---------------------------------------------------------------------\n\nfunc TestPointerSemantics_CloseVisibleViaAlias(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\n\t// Aliasing the pointer should share state.\n\talias := al\n\turequire.NotPanics(t, cur, func() {\n\t\talias.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 100)))\n\t})\n\tuassert.Equal(t, int64(100), al.Spent().AmountOf(\"ugnot\"))\n\n\t// Close via either reference.\n\talias.Close()\n\tuassert.True(t, al.Closed())\n\tuassert.True(t, alias.Closed())\n\n\tuassert.PanicsWithMessage(t, cur, \"allowancesender: closed\", func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 1)))\n\t})\n}\n\n// ---------------------------------------------------------------------\n// Defensive copy: mutating returned Coins must not leak into state\n// ---------------------------------------------------------------------\n\nfunc TestCap_ReturnsDefensiveCopy(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\n\t// Mutate the returned cap; internal state must not change.\n\tgot := al.Cap()\n\tif len(got) \u003e 0 {\n\t\tgot[0].Amount = 9_999_999_999\n\t}\n\n\t// Confirm internal state intact: re-read Cap.\n\tagain := al.Cap()\n\tuassert.Equal(t, int64(1000), again.AmountOf(\"ugnot\"))\n\n\t// Confirm enforcement still works: 1001 should still be rejected.\n\tuassert.PanicsWithMessage(t, cur, \"allowancesender: cap exceeded for denom ugnot\", func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 1001)))\n\t})\n}\n\nfunc TestSpent_ReturnsDefensiveCopy(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\n\turequire.NotPanics(t, cur, func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 300)))\n\t})\n\n\tgot := al.Spent()\n\tif len(got) \u003e 0 {\n\t\tgot[0].Amount = 0 // try to \"rewind\" spent\n\t}\n\n\t// Internal spent must remain accurate.\n\tuassert.Equal(t, int64(300), al.Spent().AmountOf(\"ugnot\"))\n\tuassert.Equal(t, int64(700), al.Remaining().AmountOf(\"ugnot\"))\n}\n\n// ---------------------------------------------------------------------\n// Independence of separate AllowanceSenders\n// ---------------------------------------------------------------------\n\nfunc TestMultipleAllowances_Independent(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\ta1 := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 100)))\n\ta2 := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 200)))\n\n\turequire.NotPanics(t, cur, func() {\n\t\ta1.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 80)))\n\t})\n\turequire.NotPanics(t, cur, func() {\n\t\ta2.Send(carol, chain.NewCoins(chain.NewCoin(\"ugnot\", 150)))\n\t})\n\n\tuassert.Equal(t, int64(80), a1.Spent().AmountOf(\"ugnot\"))\n\tuassert.Equal(t, int64(150), a2.Spent().AmountOf(\"ugnot\"))\n\n\t// Closing one must not close the other.\n\ta1.Close()\n\tuassert.True(t, a1.Closed())\n\tuassert.False(t, a2.Closed())\n\n\turequire.NotPanics(t, cur, func() {\n\t\ta2.Send(carol, chain.NewCoins(chain.NewCoin(\"ugnot\", 50)))\n\t})\n\tuassert.PanicsWithMessage(t, cur, \"allowancesender: closed\", func() {\n\t\ta1.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 1)))\n\t})\n}\n\n// ---------------------------------------------------------------------\n// Overflow / negative-amount adversarial inputs\n// ---------------------------------------------------------------------\n\n// Adversary attempts to bypass the cap check by passing a value that\n// overflows int64 when added to an existing spent counter. Must panic\n// with the overflow-specific message rather than silently wrapping\n// (which would let the cap check pass and allow an absurd send).\nfunc TestSend_OverflowAttempt(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tconst maxInt64 = int64(9223372036854775807)\n\tal := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", maxInt64)))\n\n\t// First spend uses most of the cap.\n\turequire.NotPanics(t, cur, func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", maxInt64-100)))\n\t})\n\n\t// Now spent ≈ MaxInt64 - 100. An adversary tries to pass amount\n\t// 200, which would overflow when added to spent. Must panic with\n\t// \"amount overflow\", not silently wrap to negative and bypass cap.\n\tuassert.PanicsWithMessage(t, cur, \"allowancesender: amount overflow on spent+amt for denom ugnot\", func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 200)))\n\t})\n\n\t// State must not have changed.\n\tuassert.Equal(t, maxInt64-100, al.Spent().AmountOf(\"ugnot\"))\n\t// Bank-side recorded only the first valid send.\n\tuassert.Equal(t, 1, len(mb.sends))\n}\n\nfunc TestSend_NegativeAmount(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\n\t// Spend something so we have a non-zero spent.\n\turequire.NotPanics(t, cur, func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 200)))\n\t})\n\n\t// Adversary tries to \"uncharge\" the allowance by passing a negative\n\t// amount. Without this guard, spent would decrease, allowing more\n\t// future spends than originally permitted.\n\tuassert.PanicsWithMessage(t, cur, \"allowancesender: negative amount not allowed for denom ugnot\", func() {\n\t\tal.Send(bob, chain.Coins{chain.Coin{Denom: \"ugnot\", Amount: -50}})\n\t})\n\n\t// Spent is unchanged after the rejected attempt.\n\tuassert.Equal(t, int64(200), al.Spent().AmountOf(\"ugnot\"))\n}\n\n// Adversary's defer-recover swallows the panic from inner.SendCoins to\n// hide a failed send. Verifies that even with recovery, spent has been\n// rolled back — i.e., a recovered panic doesn't burn allowance against\n// a transfer that never moved funds.\nfunc TestSend_RecoveredPanicDoesNotBurnAllowance(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{failNext: true, failMsg: \"insufficient funds\"}\n\tal := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\n\t// Caller deliberately recovers from the inner panic.\n\tfunc() {\n\t\tdefer func() {\n\t\t\t_ = recover() // swallow\n\t\t}()\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 500)))\n\t}()\n\n\t// After the recovered panic: spent must be 0 (no funds moved →\n\t// allowance must not be charged).\n\tuassert.Equal(t, int64(0), al.Spent().AmountOf(\"ugnot\"))\n\tuassert.Equal(t, int64(1000), al.Remaining().AmountOf(\"ugnot\"))\n\n\t// And subsequent valid Send (with non-failing inner) succeeds with\n\t// full cap available.\n\turequire.NotPanics(t, cur, func() {\n\t\tal.Send(bob, chain.NewCoins(chain.NewCoin(\"ugnot\", 800)))\n\t})\n\tuassert.Equal(t, int64(800), al.Spent().AmountOf(\"ugnot\"))\n}\n\n// ---------------------------------------------------------------------\n// Empty/zero-amount edge cases\n// ---------------------------------------------------------------------\n\nfunc TestSend_EmptyAmt(cur realm, t *testing.T) {\n\tmb := \u0026mockBanker{}\n\tal := newWithMock(mb, payer, chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\n\t// Sending zero coins should not panic; just no-op forwards to inner.\n\turequire.NotPanics(t, cur, func() {\n\t\tal.Send(bob, chain.Coins{})\n\t})\n\n\t// inner.SendCoins was still called (the wrapper doesn't filter\n\t// zero sends; that's the inner banker's choice). State unchanged.\n\tuassert.Equal(t, int64(0), al.Spent().AmountOf(\"ugnot\"))\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/jaekwon/allowancesender/v0\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"8NgOB2UKmCUCPh8OVy7H3LW64Lrz+LSOJoepE05sIvNNABnK7oi8UDS8BkNRC9KZ8D7mMLPcWbBvKjDiiZUuLg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"avlhelpers","path":"gno.land/p/jefft0/avlhelpers","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":"example_test.gno","body":"package avlhelpers\n\nimport (\n\t\"encoding/hex\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nfunc ExampleTextMatch() {\n\ttree := avl.NewTree()\n\n\t{\n\t\t// Empty tree.\n\t\tmatches := ListByteStringKeysByPrefix(tree, \"\", 10)\n\t\tprintln(ufmt.Sprintf(\"# matches: %d\", len(matches)))\n\t}\n\n\ttree.Set(\"alice\", \"\")\n\ttree.Set(\"andy\", \"\")\n\ttree.Set(\"bob\", \"\")\n\n\t{\n\t\t// Match only alice.\n\t\tmatches := ListByteStringKeysByPrefix(tree, \"al\", 10)\n\t\tprintln(ufmt.Sprintf(\"# matches: %d\", len(matches)))\n\t\tprintln(\"match: \" + matches[0])\n\t}\n\n\t{\n\t\t// Match alice and andy.\n\t\tmatches := ListByteStringKeysByPrefix(tree, \"a\", 10)\n\t\tprintln(ufmt.Sprintf(\"# matches: %d\", len(matches)))\n\t\tprintln(\"match: \" + matches[0])\n\t\tprintln(\"match: \" + matches[1])\n\t}\n\n\t{\n\t\t// Match alice and andy limited to 1.\n\t\tmatches := ListByteStringKeysByPrefix(tree, \"a\", 1)\n\t\tprintln(ufmt.Sprintf(\"# matches: %d\", len(matches)))\n\t\tprintln(\"match: \" + matches[0])\n\t}\n\n\t// Output:\n\t// # matches: 0\n\t// # matches: 1\n\t// match: alice\n\t// # matches: 2\n\t// match: alice\n\t// match: andy\n\t// # matches: 1\n\t// match: alice\n}\n\nfunc ExampleBinaryMatch() {\n\ttree := avl.NewTree()\n\ttree.Set(\"a\\xff\", \"\")\n\ttree.Set(\"a\\xff\\xff\", \"\")\n\ttree.Set(\"b\", \"\")\n\ttree.Set(\"\\xff\\xff\\x00\", \"\")\n\n\t{\n\t\t// Match only \"a\\xff\\xff\".\n\t\tmatches := ListByteStringKeysByPrefix(tree, \"a\\xff\\xff\", 10)\n\t\tprintln(ufmt.Sprintf(\"# matches: %d\", len(matches)))\n\t\tprintln(ufmt.Sprintf(\"match: %s\", hex.EncodeToString([]byte(matches[0]))))\n\t}\n\n\t{\n\t\t// Match \"a\\xff\" and \"a\\xff\\xff\".\n\t\tmatches := ListByteStringKeysByPrefix(tree, \"a\\xff\", 10)\n\t\tprintln(ufmt.Sprintf(\"# matches: %d\", len(matches)))\n\t\tprintln(ufmt.Sprintf(\"match: %s\", hex.EncodeToString([]byte(matches[0]))))\n\t\tprintln(ufmt.Sprintf(\"match: %s\", hex.EncodeToString([]byte(matches[1]))))\n\t}\n\n\t{\n\t\t// Edge case: Match only \"\\xff\\xff\\x00\".\n\t\tmatches := ListByteStringKeysByPrefix(tree, \"\\xff\\xff\", 10)\n\t\tprintln(ufmt.Sprintf(\"# matches: %d\", len(matches)))\n\t\tprintln(ufmt.Sprintf(\"match: %s\", hex.EncodeToString([]byte(matches[0]))))\n\t}\n\n\t// Output:\n\t// # matches: 1\n\t// match: 61ffff\n\t// # matches: 2\n\t// match: 61ff\n\t// match: 61ffff\n\t// # matches: 1\n\t// match: ffff00\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/jefft0/avlhelpers\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"/0n9MWoFJDvCvIHPdPTxXd5QFIE11NB9kyguae5hPn9fx8juBaCiT+H1VPLrrB0IEyJDXQPvghL02/4xFQsjTQ=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"expect","path":"gno.land/p/jeronimoalbi/expect","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":"boolean_test.gno","body":"package expect_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nfunc TestBooleanChecker(t *testing.T) {\n\tt.Run(\"to be truthy\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewBooleanChecker(ctx, true).ToBeTruthy()\n\t})\n\n\tt.Run(\"not to be truthy\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewBooleanChecker(ctx, false).Not().ToBeTruthy()\n\t})\n\n\tt.Run(\"to be falsy\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewBooleanChecker(ctx, false).ToBeFalsy()\n\t})\n\n\tt.Run(\"not to be falsy\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewBooleanChecker(ctx, true).Not().ToBeFalsy()\n\t})\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":"float_test.gno","body":"package expect_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nfunc TestFloatChecker(t *testing.T) {\n\tt.Run(\"to equal\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewFloatChecker(ctx, 1.2).ToEqual(1.2)\n\t})\n\n\tt.Run(\"not to equal\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewFloatChecker(ctx, 1.2).Not().ToEqual(3.4)\n\t})\n\n\tt.Run(\"to be greater than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewFloatChecker(ctx, 1.2).ToBeGreaterThan(1)\n\t})\n\n\tt.Run(\"not to be greater than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewFloatChecker(ctx, 1.2).Not().ToBeGreaterThan(1.3)\n\t})\n\n\tt.Run(\"to be greater or equal than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewFloatChecker(ctx, 1.2).ToBeGreaterOrEqualThan(1.2)\n\t\texpect.NewFloatChecker(ctx, 1.2).ToBeGreaterOrEqualThan(1.1)\n\t})\n\n\tt.Run(\"not to be greater or equal than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewFloatChecker(ctx, 1.2).Not().ToBeGreaterOrEqualThan(1.3)\n\t})\n\n\tt.Run(\"to be lower than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewFloatChecker(ctx, 1.2).ToBeLowerThan(1.3)\n\t})\n\n\tt.Run(\"not to be lower than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewFloatChecker(ctx, 1.2).Not().ToBeLowerThan(1)\n\t})\n\n\tt.Run(\"to be lower or equal than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewFloatChecker(ctx, 1.2).ToBeLowerOrEqualThan(1.2)\n\t\texpect.NewFloatChecker(ctx, 1.2).ToBeLowerOrEqualThan(1.3)\n\t})\n\n\tt.Run(\"not to be lower or equal than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewFloatChecker(ctx, 1.2).Not().ToBeLowerOrEqualThan(1.1)\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":"func_test.gno","body":"package expect_test\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nfunc TestFunction(t *testing.T) {\n\tt.Run(\"not to fail\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Func(t, func() error {\n\t\t\treturn nil\n\t\t}).Not().ToFail()\n\t})\n\n\tt.Run(\"to fail\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Func(t, func() error {\n\t\t\treturn errors.New(\"Foo\")\n\t\t}).ToFail()\n\t})\n\n\tt.Run(\"to fail with mesasge\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Func(t, func() error {\n\t\t\treturn errors.New(\"Foo\")\n\t\t}).ToFail().WithMessage(\"Foo\")\n\t})\n\n\tt.Run(\"to fail with different message\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Func(t, func() error {\n\t\t\treturn errors.New(\"Bar\")\n\t\t}).ToFail().Not().WithMessage(\"Foo\")\n\t})\n\n\tt.Run(\"to fail with error\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Func(t, func() error {\n\t\t\treturn errors.New(\"Foo\")\n\t\t}).ToFail().WithError(errors.New(\"Foo\"))\n\t})\n\n\tt.Run(\"to fail with different error\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Func(t, func() error {\n\t\t\treturn errors.New(\"Bar\")\n\t\t}).ToFail().Not().WithError(errors.New(\"Foo\"))\n\t})\n\n\tt.Run(\"not to panic\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Func(t, func() error {\n\t\t\treturn nil\n\t\t}).Not().ToPanic()\n\t})\n\n\tt.Run(\"to panic\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Func(t, func() error {\n\t\t\tpanic(\"Foo\")\n\t\t}).ToPanic()\n\t})\n\n\tt.Run(\"to panic with message\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Func(t, func() error {\n\t\t\tpanic(\"Foo\")\n\t\t}).ToPanic().WithMessage(\"Foo\")\n\t})\n\n\tt.Run(\"to panich with different message\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Func(t, func() error {\n\t\t\tpanic(\"Foo\")\n\t\t}).ToPanic().Not().WithMessage(\"Bar\")\n\t})\n\n\tt.Run(\"to return value\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Func(t, func() any {\n\t\t\treturn \"foo\"\n\t\t}).ToReturn(\"foo\")\n\n\t\texpect.Func(t, func() (any, error) {\n\t\t\treturn \"foo\", nil\n\t\t}).ToReturn(\"foo\")\n\t})\n\n\tt.Run(\"not to return value\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Func(t, func() any {\n\t\t\treturn \"foo\"\n\t\t}).Not().ToReturn(\"bar\")\n\n\t\texpect.Func(t, func() (any, error) {\n\t\t\treturn \"foo\", nil\n\t\t}).Not().ToReturn(\"bar\")\n\t})\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/jeronimoalbi/expect\"\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":"int_test.gno","body":"package expect_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nfunc TestIntChecker(t *testing.T) {\n\tt.Run(\"to equal\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewIntChecker(ctx, 1).ToEqual(1)\n\t})\n\n\tt.Run(\"not to equal\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewIntChecker(ctx, 1).Not().ToEqual(2)\n\t})\n\n\tt.Run(\"to be greater than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewIntChecker(ctx, 2).ToBeGreaterThan(1)\n\t})\n\n\tt.Run(\"not to be greater than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewIntChecker(ctx, 1).Not().ToBeGreaterThan(2)\n\t})\n\n\tt.Run(\"to be greater or equal than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewIntChecker(ctx, 2).ToBeGreaterOrEqualThan(2)\n\t\texpect.NewIntChecker(ctx, 2).ToBeGreaterOrEqualThan(1)\n\t})\n\n\tt.Run(\"not to be greater or equal than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewIntChecker(ctx, 1).Not().ToBeGreaterOrEqualThan(2)\n\t})\n\n\tt.Run(\"to be lower than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewIntChecker(ctx, 1).ToBeLowerThan(2)\n\t})\n\n\tt.Run(\"not to be lower than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewIntChecker(ctx, 1).Not().ToBeLowerThan(1)\n\t})\n\n\tt.Run(\"to be lower or equal than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewIntChecker(ctx, 1).ToBeLowerOrEqualThan(1)\n\t\texpect.NewIntChecker(ctx, 1).ToBeLowerOrEqualThan(2)\n\t})\n\n\tt.Run(\"not to be lower or equal than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewIntChecker(ctx, 2).Not().ToBeLowerOrEqualThan(1)\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":"string_test.gno","body":"package expect_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nfunc TestStringChecker(t *testing.T) {\n\tt.Run(\"to equal\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewStringChecker(ctx, \"foo\").ToEqual(\"foo\")\n\t})\n\n\tt.Run(\"not to equal\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewStringChecker(ctx, \"foo\").Not().ToEqual(\"bar\")\n\t})\n\n\tt.Run(\"to be empty\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewStringChecker(ctx, \"\").ToBeEmpty()\n\t})\n\n\tt.Run(\"not to be empty\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewStringChecker(ctx, \"foo\").Not().ToBeEmpty()\n\t})\n\n\tt.Run(\"same length\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewStringChecker(ctx, \"foo\").ToHaveLength(3)\n\t})\n\n\tt.Run(\"different length\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewStringChecker(ctx, \"foo\").Not().ToHaveLength(1)\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":"uint_test.gno","body":"package expect_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nfunc TestUintChecker(t *testing.T) {\n\tt.Run(\"to equal\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewUintChecker(ctx, 1).ToEqual(1)\n\t})\n\n\tt.Run(\"not to equal\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewUintChecker(ctx, 1).Not().ToEqual(2)\n\t})\n\n\tt.Run(\"to be greater than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewUintChecker(ctx, 2).ToBeGreaterThan(1)\n\t})\n\n\tt.Run(\"not to be greater than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewUintChecker(ctx, 1).Not().ToBeGreaterThan(2)\n\t})\n\n\tt.Run(\"to be greater or equal than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewUintChecker(ctx, 2).ToBeGreaterOrEqualThan(2)\n\t\texpect.NewUintChecker(ctx, 2).ToBeGreaterOrEqualThan(1)\n\t})\n\n\tt.Run(\"not to be greater or equal than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewUintChecker(ctx, 1).Not().ToBeGreaterOrEqualThan(2)\n\t})\n\n\tt.Run(\"to be lower than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewUintChecker(ctx, 1).ToBeLowerThan(2)\n\t})\n\n\tt.Run(\"not to be lower than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewUintChecker(ctx, 1).Not().ToBeLowerThan(1)\n\t})\n\n\tt.Run(\"to be lower or equal than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewUintChecker(ctx, 1).ToBeLowerOrEqualThan(1)\n\t\texpect.NewUintChecker(ctx, 1).ToBeLowerOrEqualThan(2)\n\t})\n\n\tt.Run(\"not to be lower or equal than\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tctx := expect.NewContext(t)\n\t\texpect.NewUintChecker(ctx, 2).Not().ToBeLowerOrEqualThan(1)\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"},{"name":"value_test.gno","body":"package expect_test\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nfunc TestValue(t *testing.T) {\n\tt.Run(\"equal\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Value(t, \"foo\").ToEqual(\"foo\")\n\t\texpect.Value(t, []byte(\"foo\")).ToEqual([]byte(\"foo\"))\n\t\texpect.Value(t, stringer(\"foo\")).ToEqual(stringer(\"foo\"))\n\t\texpect.Value(t, true).ToEqual(true)\n\t\texpect.Value(t, float32(1)).ToEqual(float32(1))\n\t\texpect.Value(t, float64(1)).ToEqual(float64(1))\n\t\texpect.Value(t, uint(1)).ToEqual(uint(1))\n\t\texpect.Value(t, uint8(1)).ToEqual(uint8(1))\n\t\texpect.Value(t, uint16(1)).ToEqual(uint16(1))\n\t\texpect.Value(t, uint32(1)).ToEqual(uint32(1))\n\t\texpect.Value(t, uint64(1)).ToEqual(uint64(1))\n\t\texpect.Value(t, int(1)).ToEqual(int(1))\n\t\texpect.Value(t, int8(1)).ToEqual(int8(1))\n\t\texpect.Value(t, int16(1)).ToEqual(int16(1))\n\t\texpect.Value(t, int32(1)).ToEqual(int32(1))\n\t\texpect.Value(t, int64(1)).ToEqual(int64(1))\n\t\texpect.Value(t, errors.New(\"foo\")).ToEqual(errors.New(\"foo\"))\n\t\texpect.Value(t, errors.New(\"foo bar\")).ToContainErrorString(\"foo\")\n\t})\n\n\tt.Run(\"not to equal\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Value(t, \"foo\").Not().ToEqual(\"bar\")\n\t\texpect.Value(t, []byte(\"foo\")).Not().ToEqual([]byte(\"bar\"))\n\t\texpect.Value(t, stringer(\"foo\")).Not().ToEqual(stringer(\"bar\"))\n\t\texpect.Value(t, true).Not().ToEqual(false)\n\t\texpect.Value(t, float32(1)).Not().ToEqual(float32(2))\n\t\texpect.Value(t, float64(1)).Not().ToEqual(float64(2))\n\t\texpect.Value(t, uint(1)).Not().ToEqual(uint(2))\n\t\texpect.Value(t, uint8(1)).Not().ToEqual(uint8(2))\n\t\texpect.Value(t, uint16(1)).Not().ToEqual(uint16(2))\n\t\texpect.Value(t, uint32(1)).Not().ToEqual(uint32(2))\n\t\texpect.Value(t, uint64(1)).Not().ToEqual(uint64(2))\n\t\texpect.Value(t, int(1)).Not().ToEqual(int(2))\n\t\texpect.Value(t, int8(1)).Not().ToEqual(int8(2))\n\t\texpect.Value(t, int16(1)).Not().ToEqual(int16(2))\n\t\texpect.Value(t, int32(1)).Not().ToEqual(int32(2))\n\t\texpect.Value(t, int64(1)).Not().ToEqual(int64(2))\n\t\texpect.Value(t, errors.New(\"foo\")).Not().ToEqual(errors.New(\"bar\"))\n\t\texpect.Value(t, errors.New(\"foo\")).Not().ToContainErrorString(\"bar\")\n\t})\n\n\tt.Run(\"to be nil\", func(t *testing.T) {\n\t\tt.Parallel()\n\t\texpect.Value(t, nil).ToBeNil()\n\t\texpect.Value(t, (*int)(nil)).ToBeNil() // typed nil\n\t})\n\n\tt.Run(\"not to be nil\", func(t *testing.T) {\n\t\tt.Parallel()\n\t\texpect.Value(t, \"\").Not().ToBeNil()\n\t})\n\n\tt.Run(\"to be truthy\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Value(t, \"true\").AsBoolean().ToBeTruthy()\n\t\texpect.Value(t, \"TRUE\").AsBoolean().ToBeTruthy()\n\t\texpect.Value(t, \"t\").AsBoolean().ToBeTruthy()\n\t\texpect.Value(t, \"1\").AsBoolean().ToBeTruthy()\n\t\texpect.Value(t, []byte(\"true\")).AsBoolean().ToBeTruthy()\n\t})\n\n\tt.Run(\"not to be truthy\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Value(t, \"\").AsBoolean().Not().ToBeTruthy()\n\t\texpect.Value(t, \"false\").AsBoolean().Not().ToBeTruthy()\n\t\texpect.Value(t, \"FALSE\").AsBoolean().Not().ToBeTruthy()\n\t\texpect.Value(t, \"f\").AsBoolean().Not().ToBeTruthy()\n\t\texpect.Value(t, \"0\").AsBoolean().Not().ToBeTruthy()\n\t\texpect.Value(t, []byte(nil)).AsBoolean().Not().ToBeTruthy()\n\t\texpect.Value(t, []byte(\"false\")).AsBoolean().Not().ToBeTruthy()\n\t})\n\n\tt.Run(\"to be falsy\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Value(t, \"false\").AsBoolean().ToBeFalsy()\n\t\texpect.Value(t, \"FALSE\").AsBoolean().ToBeFalsy()\n\t\texpect.Value(t, \"f\").AsBoolean().ToBeFalsy()\n\t\texpect.Value(t, \"0\").AsBoolean().ToBeFalsy()\n\t\texpect.Value(t, \"\").AsBoolean().ToBeFalsy()\n\t\texpect.Value(t, []byte(nil)).AsBoolean().ToBeFalsy()\n\t})\n\n\tt.Run(\"not to be falsy\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Value(t, \"true\").AsBoolean().Not().ToBeFalsy()\n\t\texpect.Value(t, \"TRUE\").AsBoolean().Not().ToBeFalsy()\n\t\texpect.Value(t, \"t\").AsBoolean().Not().ToBeFalsy()\n\t\texpect.Value(t, \"1\").AsBoolean().Not().ToBeFalsy()\n\t\texpect.Value(t, []byte(\"true\")).AsBoolean().Not().ToBeFalsy()\n\t})\n\n\tt.Run(\"to equal stringer\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Value(t, address(\"foo\")).AsString().ToEqual(\"foo\")\n\t})\n\n\tt.Run(\"not to equal stringer\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\texpect.Value(t, address(\"foo\")).AsString().Not().ToEqual(\"bar\")\n\t})\n}\n\ntype stringer string\n\nfunc (s stringer) String() string { return string(s) }\n"},{"name":"z_boolean_0_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, true).AsBoolean().ToEqual(false)\n\texpect.Value(t, true).AsBoolean().Not().ToEqual(true)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to match\n// Got: true\n// Want: false\n// Expected values to be different\n// Got: true\n"},{"name":"z_boolean_1_filetest.gno","body":"package main\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\ntype intStringer struct{ value int }\n\nfunc (v intStringer) String() string {\n\treturn strconv.Itoa(v.value)\n}\n\nfunc main() {\n\texpect.Value(t, true).AsBoolean().ToBeFalsy()\n\texpect.Value(t, false).AsBoolean().Not().ToBeFalsy()\n\n\texpect.Value(t, \"TRUE\").AsBoolean().ToBeFalsy()\n\texpect.Value(t, \"FALSE\").AsBoolean().Not().ToBeFalsy()\n\n\texpect.Value(t, []byte(\"TRUE\")).AsBoolean().ToBeFalsy()\n\texpect.Value(t, []byte(\"FALSE\")).AsBoolean().Not().ToBeFalsy()\n\n\texpect.Value(t, intStringer{1}).AsBoolean().ToBeFalsy()\n\texpect.Value(t, intStringer{0}).AsBoolean().Not().ToBeFalsy()\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected value to be falsy\n// Expected value not to be falsy\n// Expected value to be falsy\n// Expected value not to be falsy\n// Expected value to be falsy\n// Expected value not to be falsy\n// Expected value to be falsy\n// Expected value not to be falsy\n"},{"name":"z_boolean_2_filetest.gno","body":"package main\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\ntype intStringer struct{ value int }\n\nfunc (v intStringer) String() string {\n\treturn strconv.Itoa(v.value)\n}\n\nfunc main() {\n\texpect.Value(t, false).AsBoolean().ToBeTruthy()\n\texpect.Value(t, true).AsBoolean().Not().ToBeTruthy()\n\n\texpect.Value(t, \"FALSE\").AsBoolean().ToBeTruthy()\n\texpect.Value(t, \"TRUE\").AsBoolean().Not().ToBeTruthy()\n\n\texpect.Value(t, []byte(\"FALSE\")).AsBoolean().ToBeTruthy()\n\texpect.Value(t, []byte(\"TRUE\")).AsBoolean().Not().ToBeTruthy()\n\n\texpect.Value(t, intStringer{0}).AsBoolean().ToBeTruthy()\n\texpect.Value(t, intStringer{1}).AsBoolean().Not().ToBeTruthy()\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected value to be truthy\n// Expected value not to be truthy\n// Expected value to be truthy\n// Expected value not to be truthy\n// Expected value to be truthy\n// Expected value not to be truthy\n// Expected value to be truthy\n// Expected value not to be truthy\n"},{"name":"z_error_0_filetest.gno","body":"package main\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput  strings.Builder\n\tt       = expect.MockTestingT(\u0026output)\n\ttestErr = errors.New(\"test\")\n)\n\nfunc main() {\n\texpect.Func(t, func() error {\n\t\treturn testErr\n\t}).ToFail().WithMessage(\"foo\")\n\n\texpect.Func(t, func() error {\n\t\treturn testErr\n\t}).ToFail().Not().WithMessage(\"test\")\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected error message to match\n// Got: test\n// Want: foo\n// Expected error message to be different\n// Got: test\n"},{"name":"z_error_1_filetest.gno","body":"package main\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput  strings.Builder\n\tt       = expect.MockTestingT(\u0026output)\n\ttestErr = errors.New(\"test\")\n)\n\nfunc main() {\n\texpect.Func(t, func() error {\n\t\treturn testErr\n\t}).ToFail().WithError(errors.New(\"foo\"))\n\n\texpect.Func(t, func() error {\n\t\treturn testErr\n\t}).ToFail().Not().WithError(testErr)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected errors to match\n// Got: test\n// Want: foo\n// Expected errors to be different\n// Got: test\n"},{"name":"z_float_0_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, 1.2).AsFloat().ToEqual(1.1)\n\texpect.Value(t, 1.2).AsFloat().Not().ToEqual(1.2)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to match\n// Got: 1.2\n// Want: 1.1\n// Expected value to be different\n// Got: 1.2\n"},{"name":"z_float_1_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, 1.2).AsFloat().ToBeGreaterThan(1.3)\n\texpect.Value(t, 1.2).AsFloat().Not().ToBeGreaterThan(1.1)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to be gerater than 1.3\n// Got: 1.2\n// Expected value to not to be greater than 1.1\n// Got: 1.2\n"},{"name":"z_float_2_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, 1.2).AsFloat().ToBeGreaterOrEqualThan(1.3)\n\texpect.Value(t, 1.2).AsFloat().Not().ToBeGreaterOrEqualThan(1.2)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to be greater or equal than 1.3\n// Got: 1.2\n// Expected value to not to be greater or equal than 1.2\n// Got: 1.2\n"},{"name":"z_float_3_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, 1.2).AsFloat().ToBeLowerThan(1.1)\n\texpect.Value(t, 1.2).AsFloat().Not().ToBeLowerThan(1.3)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to be lower than 1.1\n// Got: 1.2\n// Expected value to not to be lower than 1.3\n// Got: 1.2\n"},{"name":"z_float_4_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, 1.2).AsFloat().ToBeLowerOrEqualThan(1.1)\n\texpect.Value(t, 1.2).AsFloat().Not().ToBeLowerOrEqualThan(1.2)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to be lower or equal than 1.1\n// Got: 1.2\n// Expected value to not to be lower or equal than 1.2\n// Got: 1.2\n"},{"name":"z_func_0_filetest.gno","body":"package main\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\tgotMsg := \"Boom!\"\n\tgotErr := errors.New(gotMsg)\n\twantMsg := \"Tick Tock\"\n\twantErr := errors.New(wantMsg)\n\n\texpect.Func(t, func() error { return nil }).ToFail()\n\texpect.Func(t, func() error { return gotErr }).ToFail().WithMessage(wantMsg)\n\texpect.Func(t, func() error { return gotErr }).ToFail().WithError(wantErr)\n\n\texpect.Func(t, func() (any, error) { return nil, nil }).ToFail()\n\texpect.Func(t, func() (any, error) { return nil, gotErr }).ToFail().WithMessage(wantMsg)\n\texpect.Func(t, func() (any, error) { return nil, gotErr }).ToFail().WithError(wantErr)\n\n\texpect.Func(t, func() int { return 0 }).ToFail()\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected func to return an error\n// Expected error message to match\n// Got: Boom!\n// Want: Tick Tock\n// Expected errors to match\n// Got: Boom!\n// Want: Tick Tock\n// Expected func to return an error\n// Expected error message to match\n// Got: Boom!\n// Want: Tick Tock\n// Expected errors to match\n// Got: Boom!\n// Want: Tick Tock\n// Unsupported error func type\n// Got: unknown\n"},{"name":"z_func_1_filetest.gno","body":"package main\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\tmsg := \"Boom!\"\n\terr := errors.New(msg)\n\n\texpect.Func(t, func() error { return err }).Not().ToFail()\n\texpect.Func(t, func() error { return err }).ToFail().Not().WithMessage(msg)\n\texpect.Func(t, func() error { return err }).ToFail().Not().WithError(err)\n\n\texpect.Func(t, func() (any, error) { return nil, err }).Not().ToFail()\n\texpect.Func(t, func() (any, error) { return nil, err }).ToFail().Not().WithMessage(msg)\n\texpect.Func(t, func() (any, error) { return nil, err }).ToFail().Not().WithError(err)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Func failed with error\n// Got: Boom!\n// Expected error message to be different\n// Got: Boom!\n// Expected errors to be different\n// Got: Boom!\n// Func failed with error\n// Got: Boom!\n// Expected error message to be different\n// Got: Boom!\n// Expected errors to be different\n// Got: Boom!\n"},{"name":"z_func_2_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\tgotMsg := \"Boom!\"\n\twantMsg := \"Tick Tock\"\n\n\texpect.Func(t, func() {}).ToPanic()\n\texpect.Func(t, func() { panic(gotMsg) }).ToPanic().WithMessage(wantMsg)\n\n\texpect.Func(t, func() error { return nil }).ToPanic()\n\texpect.Func(t, func() error { panic(gotMsg) }).ToPanic().WithMessage(wantMsg)\n\n\texpect.Func(t, func() any { return nil }).ToPanic()\n\texpect.Func(t, func() any { panic(gotMsg) }).ToPanic().WithMessage(wantMsg)\n\n\texpect.Func(t, func() (any, error) { return nil, nil }).ToPanic()\n\texpect.Func(t, func() (any, error) { panic(gotMsg) }).ToPanic().WithMessage(wantMsg)\n\n\texpect.Func(t, func() int { return 0 }).ToPanic()\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected function to panic\n// Expected panic message to match\n// Got: Boom!\n// Want: Tick Tock\n// Expected function to panic\n// Expected panic message to match\n// Got: Boom!\n// Want: Tick Tock\n// Expected function to panic\n// Expected panic message to match\n// Got: Boom!\n// Want: Tick Tock\n// Expected function to panic\n// Expected panic message to match\n// Got: Boom!\n// Want: Tick Tock\n// Unsupported func type\n// Got: unknown\n"},{"name":"z_func_3_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\tmsg := \"Boom!\"\n\n\texpect.Func(t, func() { panic(msg) }).Not().ToPanic()\n\texpect.Func(t, func() { panic(msg) }).ToPanic().Not().WithMessage(msg)\n\n\texpect.Func(t, func() error { panic(msg) }).Not().ToPanic()\n\texpect.Func(t, func() error { panic(msg) }).ToPanic().Not().WithMessage(msg)\n\n\texpect.Func(t, func() any { panic(msg) }).Not().ToPanic()\n\texpect.Func(t, func() any { panic(msg) }).ToPanic().Not().WithMessage(msg)\n\n\texpect.Func(t, func() (any, error) { panic(msg) }).Not().ToPanic()\n\texpect.Func(t, func() (any, error) { panic(msg) }).ToPanic().Not().WithMessage(msg)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected func not to panic\n// Got: Boom!\n// Expected panic message to be different\n// Got: Boom!\n// Expected func not to panic\n// Got: Boom!\n// Expected panic message to be different\n// Got: Boom!\n// Expected func not to panic\n// Got: Boom!\n// Expected panic message to be different\n// Got: Boom!\n// Expected func not to panic\n// Got: Boom!\n// Expected panic message to be different\n// Got: Boom!\n"},{"name":"z_func_4_filetest.gno","body":"package main\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Func(t, func() any { return \"foo\" }).ToReturn(\"bar\")\n\texpect.Func(t, func() any { return []byte(\"foo\") }).ToReturn([]byte(\"bar\"))\n\texpect.Func(t, func() any { return true }).ToReturn(false)\n\texpect.Func(t, func() any { return float32(1) }).ToReturn(float32(2))\n\texpect.Func(t, func() any { return float64(1.1) }).ToReturn(float64(1.2))\n\texpect.Func(t, func() any { return uint(1) }).ToReturn(uint(2))\n\texpect.Func(t, func() any { return uint8(1) }).ToReturn(uint8(2))\n\texpect.Func(t, func() any { return uint16(1) }).ToReturn(uint16(2))\n\texpect.Func(t, func() any { return uint32(1) }).ToReturn(uint32(2))\n\texpect.Func(t, func() any { return uint64(1) }).ToReturn(uint64(2))\n\texpect.Func(t, func() any { return int(1) }).ToReturn(int(2))\n\texpect.Func(t, func() any { return int8(1) }).ToReturn(int8(2))\n\texpect.Func(t, func() any { return int16(1) }).ToReturn(int16(2))\n\texpect.Func(t, func() any { return int32(1) }).ToReturn(int32(2))\n\texpect.Func(t, func() any { return int64(1) }).ToReturn(int64(2))\n\n\texpect.Func(t, func() (any, error) { return \"foo\", nil }).ToReturn(\"bar\")\n\texpect.Func(t, func() (any, error) { return []byte(\"foo\"), nil }).ToReturn([]byte(\"bar\"))\n\texpect.Func(t, func() (any, error) { return true, nil }).ToReturn(false)\n\texpect.Func(t, func() (any, error) { return float32(1), nil }).ToReturn(float32(2))\n\texpect.Func(t, func() (any, error) { return float64(1.1), nil }).ToReturn(float64(1.2))\n\texpect.Func(t, func() (any, error) { return uint(1), nil }).ToReturn(uint(2))\n\texpect.Func(t, func() (any, error) { return uint8(1), nil }).ToReturn(uint8(2))\n\texpect.Func(t, func() (any, error) { return uint16(1), nil }).ToReturn(uint16(2))\n\texpect.Func(t, func() (any, error) { return uint32(1), nil }).ToReturn(uint32(2))\n\texpect.Func(t, func() (any, error) { return uint64(1), nil }).ToReturn(uint64(2))\n\texpect.Func(t, func() (any, error) { return int(1), nil }).ToReturn(int(2))\n\texpect.Func(t, func() (any, error) { return int8(1), nil }).ToReturn(int8(2))\n\texpect.Func(t, func() (any, error) { return int16(1), nil }).ToReturn(int16(2))\n\texpect.Func(t, func() (any, error) { return int32(1), nil }).ToReturn(int32(2))\n\texpect.Func(t, func() (any, error) { return int64(1), nil }).ToReturn(int64(2))\n\n\texpect.Func(t, func() (any, error) { return 0, errors.New(\"Boom!\") }).ToReturn(1)\n\texpect.Func(t, func() {}).ToReturn(1)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to match\n// Got: foo\n// Want: bar\n// Expected values to match\n// Got: foo\n// Want: bar\n// Expected values to match\n// Got: true\n// Want: false\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1.1\n// Want: 1.2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: foo\n// Want: bar\n// Expected values to match\n// Got: foo\n// Want: bar\n// Expected values to match\n// Got: true\n// Want: false\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1.1\n// Want: 1.2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Function returned unexpected error\n// Got: Boom!\n// Unsupported func type\n// Got: unknown\n"},{"name":"z_func_5_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Func(t, func() any { return \"foo\" }).Not().ToReturn(\"foo\")\n\texpect.Func(t, func() any { return []byte(\"foo\") }).Not().ToReturn([]byte(\"foo\"))\n\texpect.Func(t, func() any { return true }).Not().ToReturn(true)\n\texpect.Func(t, func() any { return float32(1) }).Not().ToReturn(float32(1))\n\texpect.Func(t, func() any { return float64(1.1) }).Not().ToReturn(float64(1.1))\n\texpect.Func(t, func() any { return uint(1) }).Not().ToReturn(uint(1))\n\texpect.Func(t, func() any { return uint8(1) }).Not().ToReturn(uint8(1))\n\texpect.Func(t, func() any { return uint16(1) }).Not().ToReturn(uint16(1))\n\texpect.Func(t, func() any { return uint32(1) }).Not().ToReturn(uint32(1))\n\texpect.Func(t, func() any { return uint64(1) }).Not().ToReturn(uint64(1))\n\texpect.Func(t, func() any { return int(1) }).Not().ToReturn(int(1))\n\texpect.Func(t, func() any { return int8(1) }).Not().ToReturn(int8(1))\n\texpect.Func(t, func() any { return int16(1) }).Not().ToReturn(int16(1))\n\texpect.Func(t, func() any { return int32(1) }).Not().ToReturn(int32(1))\n\texpect.Func(t, func() any { return int64(1) }).Not().ToReturn(int64(1))\n\n\texpect.Func(t, func() (any, error) { return \"foo\", nil }).Not().ToReturn(\"foo\")\n\texpect.Func(t, func() (any, error) { return []byte(\"foo\"), nil }).Not().ToReturn([]byte(\"foo\"))\n\texpect.Func(t, func() (any, error) { return true, nil }).Not().ToReturn(true)\n\texpect.Func(t, func() (any, error) { return float32(1), nil }).Not().ToReturn(float32(1))\n\texpect.Func(t, func() (any, error) { return float64(1.1), nil }).Not().ToReturn(float64(1.1))\n\texpect.Func(t, func() (any, error) { return uint(1), nil }).Not().ToReturn(uint(1))\n\texpect.Func(t, func() (any, error) { return uint8(1), nil }).Not().ToReturn(uint8(1))\n\texpect.Func(t, func() (any, error) { return uint16(1), nil }).Not().ToReturn(uint16(1))\n\texpect.Func(t, func() (any, error) { return uint32(1), nil }).Not().ToReturn(uint32(1))\n\texpect.Func(t, func() (any, error) { return uint64(1), nil }).Not().ToReturn(uint64(1))\n\texpect.Func(t, func() (any, error) { return int(1), nil }).Not().ToReturn(int(1))\n\texpect.Func(t, func() (any, error) { return int8(1), nil }).Not().ToReturn(int8(1))\n\texpect.Func(t, func() (any, error) { return int16(1), nil }).Not().ToReturn(int16(1))\n\texpect.Func(t, func() (any, error) { return int32(1), nil }).Not().ToReturn(int32(1))\n\texpect.Func(t, func() (any, error) { return int64(1), nil }).Not().ToReturn(int64(1))\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to be different\n// Got: foo\n// Expected values to be different\n// Got: foo\n// Expected values to be different\n// Got: true\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1.1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected values to be different\n// Got: foo\n// Expected values to be different\n// Got: foo\n// Expected values to be different\n// Got: true\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1.1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n"},{"name":"z_func_6_filetest.gno","body":"// PKGPATH: gno.land/r/demo/test\npackage test\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nconst (\n\tcaller = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\")\n\tmsg    = \"Boom!\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc Fail(realm) {\n\tpanic(msg)\n}\n\nfunc Success(realm) {\n\t// No panic\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(caller))\n\n\texpect.Func(t, func() { Fail(cross(cur)) }).ToCrossPanic()\n\texpect.Func(t, func() { Fail(cross(cur)) }).ToCrossPanic().WithMessage(msg)\n\n\texpect.Func(t, func() error { Fail(cross(cur)); return nil }).ToCrossPanic()\n\texpect.Func(t, func() error { Fail(cross(cur)); return nil }).ToCrossPanic().WithMessage(msg)\n\n\texpect.Func(t, func() any { Fail(cross(cur)); return nil }).ToCrossPanic()\n\texpect.Func(t, func() any { Fail(cross(cur)); return nil }).ToCrossPanic().WithMessage(msg)\n\n\texpect.Func(t, func() (any, error) { Fail(cross(cur)); return nil, nil }).ToCrossPanic()\n\texpect.Func(t, func() (any, error) { Fail(cross(cur)); return nil, nil }).ToCrossPanic().WithMessage(msg)\n\n\texpect.Func(t, func() { Success(cross(cur)) }).Not().ToCrossPanic()\n\texpect.Func(t, func() error { Success(cross(cur)); return nil }).Not().ToCrossPanic()\n\texpect.Func(t, func() any { Success(cross(cur)); return nil }).Not().ToCrossPanic()\n\texpect.Func(t, func() (any, error) { Success(cross(cur)); return nil, nil }).Not().ToCrossPanic()\n\n\t// None should fail, output should be empty\n\tprint(output.String())\n}\n\n// Output:\n"},{"name":"z_func_7_filetest.gno","body":"// PKGPATH: gno.land/r/demo/test\npackage test\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nconst (\n\tcaller = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\")\n\tmsg    = \"Boom!\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc Fail(realm) {\n\tpanic(msg)\n}\n\nfunc Success(realm) {\n\t// No panic\n}\n\nfunc main(cur realm) {\n\twantMsg := \"Tick Tock\"\n\n\ttesting.SetRealm(testing.NewUserRealm(caller))\n\n\texpect.Func(t, func() { Success(cross(cur)) }).ToCrossPanic()\n\texpect.Func(t, func() { Fail(cross(cur)) }).ToCrossPanic().WithMessage(wantMsg)\n\n\texpect.Func(t, func() error { Success(cross(cur)); return nil }).ToCrossPanic()\n\texpect.Func(t, func() error { Fail(cross(cur)); return nil }).ToCrossPanic().WithMessage(wantMsg)\n\n\texpect.Func(t, func() any { Success(cross(cur)); return nil }).ToCrossPanic()\n\texpect.Func(t, func() any { Fail(cross(cur)); return nil }).ToCrossPanic().WithMessage(wantMsg)\n\n\texpect.Func(t, func() (any, error) { Success(cross(cur)); return nil, nil }).ToCrossPanic()\n\texpect.Func(t, func() (any, error) { Fail(cross(cur)); return nil, nil }).ToCrossPanic().WithMessage(wantMsg)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected function to cross panic\n// Expected cross panic message to match\n// Got: Boom!\n// Want: Tick Tock\n// Expected function to cross panic\n// Expected cross panic message to match\n// Got: Boom!\n// Want: Tick Tock\n// Expected function to cross panic\n// Expected cross panic message to match\n// Got: Boom!\n// Want: Tick Tock\n// Expected function to cross panic\n// Expected cross panic message to match\n// Got: Boom!\n// Want: Tick Tock\n"},{"name":"z_func_8_filetest.gno","body":"// PKGPATH: gno.land/r/demo/test\npackage test\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nconst (\n\tcaller = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\")\n\tmsg    = \"Boom!\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc Fail(realm) {\n\tpanic(msg)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(caller))\n\n\texpect.Func(t, func() { Fail(cross(cur)) }).Not().ToCrossPanic()\n\texpect.Func(t, func() { Fail(cross(cur)) }).ToCrossPanic().Not().WithMessage(msg)\n\n\texpect.Func(t, func() error { Fail(cross(cur)); return nil }).Not().ToCrossPanic()\n\texpect.Func(t, func() error { Fail(cross(cur)); return nil }).ToCrossPanic().Not().WithMessage(msg)\n\n\texpect.Func(t, func() any { Fail(cross(cur)); return nil }).Not().ToCrossPanic()\n\texpect.Func(t, func() any { Fail(cross(cur)); return nil }).ToCrossPanic().Not().WithMessage(msg)\n\n\texpect.Func(t, func() (any, error) { Fail(cross(cur)); return nil, nil }).Not().ToCrossPanic()\n\texpect.Func(t, func() (any, error) { Fail(cross(cur)); return nil, nil }).ToCrossPanic().Not().WithMessage(msg)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected func not to cross panic\n// Got: Boom!\n// Expected cross panic message to be different\n// Got: Boom!\n// Expected func not to cross panic\n// Got: Boom!\n// Expected cross panic message to be different\n// Got: Boom!\n// Expected func not to cross panic\n// Got: Boom!\n// Expected cross panic message to be different\n// Got: Boom!\n// Expected func not to cross panic\n// Got: Boom!\n// Expected cross panic message to be different\n// Got: Boom!\n"},{"name":"z_int_0_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, 1).AsInt().ToEqual(2)\n\texpect.Value(t, 1).AsInt().Not().ToEqual(1)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected value to be different\n// Got: 1\n"},{"name":"z_int_1_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, 1).AsInt().ToBeGreaterThan(2)\n\texpect.Value(t, 1).AsInt().Not().ToBeGreaterThan(0)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to be gerater than 2\n// Got: 1\n// Expected value to not to be greater than 0\n// Got: 1\n"},{"name":"z_int_2_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, 1).AsInt().ToBeGreaterOrEqualThan(2)\n\texpect.Value(t, 1).AsInt().Not().ToBeGreaterOrEqualThan(1)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to be greater or equal than 2\n// Got: 1\n// Expected value to not to be greater or equal than 1\n// Got: 1\n"},{"name":"z_int_3_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, 1).AsInt().ToBeLowerThan(1)\n\texpect.Value(t, 1).AsInt().Not().ToBeLowerThan(2)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to be lower than 1\n// Got: 1\n// Expected value to not to be lower than 2\n// Got: 1\n"},{"name":"z_int_4_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, 1).AsInt().ToBeLowerOrEqualThan(0)\n\texpect.Value(t, 1).AsInt().Not().ToBeLowerOrEqualThan(1)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to be lower or equal than 0\n// Got: 1\n// Expected value to not to be lower or equal than 1\n// Got: 1\n"},{"name":"z_string_0_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, \"foo\").AsString().ToEqual(\"bar\")\n\texpect.Value(t, \"foo\").AsString().Not().ToEqual(\"foo\")\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to match\n// Got: foo\n// Want: bar\n// Expected values to be different\n// Got: foo\n"},{"name":"z_string_1_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, \"foo\").AsString().ToBeEmpty()\n\texpect.Value(t, \"\").AsString().Not().ToBeEmpty()\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected string to be empty\n// Got: foo\n// Unexpected empty string\n"},{"name":"z_string_2_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, \"foo\").AsString().ToHaveLength(2)\n\texpect.Value(t, \"foo\").AsString().Not().ToHaveLength(3)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected string length to match\n// Got: 3\n// Want: 2\n// Expected string lengths to be different\n// Got: 3\n"},{"name":"z_uint_0_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, 1).AsUint().ToEqual(2)\n\texpect.Value(t, 1).AsUint().Not().ToEqual(1)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected value to be different\n// Got: 1\n"},{"name":"z_uint_1_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, 1).AsUint().ToBeGreaterThan(2)\n\texpect.Value(t, 1).AsUint().Not().ToBeGreaterThan(0)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to be gerater than 2\n// Got: 1\n// Expected value to not to be greater than 0\n// Got: 1\n"},{"name":"z_uint_2_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, 1).AsUint().ToBeGreaterOrEqualThan(2)\n\texpect.Value(t, 1).AsUint().Not().ToBeGreaterOrEqualThan(1)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to be greater or equal than 2\n// Got: 1\n// Expected value to not to be greater or equal than 1\n// Got: 1\n"},{"name":"z_uint_3_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, 1).AsUint().ToBeLowerThan(1)\n\texpect.Value(t, 1).AsUint().Not().ToBeLowerThan(2)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to be lower than 1\n// Got: 1\n// Expected value to not to be lower than 2\n// Got: 1\n"},{"name":"z_uint_4_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, 1).AsUint().ToBeLowerOrEqualThan(0)\n\texpect.Value(t, 1).AsUint().Not().ToBeLowerOrEqualThan(1)\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to be lower or equal than 0\n// Got: 1\n// Expected value to not to be lower or equal than 1\n// Got: 1\n"},{"name":"z_value_0_filetest.gno","body":"package main\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\ntype stringer string\n\nfunc (s stringer) String() string { return string(s) }\n\nfunc main() {\n\texpect.Value(t, \"foo\").ToEqual(\"bar\")\n\texpect.Value(t, []byte(\"foo\")).ToEqual([]byte(\"bar\"))\n\texpect.Value(t, stringer(\"foo\")).ToEqual(stringer(\"bar\"))\n\texpect.Value(t, true).ToEqual(false)\n\texpect.Value(t, float32(1)).ToEqual(float32(2))\n\texpect.Value(t, float64(1.1)).ToEqual(float64(1.2))\n\texpect.Value(t, uint(1)).ToEqual(uint(2))\n\texpect.Value(t, uint8(1)).ToEqual(uint8(2))\n\texpect.Value(t, uint16(1)).ToEqual(uint16(2))\n\texpect.Value(t, uint32(1)).ToEqual(uint32(2))\n\texpect.Value(t, uint64(1)).ToEqual(uint64(2))\n\texpect.Value(t, int(1)).ToEqual(int(2))\n\texpect.Value(t, int8(1)).ToEqual(int8(2))\n\texpect.Value(t, int16(1)).ToEqual(int16(2))\n\texpect.Value(t, int32(1)).ToEqual(int32(2))\n\texpect.Value(t, int64(1)).ToEqual(int64(2))\n\texpect.Value(t, errors.New(\"foo\")).ToEqual(errors.New(\"bar\"))\n\texpect.Value(t, errors.New(\"foo\")).ToContainErrorString(\"bar\")\n\n\texpect.Value(t, 0).ToEqual(errors.New(\"foo\"))\n\texpect.Value(t, 0).ToEqual([]string{})\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to match\n// Got: foo\n// Want: bar\n// Expected values to match\n// Got: foo\n// Want: bar\n// Expected values to match\n// Got: foo\n// Want: bar\n// Expected values to match\n// Got: true\n// Want: false\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1.1\n// Want: 1.2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected values to match\n// Got: 1\n// Want: 2\n// Expected errors to match\n// Got: foo\n// Want: bar\n// Expected error message to contain: bar\n// Got: foo\n// Error is not equal to value\n// Got: foo\n// Unsupported type: unknown\n"},{"name":"z_value_1_filetest.gno","body":"package main\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\ntype stringer string\n\nfunc (s stringer) String() string { return string(s) }\n\nfunc main() {\n\texpect.Value(t, \"foo\").Not().ToEqual(\"foo\")\n\texpect.Value(t, []byte(\"foo\")).Not().ToEqual([]byte(\"foo\"))\n\texpect.Value(t, stringer(\"foo\")).Not().ToEqual(stringer(\"foo\"))\n\texpect.Value(t, true).Not().ToEqual(true)\n\texpect.Value(t, float32(1)).Not().ToEqual(float32(1))\n\texpect.Value(t, float64(1)).Not().ToEqual(float64(1))\n\texpect.Value(t, uint(1)).Not().ToEqual(uint(1))\n\texpect.Value(t, uint8(1)).Not().ToEqual(uint8(1))\n\texpect.Value(t, uint16(1)).Not().ToEqual(uint16(1))\n\texpect.Value(t, uint32(1)).Not().ToEqual(uint32(1))\n\texpect.Value(t, uint64(1)).Not().ToEqual(uint64(1))\n\texpect.Value(t, int(1)).Not().ToEqual(int(1))\n\texpect.Value(t, int8(1)).Not().ToEqual(int8(1))\n\texpect.Value(t, int16(1)).Not().ToEqual(int16(1))\n\texpect.Value(t, int32(1)).Not().ToEqual(int32(1))\n\texpect.Value(t, int64(1)).Not().ToEqual(int64(1))\n\texpect.Value(t, errors.New(\"foo\")).Not().ToEqual(errors.New(\"foo\"))\n\texpect.Value(t, errors.New(\"foo bar\")).Not().ToContainErrorString(\"bar\")\n\n\texpect.Value(t, 0).Not().ToEqual(errors.New(\"foo\"))\n\texpect.Value(t, 0).Not().ToEqual([]string{})\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected values to be different\n// Got: foo\n// Expected values to be different\n// Got: foo\n// Expected values to be different\n// Got: foo\n// Expected values to be different\n// Got: true\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected value to be different\n// Got: 1\n// Expected errors to be different\n// Got: foo\n// Expected error message not to contain: bar\n// Got: foo bar\n// Error is not equal to value\n// Got: foo\n// Unsupported type: unknown\n"},{"name":"z_value_2_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, \"foo\").ToBeNil()\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected value to be nil\n// Got: foo\n"},{"name":"z_value_3_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, nil).Not().ToBeNil()\n\texpect.Value(t, (*int)(nil)).Not().ToBeNil()\n\n\tprintln(output.String())\n}\n\n// Output:\n// Expected a non nil value\n// Expected a non nil value\n"},{"name":"z_value_4_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, nil).WithFailPrefix(\"Foo prefix\").Not().ToBeNil()\n\texpect.Value(t, (*int)(nil)).WithFailPrefix(\"Foo prefix\").Not().ToBeNil()\n\n\tprintln(output.String())\n}\n\n// Output:\n// Foo prefix - Expected a non nil value\n// Foo prefix - Expected a non nil value\n"},{"name":"z_value_5_filetest.gno","body":"package main\n\nimport (\n\t\"strings\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n)\n\nvar (\n\toutput strings.Builder\n\tt      = expect.MockTestingT(\u0026output)\n)\n\nfunc main() {\n\texpect.Value(t, 1).AsString()\n\texpect.Value(t, 1).AsBoolean()\n\texpect.Value(t, 1).AsFloat()\n\texpect.Value(t, 1).AsUint()\n\texpect.Value(t, \"\").AsInt()\n\n\tprintln(output.String())\n}\n\n// Output:\n// Failed: incompatible type: expected a string value\n// Got: int\n// Failed: incompatible type: expected a boolean value\n// Got: int\n// incompatible type: expected a float value\n// Got: int\n// Failed: incompatible type: expected an int value\n// Got: string\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"y/XLr7UkwFhFrMCfZFz3VFBt0vqjBd6tecE+HXtm83VriyKxm1AefBg1ucOxpfPHOkn9zoFCcQehsfGhmpgvFw=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"mdform","path":"gno.land/p/jeronimoalbi/mdform","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\"\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\"\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"},{"name":"mdform_filetest.gno","body":"package main\n\nimport \"gno.land/p/jeronimoalbi/mdform\"\n\nfunc main() {\n\tform := mdform.\n\t\tNew(\n\t\t\t\"exec\", \"FunctionName\",\n\t\t).\n\t\tInput(\n\t\t\t\"name\",\n\t\t\t\"placeholder\", \"Name\",\n\t\t\t\"value\", \"John Doe\",\n\t\t).\n\t\tSelect(\n\t\t\t\"country\",\n\t\t\t\"United States\",\n\t\t\t\"description\", \"Select your country\",\n\t\t).\n\t\tSelect(\n\t\t\t\"country\",\n\t\t\t\"Spain\",\n\t\t).\n\t\tSelect(\n\t\t\t\"country\",\n\t\t\t\"Germany\",\n\t\t).\n\t\tCheckbox(\n\t\t\t\"interests\",\n\t\t\t\"music\",\n\t\t\t\"description\", \"What do you like to do?\",\n\t\t).\n\t\tCheckbox(\n\t\t\t\"interests\",\n\t\t\t\"tech\",\n\t\t\t\"checked\", \"true\",\n\t\t)\n\tprintln(form.String())\n}\n\n// Output:\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"},{"name":"mdform_test.gno","body":"package mdform_test\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/jeronimoalbi/mdform\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\n// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\n\nfunc TestNew(cur realm, t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tattrs    []string\n\t\tmarkdown string\n\t\terr      string\n\t}{\n\t\t{\n\t\t\tname:     \"ok\",\n\t\t\tattrs:    []string{\"exec\", \"FunctionName\"},\n\t\t\tmarkdown: `\u003cgno-form exec=\"FunctionName\"\u003e\u003c/gno-form\u003e`,\n\t\t},\n\t\t{\n\t\t\tname:     \"no attributes\",\n\t\t\tmarkdown: `\u003cgno-form\u003e\u003c/gno-form\u003e`,\n\t\t},\n\t\t{\n\t\t\tname:  \"uneven attributes\",\n\t\t\tattrs: []string{\"exec\"},\n\t\t\terr:   \"expected an even number of attribute arguments\",\n\t\t},\n\t\t{\n\t\t\tname:  \"invalid attribute\",\n\t\t\tattrs: []string{\"foo\", \"\"},\n\t\t\terr:   \"invalid attribute: foo\",\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tvar markdown string\n\t\t\tfn := func() {\n\t\t\t\tf := mdform.New(tc.attrs...)\n\t\t\t\tmarkdown = strings.ReplaceAll(f.String(), \"\\n\", \"\")\n\t\t\t}\n\n\t\t\tif tc.err != \"\" {\n\t\t\t\turequire.PanicsWithMessage(t, cur, tc.err, fn, \"expect form to fail\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.NotPanics(t, cur, fn, \"expect form to be created\")\n\t\t\tuassert.Equal(t, tc.markdown, markdown, \"expected markdown to match\")\n\t\t})\n\t}\n}\n\nfunc TestFormInput(cur realm, t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tinputName string\n\t\tattrs     []string\n\t\tmarkdown  string\n\t\terr       string\n\t}{\n\t\t{\n\t\t\tname:      \"ok\",\n\t\t\tinputName: \"test\",\n\t\t\tattrs:     []string{\"value\", \"foo\"},\n\t\t\tmarkdown:  `\u003cgno-form\u003e\u003cgno-input name=\"test\" value=\"foo\" /\u003e\u003c/gno-form\u003e`,\n\t\t},\n\t\t{\n\t\t\tname:      \"no attributes\",\n\t\t\tinputName: \"test\",\n\t\t\tmarkdown:  `\u003cgno-form\u003e\u003cgno-input name=\"test\" /\u003e\u003c/gno-form\u003e`,\n\t\t},\n\t\t{\n\t\t\tname:      \"empty name\",\n\t\t\tinputName: \"  \",\n\t\t\terr:       \"form input name is required\",\n\t\t},\n\t\t{\n\t\t\tname:      \"radio type\",\n\t\t\tinputName: \"test\",\n\t\t\tattrs:     []string{\"type\", \"radio\"},\n\t\t\terr:       \"use form.Radio() to create inputs of type radio\",\n\t\t},\n\t\t{\n\t\t\tname:      \"checkbox type\",\n\t\t\tinputName: \"test\",\n\t\t\tattrs:     []string{\"type\", \"checkbox\"},\n\t\t\terr:       \"use form.Checkbox() to create inputs of type checkbox\",\n\t\t},\n\t\t{\n\t\t\tname:      \"uneven attributes\",\n\t\t\tinputName: \"test\",\n\t\t\tattrs:     []string{\"value\"},\n\t\t\terr:       \"expected an even number of attribute arguments\",\n\t\t},\n\t\t{\n\t\t\tname:      \"invalid attribute\",\n\t\t\tinputName: \"test\",\n\t\t\tattrs:     []string{\"foo\", \"\"},\n\t\t\terr:       \"invalid attribute: foo\",\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tvar markdown string\n\t\t\tfn := func() {\n\t\t\t\tf := mdform.New()\n\t\t\t\tf.Input(tc.inputName, tc.attrs...)\n\t\t\t\tmarkdown = strings.ReplaceAll(f.String(), \"\\n\", \"\")\n\t\t\t}\n\n\t\t\tif tc.err != \"\" {\n\t\t\t\turequire.PanicsWithMessage(t, cur, tc.err, fn, \"expect form input to fail\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.NotPanics(t, cur, fn, \"expect form input to be created\")\n\t\t\tuassert.Equal(t, tc.markdown, markdown, \"expected markdown to match\")\n\t\t})\n\t}\n}\n\nfunc TestFormRadio(cur realm, t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tinputName string\n\t\tvalue     string\n\t\tattrs     []string\n\t\tmarkdown  string\n\t\terr       string\n\t}{\n\t\t{\n\t\t\tname:      \"ok\",\n\t\t\tinputName: \"test\",\n\t\t\tvalue:     \"foo\",\n\t\t\tattrs:     []string{\"readonly\", \"true\"},\n\t\t\tmarkdown:  `\u003cgno-form\u003e\u003cgno-input type=\"radio\" name=\"test\" value=\"foo\" readonly=\"true\" /\u003e\u003c/gno-form\u003e`,\n\t\t},\n\t\t{\n\t\t\tname:      \"no attributes\",\n\t\t\tinputName: \"test\",\n\t\t\tvalue:     \"foo\",\n\t\t\tmarkdown:  `\u003cgno-form\u003e\u003cgno-input type=\"radio\" name=\"test\" value=\"foo\" /\u003e\u003c/gno-form\u003e`,\n\t\t},\n\t\t{\n\t\t\tname:      \"empty name\",\n\t\t\tinputName: \"  \",\n\t\t\terr:       \"form radio input name is required\",\n\t\t},\n\t\t{\n\t\t\tname:      \"ignore type attribute\",\n\t\t\tinputName: \"test\",\n\t\t\tattrs:     []string{\"type\", \"text\"},\n\t\t\tmarkdown:  `\u003cgno-form\u003e\u003cgno-input type=\"radio\" name=\"test\" value=\"\" /\u003e\u003c/gno-form\u003e`,\n\t\t},\n\t\t{\n\t\t\tname:      \"ignore value attribute\",\n\t\t\tinputName: \"test\",\n\t\t\tattrs:     []string{\"value\", \"foo\"},\n\t\t\tmarkdown:  `\u003cgno-form\u003e\u003cgno-input type=\"radio\" name=\"test\" value=\"\" /\u003e\u003c/gno-form\u003e`,\n\t\t},\n\t\t{\n\t\t\tname:      \"uneven attributes\",\n\t\t\tinputName: \"test\",\n\t\t\tattrs:     []string{\"readonly\"},\n\t\t\terr:       \"expected an even number of attribute arguments\",\n\t\t},\n\t\t{\n\t\t\tname:      \"invalid attribute\",\n\t\t\tinputName: \"test\",\n\t\t\tattrs:     []string{\"foo\", \"\"},\n\t\t\terr:       \"invalid attribute: foo\",\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tvar markdown string\n\t\t\tfn := func() {\n\t\t\t\tf := mdform.New()\n\t\t\t\tf.Radio(tc.inputName, tc.value, tc.attrs...)\n\t\t\t\tmarkdown = strings.ReplaceAll(f.String(), \"\\n\", \"\")\n\t\t\t}\n\n\t\t\tif tc.err != \"\" {\n\t\t\t\turequire.PanicsWithMessage(t, cur, tc.err, fn, \"expect form radio input to fail\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.NotPanics(t, cur, fn, \"expect form radio input to be created\")\n\t\t\tuassert.Equal(t, tc.markdown, markdown, \"expected markdown to match\")\n\t\t})\n\t}\n}\n\nfunc TestFormCheckbox(cur realm, t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tinputName string\n\t\tvalue     string\n\t\tattrs     []string\n\t\tmarkdown  string\n\t\terr       string\n\t}{\n\t\t{\n\t\t\tname:      \"ok\",\n\t\t\tinputName: \"test\",\n\t\t\tvalue:     \"foo\",\n\t\t\tattrs:     []string{\"readonly\", \"true\"},\n\t\t\tmarkdown:  `\u003cgno-form\u003e\u003cgno-input type=\"checkbox\" name=\"test\" value=\"foo\" readonly=\"true\" /\u003e\u003c/gno-form\u003e`,\n\t\t},\n\t\t{\n\t\t\tname:      \"no attributes\",\n\t\t\tinputName: \"test\",\n\t\t\tvalue:     \"foo\",\n\t\t\tmarkdown:  `\u003cgno-form\u003e\u003cgno-input type=\"checkbox\" name=\"test\" value=\"foo\" /\u003e\u003c/gno-form\u003e`,\n\t\t},\n\t\t{\n\t\t\tname:      \"empty name\",\n\t\t\tinputName: \"  \",\n\t\t\terr:       \"form checkbox input name is required\",\n\t\t},\n\t\t{\n\t\t\tname:      \"ignore type attribute\",\n\t\t\tinputName: \"test\",\n\t\t\tattrs:     []string{\"type\", \"text\"},\n\t\t\tmarkdown:  `\u003cgno-form\u003e\u003cgno-input type=\"checkbox\" name=\"test\" value=\"\" /\u003e\u003c/gno-form\u003e`,\n\t\t},\n\t\t{\n\t\t\tname:      \"ignore value attribute\",\n\t\t\tinputName: \"test\",\n\t\t\tattrs:     []string{\"value\", \"foo\"},\n\t\t\tmarkdown:  `\u003cgno-form\u003e\u003cgno-input type=\"checkbox\" name=\"test\" value=\"\" /\u003e\u003c/gno-form\u003e`,\n\t\t},\n\t\t{\n\t\t\tname:      \"uneven attributes\",\n\t\t\tinputName: \"test\",\n\t\t\tattrs:     []string{\"readonly\"},\n\t\t\terr:       \"expected an even number of attribute arguments\",\n\t\t},\n\t\t{\n\t\t\tname:      \"invalid attribute\",\n\t\t\tinputName: \"test\",\n\t\t\tattrs:     []string{\"foo\", \"\"},\n\t\t\terr:       \"invalid attribute: foo\",\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tvar markdown string\n\t\t\tfn := func() {\n\t\t\t\tf := mdform.New()\n\t\t\t\tf.Checkbox(tc.inputName, tc.value, tc.attrs...)\n\t\t\t\tmarkdown = strings.ReplaceAll(f.String(), \"\\n\", \"\")\n\t\t\t}\n\n\t\t\tif tc.err != \"\" {\n\t\t\t\turequire.PanicsWithMessage(t, cur, tc.err, fn, \"expect form checkbox input to fail\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.NotPanics(t, cur, fn, \"expect form checkbox input to be created\")\n\t\t\tuassert.Equal(t, tc.markdown, markdown, \"expected markdown to match\")\n\t\t})\n\t}\n}\n\nfunc TestFormTextarea(cur realm, t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tinputName string\n\t\tattrs     []string\n\t\tmarkdown  string\n\t\terr       string\n\t}{\n\t\t{\n\t\t\tname:      \"ok\",\n\t\t\tinputName: \"test\",\n\t\t\tattrs:     []string{\"value\", \"foo\"},\n\t\t\tmarkdown:  `\u003cgno-form\u003e\u003cgno-textarea name=\"test\" value=\"foo\" /\u003e\u003c/gno-form\u003e`,\n\t\t},\n\t\t{\n\t\t\tname:      \"no attributes\",\n\t\t\tinputName: \"test\",\n\t\t\tmarkdown:  `\u003cgno-form\u003e\u003cgno-textarea name=\"test\" /\u003e\u003c/gno-form\u003e`,\n\t\t},\n\t\t{\n\t\t\tname:      \"empty name\",\n\t\t\tinputName: \"  \",\n\t\t\terr:       \"form textarea name is required\",\n\t\t},\n\t\t{\n\t\t\tname:      \"uneven attributes\",\n\t\t\tinputName: \"test\",\n\t\t\tattrs:     []string{\"value\"},\n\t\t\terr:       \"expected an even number of attribute arguments\",\n\t\t},\n\t\t{\n\t\t\tname:      \"invalid attribute\",\n\t\t\tinputName: \"test\",\n\t\t\tattrs:     []string{\"foo\", \"\"},\n\t\t\terr:       \"invalid attribute: foo\",\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tvar markdown string\n\t\t\tfn := func() {\n\t\t\t\tf := mdform.New()\n\t\t\t\tf.Textarea(tc.inputName, tc.attrs...)\n\t\t\t\tmarkdown = strings.ReplaceAll(f.String(), \"\\n\", \"\")\n\t\t\t}\n\n\t\t\tif tc.err != \"\" {\n\t\t\t\turequire.PanicsWithMessage(t, cur, tc.err, fn, \"expect form textarea to fail\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.NotPanics(t, cur, fn, \"expect form textarea to be created\")\n\t\t\tuassert.Equal(t, tc.markdown, markdown, \"expected markdown to match\")\n\t\t})\n\t}\n}\n\nfunc TestFormSelect(cur realm, t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tinputName string\n\t\tvalue     string\n\t\tattrs     []string\n\t\tmarkdown  string\n\t\terr       string\n\t}{\n\t\t{\n\t\t\tname:      \"ok\",\n\t\t\tinputName: \"test\",\n\t\t\tvalue:     \"foo\",\n\t\t\tattrs:     []string{\"readonly\", \"true\"},\n\t\t\tmarkdown:  `\u003cgno-form\u003e\u003cgno-select name=\"test\" value=\"foo\" readonly=\"true\" /\u003e\u003c/gno-form\u003e`,\n\t\t},\n\t\t{\n\t\t\tname:      \"no attributes\",\n\t\t\tinputName: \"test\",\n\t\t\tvalue:     \"foo\",\n\t\t\tmarkdown:  `\u003cgno-form\u003e\u003cgno-select name=\"test\" value=\"foo\" /\u003e\u003c/gno-form\u003e`,\n\t\t},\n\t\t{\n\t\t\tname:      \"empty name\",\n\t\t\tinputName: \"  \",\n\t\t\terr:       \"form select name is required\",\n\t\t},\n\t\t{\n\t\t\tname:      \"uneven attributes\",\n\t\t\tinputName: \"test\",\n\t\t\tattrs:     []string{\"value\"},\n\t\t\terr:       \"expected an even number of attribute arguments\",\n\t\t},\n\t\t{\n\t\t\tname:      \"invalid attribute\",\n\t\t\tinputName: \"test\",\n\t\t\tattrs:     []string{\"foo\", \"\"},\n\t\t\terr:       \"invalid attribute: foo\",\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tvar markdown string\n\t\t\tfn := func() {\n\t\t\t\tf := mdform.New()\n\t\t\t\tf.Select(tc.inputName, tc.value, tc.attrs...)\n\t\t\t\tmarkdown = strings.ReplaceAll(f.String(), \"\\n\", \"\")\n\t\t\t}\n\n\t\t\tif tc.err != \"\" {\n\t\t\t\turequire.PanicsWithMessage(t, cur, tc.err, fn, \"expect form textarea to fail\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.NotPanics(t, cur, fn, \"expect form textarea to be created\")\n\t\t\tuassert.Equal(t, tc.markdown, markdown, \"expected markdown to match\")\n\t\t})\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"qzITgGZ9DIBUeGMt+3ntZuLFJHyPs7lGx+28I73oq3B6VQQpSzu+dWOj9UiudFzKF9F3eUmtYGJ8NrLvgxfSyQ=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1manfred47kzduec920z88wfr64ylksmdcedlf5","package":{"name":"typeutil","path":"gno.land/p/moul/typeutil","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/typeutil\"\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"},{"name":"typeutil_test.gno","body":"package typeutil\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype testStringer struct {\n\tvalue string\n}\n\nfunc (t testStringer) String() string {\n\treturn \"test:\" + t.value\n}\n\nfunc TestToString(t *testing.T) {\n\t// setup test data\n\tstr := \"hello\"\n\tnum := 42\n\tb := true\n\tnow := time.Now()\n\taddr := address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\tstringer := testStringer{value: \"hello\"}\n\n\ttype testCase struct {\n\t\tname     string\n\t\tinput    any\n\t\texpected string\n\t}\n\n\ttests := []testCase{\n\t\t// basic types\n\t\t{\"string\", \"hello\", \"hello\"},\n\t\t{\"empty_string\", \"\", \"\"},\n\t\t{\"nil\", nil, \"\"},\n\n\t\t// integer types\n\t\t{\"int\", 42, \"42\"},\n\t\t{\"int8\", int8(8), \"8\"},\n\t\t{\"int16\", int16(16), \"16\"},\n\t\t{\"int32\", int32(32), \"32\"},\n\t\t{\"int64\", int64(64), \"64\"},\n\t\t{\"uint\", uint(42), \"42\"},\n\t\t{\"uint8\", uint8(8), \"8\"},\n\t\t{\"uint16\", uint16(16), \"16\"},\n\t\t{\"uint32\", uint32(32), \"32\"},\n\t\t{\"uint64\", uint64(64), \"64\"},\n\n\t\t// float types\n\t\t{\"float32\", float32(3.14), \"3.14\"},\n\t\t{\"float64\", 3.14159, \"3.14159\"},\n\n\t\t// boolean\n\t\t{\"bool_true\", true, \"true\"},\n\t\t{\"bool_false\", false, \"false\"},\n\n\t\t// special types\n\t\t{\"time\", now, now.String()},\n\t\t{\"address\", addr, string(addr)},\n\t\t{\"bytes\", []byte(\"hello\"), \"hello\"},\n\t\t{\"stringer\", stringer, \"test:hello\"},\n\n\t\t// slices\n\t\t{\"empty_slice\", []string{}, \"[]\"},\n\t\t{\"string_slice\", []string{\"a\", \"b\"}, \"[a b]\"},\n\t\t{\"int_slice\", []int{1, 2}, \"[1 2]\"},\n\t\t{\"int32_slice\", []int32{1, 2}, \"[1 2]\"},\n\t\t{\"int64_slice\", []int64{1, 2}, \"[1 2]\"},\n\t\t{\"float32_slice\", []float32{1.1, 2.2}, \"[1.1 2.2]\"},\n\t\t{\"float64_slice\", []float64{1.1, 2.2}, \"[1.1 2.2]\"},\n\t\t{\"bytes_slice\", [][]byte{[]byte(\"a\"), []byte(\"b\")}, \"[a b]\"},\n\t\t{\"time_slice\", []time.Time{now, now}, \"[\" + now.String() + \" \" + now.String() + \"]\"},\n\t\t{\"address_slice\", []address{addr, addr}, \"[\" + string(addr) + \" \" + string(addr) + \"]\"},\n\t\t{\"interface_slice\", []any{1, \"a\", true}, \"[1 a true]\"},\n\n\t\t// empty slices\n\t\t{\"empty_string_slice\", []string{}, \"[]\"},\n\t\t{\"empty_int_slice\", []int{}, \"[]\"},\n\t\t{\"empty_int32_slice\", []int32{}, \"[]\"},\n\t\t{\"empty_int64_slice\", []int64{}, \"[]\"},\n\t\t{\"empty_float32_slice\", []float32{}, \"[]\"},\n\t\t{\"empty_float64_slice\", []float64{}, \"[]\"},\n\t\t{\"empty_bytes_slice\", [][]byte{}, \"[]\"},\n\t\t{\"empty_time_slice\", []time.Time{}, \"[]\"},\n\t\t{\"empty_address_slice\", []address{}, \"[]\"},\n\t\t{\"empty_interface_slice\", []any{}, \"[]\"},\n\n\t\t// maps\n\t\t{\"empty_string_map\", map[string]string{}, \"map[]\"},\n\t\t{\"string_map\", map[string]string{\"a\": \"1\", \"b\": \"2\"}, \"map[a:1 b:2]\"},\n\t\t{\"empty_interface_map\", map[string]any{}, \"map[]\"},\n\t\t{\"interface_map\", map[string]any{\"a\": 1, \"b\": \"2\"}, \"map[a:1 b:2]\"},\n\n\t\t// edge cases\n\t\t{\"empty_bytes\", []byte{}, \"\"},\n\t\t{\"nil_interface\", any(nil), \"\"},\n\t\t{\"empty_struct\", struct{}{}, \"{}\"},\n\t\t{\"unknown_type\", struct{ foo string }{}, \"\u003cunknown\u003e\"},\n\n\t\t// pointer types\n\t\t{\"nil_string_ptr\", (*string)(nil), \"\"},\n\t\t{\"string_ptr\", \u0026str, \"hello\"},\n\t\t{\"nil_int_ptr\", (*int)(nil), \"\"},\n\t\t{\"int_ptr\", \u0026num, \"42\"},\n\t\t{\"nil_bool_ptr\", (*bool)(nil), \"\"},\n\t\t{\"bool_ptr\", \u0026b, \"true\"},\n\t\t// {\"nil_time_ptr\", (*time.Time)(nil), \"\"}, // TODO: fix this\n\t\t{\"time_ptr\", \u0026now, now.String()},\n\t\t// {\"nil_address_ptr\", (*address)(nil), \"\"}, // TODO: fix this\n\t\t{\"address_ptr\", \u0026addr, string(addr)},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := ToString(tt.input)\n\t\t\tif got != tt.expected {\n\t\t\t\tt.Errorf(\"%s: ToString(%v) = %q, want %q\", tt.name, tt.input, got, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestToBool(t *testing.T) {\n\tstr := \"true\"\n\tnum := 42\n\tb := true\n\tnow := time.Now()\n\taddr := address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\tzero := 0\n\tempty := \"\"\n\tfalseVal := false\n\n\ttype testCase struct {\n\t\tname     string\n\t\tinput    any\n\t\texpected bool\n\t}\n\n\ttests := []testCase{\n\t\t// basic types\n\t\t{\"true\", true, true},\n\t\t{\"false\", false, false},\n\t\t{\"nil\", nil, false},\n\n\t\t// strings\n\t\t{\"empty_string\", \"\", false},\n\t\t{\"zero_string\", \"0\", false},\n\t\t{\"false_string\", \"false\", false},\n\t\t{\"f_string\", \"f\", false},\n\t\t{\"no_string\", \"no\", false},\n\t\t{\"n_string\", \"n\", false},\n\t\t{\"off_string\", \"off\", false},\n\t\t{\"space_string\", \" \", false},\n\t\t{\"true_string\", \"true\", true},\n\t\t{\"yes_string\", \"yes\", true},\n\t\t{\"random_string\", \"hello\", true},\n\n\t\t// numbers\n\t\t{\"zero_int\", 0, false},\n\t\t{\"positive_int\", 1, true},\n\t\t{\"negative_int\", -1, true},\n\t\t{\"zero_float\", 0.0, false},\n\t\t{\"positive_float\", 0.1, true},\n\t\t{\"negative_float\", -0.1, true},\n\n\t\t// special types\n\t\t{\"empty_bytes\", []byte{}, false},\n\t\t{\"non_empty_bytes\", []byte{1}, true},\n\t\t/*{\"zero_time\", time.Time{}, false},*/ // TODO: fix this\n\t\t{\"empty_address\", address(\"\"), false},\n\n\t\t// slices\n\t\t{\"empty_slice\", []string{}, false},\n\t\t{\"non_empty_slice\", []string{\"a\"}, true},\n\n\t\t// maps\n\t\t{\"empty_map\", map[string]string{}, false},\n\t\t{\"non_empty_map\", map[string]string{\"a\": \"b\"}, true},\n\n\t\t// pointer types\n\t\t{\"nil_bool_ptr\", (*bool)(nil), false},\n\t\t{\"true_ptr\", \u0026b, true},\n\t\t{\"false_ptr\", \u0026falseVal, false},\n\t\t{\"nil_string_ptr\", (*string)(nil), false},\n\t\t{\"string_ptr\", \u0026str, true},\n\t\t{\"empty_string_ptr\", \u0026empty, false},\n\t\t{\"nil_int_ptr\", (*int)(nil), false},\n\t\t{\"int_ptr\", \u0026num, true},\n\t\t{\"zero_int_ptr\", \u0026zero, false},\n\t\t// {\"nil_time_ptr\", (*time.Time)(nil), false}, // TODO: fix this\n\t\t{\"time_ptr\", \u0026now, true},\n\t\t// {\"nil_address_ptr\", (*address)(nil), false}, // TODO: fix this\n\t\t{\"address_ptr\", \u0026addr, true},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := ToBool(tt.input)\n\t\t\tif got != tt.expected {\n\t\t\t\tt.Errorf(\"%s: ToBool(%v) = %v, want %v\", tt.name, tt.input, got, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestIsZero(t *testing.T) {\n\tstr := \"hello\"\n\tnum := 42\n\tb := true\n\tnow := time.Now()\n\taddr := address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\tzero := 0\n\tempty := \"\"\n\tfalseVal := false\n\n\ttype testCase struct {\n\t\tname     string\n\t\tinput    any\n\t\texpected bool\n\t}\n\n\ttests := []testCase{\n\t\t// basic types\n\t\t{\"true\", true, false},\n\t\t{\"false\", false, true},\n\t\t{\"nil\", nil, true},\n\n\t\t// strings\n\t\t{\"empty_string\", \"\", true},\n\t\t{\"non_empty_string\", \"hello\", false},\n\n\t\t// numbers\n\t\t{\"zero_int\", 0, true},\n\t\t{\"non_zero_int\", 1, false},\n\t\t{\"zero_float\", 0.0, true},\n\t\t{\"non_zero_float\", 0.1, false},\n\n\t\t// special types\n\t\t{\"empty_bytes\", []byte{}, true},\n\t\t{\"non_empty_bytes\", []byte{1}, false},\n\t\t/*{\"zero_time\", time.Time{}, true},*/ // TODO: fix this\n\t\t{\"empty_address\", address(\"\"), true},\n\n\t\t// slices\n\t\t{\"empty_slice\", []string{}, true},\n\t\t{\"non_empty_slice\", []string{\"a\"}, false},\n\n\t\t// maps\n\t\t{\"empty_map\", map[string]string{}, true},\n\t\t{\"non_empty_map\", map[string]string{\"a\": \"b\"}, false},\n\n\t\t// pointer types\n\t\t{\"nil_bool_ptr\", (*bool)(nil), true},\n\t\t{\"false_ptr\", \u0026falseVal, true},\n\t\t{\"true_ptr\", \u0026b, false},\n\t\t{\"nil_string_ptr\", (*string)(nil), true},\n\t\t{\"empty_string_ptr\", \u0026empty, true},\n\t\t{\"string_ptr\", \u0026str, false},\n\t\t{\"nil_int_ptr\", (*int)(nil), true},\n\t\t{\"zero_int_ptr\", \u0026zero, true},\n\t\t{\"int_ptr\", \u0026num, false},\n\t\t// {\"nil_time_ptr\", (*time.Time)(nil), true}, // TODO: fix this\n\t\t{\"time_ptr\", \u0026now, false},\n\t\t// {\"nil_address_ptr\", (*address)(nil), true}, // TODO: fix this\n\t\t{\"address_ptr\", \u0026addr, false},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := IsZero(tt.input)\n\t\t\tif got != tt.expected {\n\t\t\t\tt.Errorf(\"%s: IsZero(%v) = %v, want %v\", tt.name, tt.input, got, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestToInterfaceSlice(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    any\n\t\texpected []any\n\t\tcompare  func([]any, []any) bool\n\t}{\n\t\t{\n\t\t\tname:     \"nil\",\n\t\t\tinput:    nil,\n\t\t\texpected: nil,\n\t\t\tcompare:  compareNil,\n\t\t},\n\t\t{\n\t\t\tname:     \"empty_interface_slice\",\n\t\t\tinput:    []any{},\n\t\t\texpected: []any{},\n\t\t\tcompare:  compareEmpty,\n\t\t},\n\t\t{\n\t\t\tname:     \"interface_slice\",\n\t\t\tinput:    []any{1, \"two\", true},\n\t\t\texpected: []any{1, \"two\", true},\n\t\t\tcompare:  compareInterfaces,\n\t\t},\n\t\t{\n\t\t\tname:     \"string_slice\",\n\t\t\tinput:    []string{\"a\", \"b\", \"c\"},\n\t\t\texpected: []any{\"a\", \"b\", \"c\"},\n\t\t\tcompare:  compareStrings,\n\t\t},\n\t\t{\n\t\t\tname:     \"int_slice\",\n\t\t\tinput:    []int{1, 2, 3},\n\t\t\texpected: []any{1, 2, 3},\n\t\t\tcompare:  compareInts,\n\t\t},\n\t\t{\n\t\t\tname:     \"int32_slice\",\n\t\t\tinput:    []int32{1, 2, 3},\n\t\t\texpected: []any{int32(1), int32(2), int32(3)},\n\t\t\tcompare:  compareInt32s,\n\t\t},\n\t\t{\n\t\t\tname:     \"int64_slice\",\n\t\t\tinput:    []int64{1, 2, 3},\n\t\t\texpected: []any{int64(1), int64(2), int64(3)},\n\t\t\tcompare:  compareInt64s,\n\t\t},\n\t\t{\n\t\t\tname:     \"float32_slice\",\n\t\t\tinput:    []float32{1.1, 2.2, 3.3},\n\t\t\texpected: []any{float32(1.1), float32(2.2), float32(3.3)},\n\t\t\tcompare:  compareFloat32s,\n\t\t},\n\t\t{\n\t\t\tname:     \"float64_slice\",\n\t\t\tinput:    []float64{1.1, 2.2, 3.3},\n\t\t\texpected: []any{1.1, 2.2, 3.3},\n\t\t\tcompare:  compareFloat64s,\n\t\t},\n\t\t{\n\t\t\tname:     \"bool_slice\",\n\t\t\tinput:    []bool{true, false, true},\n\t\t\texpected: []any{true, false, true},\n\t\t\tcompare:  compareBools,\n\t\t},\n\t\t/* {\n\t\t\tname:     \"time_slice\",\n\t\t\tinput:    []time.Time{now},\n\t\t\texpected: []any{now},\n\t\t\tcompare:  compareTimes,\n\t\t}, */ // TODO: fix this\n\t\t/* {\n\t\t\tname:     \"address_slice\",\n\t\t\tinput:    []address{addr},\n\t\t\texpected: []any{addr},\n\t\t\tcompare:  compareAddresses,\n\t\t},*/ // TODO: fix this\n\t\t/* {\n\t\t\tname:     \"bytes_slice\",\n\t\t\tinput:    [][]byte{[]byte(\"hello\"), []byte(\"world\")},\n\t\t\texpected: []any{[]byte(\"hello\"), []byte(\"world\")},\n\t\t\tcompare:  compareBytes,\n\t\t},*/ // TODO: fix this\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := ToInterfaceSlice(tt.input)\n\t\t\tif !tt.compare(got, tt.expected) {\n\t\t\t\tt.Errorf(\"ToInterfaceSlice() = %v, want %v\", got, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc compareNil(a, b []any) bool {\n\treturn a == nil \u0026\u0026 b == nil\n}\n\nfunc compareEmpty(a, b []any) bool {\n\treturn len(a) == 0 \u0026\u0026 len(b) == 0\n}\n\nfunc compareInterfaces(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 compareStrings(a, b []any) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tas, ok1 := a[i].(string)\n\t\tbs, ok2 := b[i].(string)\n\t\tif !ok1 || !ok2 || as != bs {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc compareInts(a, b []any) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tai, ok1 := a[i].(int)\n\t\tbi, ok2 := b[i].(int)\n\t\tif !ok1 || !ok2 || ai != bi {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc compareInt32s(a, b []any) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tai, ok1 := a[i].(int32)\n\t\tbi, ok2 := b[i].(int32)\n\t\tif !ok1 || !ok2 || ai != bi {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc compareInt64s(a, b []any) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tai, ok1 := a[i].(int64)\n\t\tbi, ok2 := b[i].(int64)\n\t\tif !ok1 || !ok2 || ai != bi {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc compareFloat32s(a, b []any) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tai, ok1 := a[i].(float32)\n\t\tbi, ok2 := b[i].(float32)\n\t\tif !ok1 || !ok2 || ai != bi {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc compareFloat64s(a, b []any) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tai, ok1 := a[i].(float64)\n\t\tbi, ok2 := b[i].(float64)\n\t\tif !ok1 || !ok2 || ai != bi {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc compareBools(a, b []any) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tab, ok1 := a[i].(bool)\n\t\tbb, ok2 := b[i].(bool)\n\t\tif !ok1 || !ok2 || ab != bb {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc compareTimes(a, b []any) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tat, ok1 := a[i].(time.Time)\n\t\tbt, ok2 := b[i].(time.Time)\n\t\tif !ok1 || !ok2 || !at.Equal(bt) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc compareAddresses(a, b []any) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\taa, ok1 := a[i].(address)\n\t\tba, ok2 := b[i].(address)\n\t\tif !ok1 || !ok2 || aa != ba {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc compareBytes(a, b []any) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tab, ok1 := a[i].([]byte)\n\t\tbb, ok2 := b[i].([]byte)\n\t\tif !ok1 || !ok2 || string(ab) != string(bb) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// compareStringInterfaceMaps compares two map[string]any for equality\nfunc compareStringInterfaceMaps(a, b map[string]any) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor k, v1 := range a {\n\t\tv2, ok := b[k]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\t// Compare values based on their type\n\t\tswitch val1 := v1.(type) {\n\t\tcase string:\n\t\t\tval2, ok := v2.(string)\n\t\t\tif !ok || val1 != val2 {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase int:\n\t\t\tval2, ok := v2.(int)\n\t\t\tif !ok || val1 != val2 {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase float64:\n\t\t\tval2, ok := v2.(float64)\n\t\t\tif !ok || val1 != val2 {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase bool:\n\t\t\tval2, ok := v2.(bool)\n\t\t\tif !ok || val1 != val2 {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase []any:\n\t\t\tval2, ok := v2.([]any)\n\t\t\tif !ok || len(val1) != len(val2) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfor i := range val1 {\n\t\t\t\tif val1[i] != val2[i] {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\tcase map[string]any:\n\t\t\tval2, ok := v2.(map[string]any)\n\t\t\tif !ok || !compareStringInterfaceMaps(val1, val2) {\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\nfunc TestToMapStringInterface(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    any\n\t\texpected map[string]any\n\t\twantErr  bool\n\t}{\n\t\t{\n\t\t\tname: \"map[string]any\",\n\t\t\tinput: map[string]any{\n\t\t\t\t\"key1\": \"value1\",\n\t\t\t\t\"key2\": 42,\n\t\t\t},\n\t\t\texpected: map[string]any{\n\t\t\t\t\"key1\": \"value1\",\n\t\t\t\t\"key2\": 42,\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"map[string]string\",\n\t\t\tinput: map[string]string{\n\t\t\t\t\"key1\": \"value1\",\n\t\t\t\t\"key2\": \"value2\",\n\t\t\t},\n\t\t\texpected: map[string]any{\n\t\t\t\t\"key1\": \"value1\",\n\t\t\t\t\"key2\": \"value2\",\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"map[string]int\",\n\t\t\tinput: map[string]int{\n\t\t\t\t\"key1\": 1,\n\t\t\t\t\"key2\": 2,\n\t\t\t},\n\t\t\texpected: map[string]any{\n\t\t\t\t\"key1\": 1,\n\t\t\t\t\"key2\": 2,\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"map[string]float64\",\n\t\t\tinput: map[string]float64{\n\t\t\t\t\"key1\": 1.1,\n\t\t\t\t\"key2\": 2.2,\n\t\t\t},\n\t\t\texpected: map[string]any{\n\t\t\t\t\"key1\": 1.1,\n\t\t\t\t\"key2\": 2.2,\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"map[string]bool\",\n\t\t\tinput: map[string]bool{\n\t\t\t\t\"key1\": true,\n\t\t\t\t\"key2\": false,\n\t\t\t},\n\t\t\texpected: map[string]any{\n\t\t\t\t\"key1\": true,\n\t\t\t\t\"key2\": false,\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"map[string][]string\",\n\t\t\tinput: map[string][]string{\n\t\t\t\t\"key1\": {\"a\", \"b\"},\n\t\t\t\t\"key2\": {\"c\", \"d\"},\n\t\t\t},\n\t\t\texpected: map[string]any{\n\t\t\t\t\"key1\": []any{\"a\", \"b\"},\n\t\t\t\t\"key2\": []any{\"c\", \"d\"},\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"nested map[string]map[string]string\",\n\t\t\tinput: map[string]map[string]string{\n\t\t\t\t\"key1\": {\"nested1\": \"value1\"},\n\t\t\t\t\"key2\": {\"nested2\": \"value2\"},\n\t\t\t},\n\t\t\texpected: map[string]any{\n\t\t\t\t\"key1\": map[string]any{\"nested1\": \"value1\"},\n\t\t\t\t\"key2\": map[string]any{\"nested2\": \"value2\"},\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname:     \"unsupported type\",\n\t\t\tinput:    42, // not a map\n\t\t\texpected: nil,\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\tgot, err := ToMapStringInterface(tt.input)\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"ToMapStringInterface() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif !tt.wantErr {\n\t\t\t\tif !compareStringInterfaceMaps(got, tt.expected) {\n\t\t\t\t\tt.Errorf(\"ToMapStringInterface() = %v, expected %v\", got, tt.expected)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Test error messages\nfunc TestToMapStringInterfaceErrors(t *testing.T) {\n\t_, err := ToMapStringInterface(42)\n\tif err == nil || !strings.Contains(err.Error(), \"unsupported map type\") {\n\t\tt.Errorf(\"Expected error containing 'unsupported map type', got %v\", err)\n\t}\n}\n\n// compareIntInterfaceMaps compares two map[int]any for equality\nfunc compareIntInterfaceMaps(a, b map[int]any) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor k, v1 := range a {\n\t\tv2, ok := b[k]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\t// Compare values based on their type\n\t\tswitch val1 := v1.(type) {\n\t\tcase string:\n\t\t\tval2, ok := v2.(string)\n\t\t\tif !ok || val1 != val2 {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase int:\n\t\t\tval2, ok := v2.(int)\n\t\t\tif !ok || val1 != val2 {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase float64:\n\t\t\tval2, ok := v2.(float64)\n\t\t\tif !ok || val1 != val2 {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase bool:\n\t\t\tval2, ok := v2.(bool)\n\t\t\tif !ok || val1 != val2 {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase []any:\n\t\t\tval2, ok := v2.([]any)\n\t\t\tif !ok || len(val1) != len(val2) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfor i := range val1 {\n\t\t\t\tif val1[i] != val2[i] {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\tcase map[string]any:\n\t\t\tval2, ok := v2.(map[string]any)\n\t\t\tif !ok || !compareStringInterfaceMaps(val1, val2) {\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\nfunc TestToMapIntInterface(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    any\n\t\texpected map[int]any\n\t\twantErr  bool\n\t}{\n\t\t{\n\t\t\tname: \"map[int]any\",\n\t\t\tinput: map[int]any{\n\t\t\t\t1: \"value1\",\n\t\t\t\t2: 42,\n\t\t\t},\n\t\t\texpected: map[int]any{\n\t\t\t\t1: \"value1\",\n\t\t\t\t2: 42,\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"map[int]string\",\n\t\t\tinput: map[int]string{\n\t\t\t\t1: \"value1\",\n\t\t\t\t2: \"value2\",\n\t\t\t},\n\t\t\texpected: map[int]any{\n\t\t\t\t1: \"value1\",\n\t\t\t\t2: \"value2\",\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"map[int]int\",\n\t\t\tinput: map[int]int{\n\t\t\t\t1: 10,\n\t\t\t\t2: 20,\n\t\t\t},\n\t\t\texpected: map[int]any{\n\t\t\t\t1: 10,\n\t\t\t\t2: 20,\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"map[int]float64\",\n\t\t\tinput: map[int]float64{\n\t\t\t\t1: 1.1,\n\t\t\t\t2: 2.2,\n\t\t\t},\n\t\t\texpected: map[int]any{\n\t\t\t\t1: 1.1,\n\t\t\t\t2: 2.2,\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"map[int]bool\",\n\t\t\tinput: map[int]bool{\n\t\t\t\t1: true,\n\t\t\t\t2: false,\n\t\t\t},\n\t\t\texpected: map[int]any{\n\t\t\t\t1: true,\n\t\t\t\t2: false,\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"map[int][]string\",\n\t\t\tinput: map[int][]string{\n\t\t\t\t1: {\"a\", \"b\"},\n\t\t\t\t2: {\"c\", \"d\"},\n\t\t\t},\n\t\t\texpected: map[int]any{\n\t\t\t\t1: []any{\"a\", \"b\"},\n\t\t\t\t2: []any{\"c\", \"d\"},\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"map[int]map[string]any\",\n\t\t\tinput: map[int]map[string]any{\n\t\t\t\t1: {\"nested1\": \"value1\"},\n\t\t\t\t2: {\"nested2\": \"value2\"},\n\t\t\t},\n\t\t\texpected: map[int]any{\n\t\t\t\t1: map[string]any{\"nested1\": \"value1\"},\n\t\t\t\t2: map[string]any{\"nested2\": \"value2\"},\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname:     \"unsupported type\",\n\t\t\tinput:    42, // not a map\n\t\t\texpected: nil,\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\tgot, err := ToMapIntInterface(tt.input)\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"ToMapIntInterface() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif !tt.wantErr {\n\t\t\t\tif !compareIntInterfaceMaps(got, tt.expected) {\n\t\t\t\t\tt.Errorf(\"ToMapIntInterface() = %v, expected %v\", got, tt.expected)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestToStringSlice(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    any\n\t\texpected []string\n\t}{\n\t\t{\n\t\t\tname:     \"nil input\",\n\t\t\tinput:    nil,\n\t\t\texpected: nil,\n\t\t},\n\t\t{\n\t\t\tname:     \"empty slice\",\n\t\t\tinput:    []string{},\n\t\t\texpected: []string{},\n\t\t},\n\t\t{\n\t\t\tname:     \"string slice\",\n\t\t\tinput:    []string{\"a\", \"b\", \"c\"},\n\t\t\texpected: []string{\"a\", \"b\", \"c\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"int slice\",\n\t\t\tinput:    []int{1, 2, 3},\n\t\t\texpected: []string{\"1\", \"2\", \"3\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"int32 slice\",\n\t\t\tinput:    []int32{1, 2, 3},\n\t\t\texpected: []string{\"1\", \"2\", \"3\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"int64 slice\",\n\t\t\tinput:    []int64{1, 2, 3},\n\t\t\texpected: []string{\"1\", \"2\", \"3\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"uint slice\",\n\t\t\tinput:    []uint{1, 2, 3},\n\t\t\texpected: []string{\"1\", \"2\", \"3\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"uint8 slice\",\n\t\t\tinput:    []uint8{1, 2, 3},\n\t\t\texpected: []string{\"1\", \"2\", \"3\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"uint16 slice\",\n\t\t\tinput:    []uint16{1, 2, 3},\n\t\t\texpected: []string{\"1\", \"2\", \"3\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"uint32 slice\",\n\t\t\tinput:    []uint32{1, 2, 3},\n\t\t\texpected: []string{\"1\", \"2\", \"3\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"uint64 slice\",\n\t\t\tinput:    []uint64{1, 2, 3},\n\t\t\texpected: []string{\"1\", \"2\", \"3\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"float32 slice\",\n\t\t\tinput:    []float32{1.1, 2.2, 3.3},\n\t\t\texpected: []string{\"1.1\", \"2.2\", \"3.3\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"float64 slice\",\n\t\t\tinput:    []float64{1.1, 2.2, 3.3},\n\t\t\texpected: []string{\"1.1\", \"2.2\", \"3.3\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"bool slice\",\n\t\t\tinput:    []bool{true, false, true},\n\t\t\texpected: []string{\"true\", \"false\", \"true\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"[]byte slice\",\n\t\t\tinput:    [][]byte{[]byte(\"hello\"), []byte(\"world\")},\n\t\t\texpected: []string{\"hello\", \"world\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"interface slice\",\n\t\t\tinput:    []any{1, \"hello\", true},\n\t\t\texpected: []string{\"1\", \"hello\", \"true\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"time slice\",\n\t\t\tinput:    []time.Time{{}, {}},\n\t\t\texpected: []string{\"0001-01-01 00:00:00 +0000 UTC\", \"0001-01-01 00:00:00 +0000 UTC\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"address slice\",\n\t\t\tinput:    []address{\"addr1\", \"addr2\"},\n\t\t\texpected: []string{\"addr1\", \"addr2\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"non-slice input\",\n\t\t\tinput:    42,\n\t\t\texpected: nil,\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 := ToStringSlice(tt.input)\n\t\t\tif !slicesEqual(result, tt.expected) {\n\t\t\t\tt.Errorf(\"ToStringSlice(%v) = %v, want %v\", tt.input, result, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Helper function to compare string slices\nfunc slicesEqual(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 TestToStringAdvanced(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    any\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname: \"slice with mixed basic types\",\n\t\t\tinput: []any{\n\t\t\t\t42,\n\t\t\t\t\"hello\",\n\t\t\t\ttrue,\n\t\t\t\t3.14,\n\t\t\t},\n\t\t\texpected: \"[42 hello true 3.14]\",\n\t\t},\n\t\t{\n\t\t\tname: \"map with basic types\",\n\t\t\tinput: map[string]any{\n\t\t\t\t\"int\":   42,\n\t\t\t\t\"str\":   \"hello\",\n\t\t\t\t\"bool\":  true,\n\t\t\t\t\"float\": 3.14,\n\t\t\t},\n\t\t\texpected: \"map[bool:true float:3.14 int:42 str:hello]\",\n\t\t},\n\t\t{\n\t\t\tname: \"mixed types map\",\n\t\t\tinput: map[any]any{\n\t\t\t\t42:         \"number\",\n\t\t\t\t\"string\":   123,\n\t\t\t\ttrue:       []int{1, 2, 3},\n\t\t\t\tstruct{}{}: \"empty\",\n\t\t\t},\n\t\t\texpected: \"map[42:number string:123 true:[1 2 3] {}:empty]\",\n\t\t},\n\t\t{\n\t\t\tname: \"nested maps\",\n\t\t\tinput: map[string]any{\n\t\t\t\t\"a\": map[string]int{\n\t\t\t\t\t\"x\": 1,\n\t\t\t\t\t\"y\": 2,\n\t\t\t\t},\n\t\t\t\t\"b\": []any{1, \"two\", true},\n\t\t\t},\n\t\t\texpected: \"map[a:map[x:1 y:2] b:[1 two true]]\",\n\t\t},\n\t\t{\n\t\t\tname:     \"empty struct\",\n\t\t\tinput:    struct{}{},\n\t\t\texpected: \"{}\",\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 := ToString(tt.input)\n\t\t\tif result != tt.expected {\n\t\t\t\tt.Errorf(\"\\nToString(%v) =\\n%v\\nwant:\\n%v\", tt.input, result, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"a6t635f5GTOAH0tDElOD5mluH/B9h4QN9t645kXTiZ0hnU7BZwYklH137XapiFUvCsRXaDhpKeuvfvrj+lqdsw=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1manfred47kzduec920z88wfr64ylksmdcedlf5","package":{"name":"ulist","path":"gno.land/p/moul/ulist","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/ulist\"\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"},{"name":"ulist_test.gno","body":"package ulist\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/typeutil\"\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"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"zo9TaTJ5Xaf3gcxp9FfOP/7PdM+a1LVbMhN7FJYNPh0zRZcjYiZ17dcopRtFxnY5HN5fKzZKe0f1KWAPgT60Hg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"message","path":"gno.land/p/jeronimoalbi/message","files":[{"name":"broker.gno","body":"package message\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"gno.land/p/moul/ulist\"\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":"broker_filetest.gno","body":"package main\n\nimport (\n\t\"gno.land/p/jeronimoalbi/message\"\n)\n\nfunc main() {\n\t// Create a message broker and a generic message callback\n\tbroker := message.NewBroker()\n\tcb := func(m message.Message) {\n\t\tprintln(\"topic triggered: \" + string(m.Topic))\n\t\tprintln(\"topic data: \" + m.Data.(string))\n\t}\n\n\t// Subscribe to a couple of events\n\t_, err := broker.Subscribe(\"eventA\", cb)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t_, err = broker.Subscribe(\"eventB\", cb)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Subscribe to an event and then unsubscribe from it\n\tid, err := broker.Subscribe(\"eventC\", cb)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t_, err = broker.Unsubscribe(\"eventC\", id)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Subscribe to all events\n\t_, err = broker.Subscribe(message.TopicAll, func(m message.Message) {\n\t\tprintln(\"catchall topic triggered: \" + string(m.Topic))\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// List broker topics\n\tprintln(\"topics:\")\n\tfor _, topic := range broker.Topics() {\n\t\tprintln(\"- \" + string(topic))\n\t}\n\n\t// Publish events\n\tprintln()\n\tif err = broker.Publish(\"eventA\", \"A\"); err != nil {\n\t\tpanic(err)\n\t}\n\n\tprintln()\n\tif err = broker.Publish(\"eventB\", \"B\"); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n// Output:\n// topics:\n// - eventA\n// - eventB\n// - eventC\n//\n// topic triggered: eventA\n// topic data: A\n// catchall topic triggered: eventA\n//\n// topic triggered: eventB\n// topic data: B\n// catchall topic triggered: eventB\n"},{"name":"broker_test.gno","body":"package message_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/jeronimoalbi/expect\"\n\t\"gno.land/p/jeronimoalbi/message\"\n)\n\nvar (\n\t_ message.Subscriber = (*message.Broker)(nil)\n\t_ message.Publisher  = (*message.Broker)(nil)\n)\n\nfunc TestBrokerTopics(t *testing.T) {\n\tbroker := message.NewBroker()\n\texpect.\n\t\tValue(t, len(broker.Topics())).\n\t\tAsInt().\n\t\tToEqual(0)\n\n\tcb := func(message.Message) {}\n\tbroker.Subscribe(\"foo\", cb)\n\tbroker.Subscribe(\"bar\", cb)\n\tbroker.Subscribe(\"baz\", cb)\n\tbroker.Subscribe(message.TopicAll, cb)\n\ttopics := broker.Topics()\n\n\texpect.\n\t\tValue(t, len(topics)).\n\t\tAsInt().\n\t\tToEqual(3)\n\texpect.\n\t\tValue(t, string(topics[0])).\n\t\tAsString().\n\t\tToEqual(\"bar\")\n\texpect.\n\t\tValue(t, string(topics[1])).\n\t\tAsString().\n\t\tToEqual(\"baz\")\n\texpect.\n\t\tValue(t, string(topics[2])).\n\t\tAsString().\n\t\tToEqual(\"foo\")\n}\n\nfunc TestBrokerPublish(t *testing.T) {\n\ttests := []struct {\n\t\tname               string\n\t\tsubscribe, publish message.Topic\n\t\tdata               any\n\t\tmessage            *message.Message\n\t\terr                error\n\t}{\n\t\t{\n\t\t\tname:      \"publishes subscribed topic\",\n\t\t\tsubscribe: \"foo\",\n\t\t\tpublish:   \"foo\",\n\t\t\tdata:      \"foo's data\",\n\t\t\tmessage: \u0026message.Message{\n\t\t\t\tTopic: \"foo\",\n\t\t\t\tData:  \"foo's data\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:      \"publishes all topics\",\n\t\t\tsubscribe: message.TopicAll,\n\t\t\tpublish:   \"foo\",\n\t\t\tdata:      \"foo's data\",\n\t\t\tmessage: \u0026message.Message{\n\t\t\t\tTopic: \"foo\",\n\t\t\t\tData:  \"foo's data\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:      \"invalid topic\",\n\t\t\tsubscribe: \"foo\",\n\t\t\tpublish:   message.TopicAll,\n\t\t\terr:       message.ErrInvalidTopic,\n\t\t},\n\t\t{\n\t\t\tname:      \"no topic\",\n\t\t\tsubscribe: \"foo\",\n\t\t\tpublish:   \"\",\n\t\t\terr:       message.ErrRequiredTopic,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t// Arrange\n\t\t\tvar msg *message.Message\n\t\t\tbroker := message.NewBroker()\n\t\t\tbroker.Subscribe(tt.subscribe, func(m message.Message) { msg = \u0026m })\n\n\t\t\t// Act\n\t\t\terr := broker.Publish(tt.publish, tt.data)\n\n\t\t\t// Assert\n\t\t\tif tt.err != nil {\n\t\t\t\texpect.\n\t\t\t\t\tFunc(t, func() error { return err }).\n\t\t\t\t\tWithFailPrefix(\"expect a publish error\").\n\t\t\t\t\tToFail().\n\t\t\t\t\tWithError(tt.err)\n\t\t\t\texpect.\n\t\t\t\t\tValue(t, istypednil(msg)).\n\t\t\t\t\tWithFailPrefix(\"expect callback not to be called\").\n\t\t\t\t\tAsBoolean().\n\t\t\t\t\tToBeTruthy()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\texpect.\n\t\t\t\tValue(t, err).\n\t\t\t\tWithFailPrefix(\"expect no publish error\").\n\t\t\t\tToBeNil()\n\t\t\texpect.\n\t\t\t\tValue(t, msg).\n\t\t\t\tWithFailPrefix(\"expect callback to be called\").\n\t\t\t\tNot().ToBeNil()\n\t\t\texpect.\n\t\t\t\tValue(t, string(msg.Topic)).\n\t\t\t\tWithFailPrefix(\"expect message topic to match\").\n\t\t\t\tAsString().\n\t\t\t\tToEqual(string(tt.message.Topic))\n\t\t\texpect.\n\t\t\t\tValue(t, msg.Data).\n\t\t\t\tWithFailPrefix(\"expect message data to match\").\n\t\t\t\tAsString().\n\t\t\t\tToEqual(tt.message.Data.(string))\n\t\t})\n\t}\n}\n\nfunc TestBrokerSubscribe(t *testing.T) {\n\tcb := func(message.Message) {}\n\ttests := []struct {\n\t\tname     string\n\t\tsetup    func(*message.Broker)\n\t\ttopic    message.Topic\n\t\tid       int64\n\t\tcallback message.Callback\n\t\terr      error\n\t}{\n\t\t{\n\t\t\tname:     \"single subscription\",\n\t\t\ttopic:    \"foo\",\n\t\t\tid:       1,\n\t\t\tcallback: cb,\n\t\t},\n\t\t{\n\t\t\tname: \"existing subscriptions\",\n\t\t\tsetup: func(b *message.Broker) {\n\t\t\t\tb.Subscribe(\"foo\", cb)\n\t\t\t},\n\t\t\ttopic:    \"foo\",\n\t\t\tid:       2,\n\t\t\tcallback: cb,\n\t\t},\n\t\t{\n\t\t\tname: \"other subscription topics\",\n\t\t\tsetup: func(b *message.Broker) {\n\t\t\t\tb.Subscribe(\"foo\", cb)\n\t\t\t},\n\t\t\ttopic:    \"bar\",\n\t\t\tid:       1,\n\t\t\tcallback: cb,\n\t\t},\n\t\t{\n\t\t\tname:  \"no topic\",\n\t\t\ttopic: \"\",\n\t\t\terr:   message.ErrRequiredTopic,\n\t\t},\n\t\t{\n\t\t\tname:     \"no callback\",\n\t\t\ttopic:    \"foo\",\n\t\t\tcallback: nil,\n\t\t\terr:      message.ErrRequiredCallback,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t// Arrange\n\t\t\tbroker := message.NewBroker()\n\t\t\tif tt.setup != nil {\n\t\t\t\ttt.setup(broker)\n\t\t\t}\n\n\t\t\t// Act\n\t\t\tid, err := broker.Subscribe(tt.topic, tt.callback)\n\n\t\t\t// Assert\n\t\t\tif tt.err != nil {\n\t\t\t\texpect.\n\t\t\t\t\tFunc(t, func() error { return err }).\n\t\t\t\t\tWithFailPrefix(\"expect a subscribe error\").\n\t\t\t\t\tToFail().\n\t\t\t\t\tWithError(tt.err)\n\t\t\t\texpect.\n\t\t\t\t\tValue(t, id).\n\t\t\t\t\tWithFailPrefix(\"expect zero ID\").\n\t\t\t\t\tAsInt().\n\t\t\t\t\tToEqual(0)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\texpect.\n\t\t\t\tValue(t, err).\n\t\t\t\tWithFailPrefix(\"expect no subscribe error\").\n\t\t\t\tToBeNil()\n\t\t\texpect.\n\t\t\t\tValue(t, id).\n\t\t\t\tWithFailPrefix(\"expect ID to match\").\n\t\t\t\tAsInt().\n\t\t\t\tToEqual(tt.id)\n\t\t})\n\t}\n}\n\nfunc TestBrokerUnsubscribe(t *testing.T) {\n\tcb := func(message.Message) {}\n\ttests := []struct {\n\t\tname   string\n\t\tsetup  func(*message.Broker)\n\t\ttopic  message.Topic\n\t\tid     int\n\t\terrMsg string\n\t}{\n\t\t{\n\t\t\tname: \"single subscription\",\n\t\t\tsetup: func(b *message.Broker) {\n\t\t\t\tb.Subscribe(\"foo\", cb)\n\t\t\t},\n\t\t\ttopic: \"foo\",\n\t\t\tid:    1,\n\t\t},\n\t\t{\n\t\t\tname: \"multiple subscriptions\",\n\t\t\tsetup: func(b *message.Broker) {\n\t\t\t\tb.Subscribe(\"foo\", cb)\n\t\t\t\tb.Subscribe(\"foo\", cb)\n\t\t\t},\n\t\t\ttopic: \"foo\",\n\t\t\tid:    2,\n\t\t},\n\t\t{\n\t\t\tname: \"other subscription topics\",\n\t\t\tsetup: func(b *message.Broker) {\n\t\t\t\tb.Subscribe(\"foo\", cb)\n\t\t\t\tb.Subscribe(\"bar\", cb)\n\t\t\t},\n\t\t\ttopic: \"foo\",\n\t\t\tid:    1,\n\t\t},\n\t\t{\n\t\t\tname:   \"not found\",\n\t\t\ttopic:  \"foo\",\n\t\t\tid:     1,\n\t\t\terrMsg: \"message topic not found: foo\",\n\t\t},\n\t\t{\n\t\t\tname:   \"no topic\",\n\t\t\ttopic:  \"\",\n\t\t\terrMsg: message.ErrRequiredTopic.Error(),\n\t\t},\n\t\t{\n\t\t\tname:   \"no subscription ID\",\n\t\t\ttopic:  \"foo\",\n\t\t\tid:     0,\n\t\t\terrMsg: message.ErrRequiredSubscriptionID.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\t// Arrange\n\t\t\tbroker := message.NewBroker()\n\t\t\tif tt.setup != nil {\n\t\t\t\ttt.setup(broker)\n\t\t\t}\n\n\t\t\t// Act\n\t\t\tunsubscribed, err := broker.Unsubscribe(tt.topic, tt.id)\n\n\t\t\t// Assert\n\t\t\tif tt.errMsg != \"\" {\n\t\t\t\texpect.\n\t\t\t\t\tFunc(t, func() error { return err }).\n\t\t\t\t\tWithFailPrefix(\"expect a subscribe error\").\n\t\t\t\t\tToFail().\n\t\t\t\t\tWithMessage(tt.errMsg)\n\t\t\t\texpect.\n\t\t\t\t\tValue(t, unsubscribed).\n\t\t\t\t\tWithFailPrefix(\"expect unsubscribe to fail\").\n\t\t\t\t\tAsBoolean().\n\t\t\t\t\tToBeFalsy()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\texpect.\n\t\t\t\tValue(t, err).\n\t\t\t\tWithFailPrefix(\"expect no unsubscribe error\").\n\t\t\t\tToBeNil()\n\t\t\texpect.\n\t\t\t\tValue(t, unsubscribed).\n\t\t\t\tWithFailPrefix(\"expect unsubscribe to succeed\").\n\t\t\t\tAsBoolean().\n\t\t\t\tToBeTruthy()\n\t\t})\n\t}\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\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"/3CGv6bBTywbCadOwYIbMfcx9WGtr8NNsKa1dvlzWFdgHLmX/AtJ2oEmkgTtzvotC2qVg+TedeGFN3/kX44ugQ=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"pager","path":"gno.land/p/jeronimoalbi/pager","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/jeronimoalbi/pager\"\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\"\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"},{"name":"pager_test.gno","body":"package pager\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 TestPager(t *testing.T) {\n\tcases := []struct {\n\t\tname, uri, prevPath, nextPath, param string\n\t\toffset, pageSize, page, pageCount    int\n\t\thasPages                             bool\n\t\titems                                []int\n\t\terr                                  error\n\t}{\n\t\t{\n\t\t\tname:      \"page 1\",\n\t\t\turi:       \"gno.land/r/demo/test:foo/bar?page=1\u0026foo=bar\",\n\t\t\titems:     []int{1, 2, 3, 4, 5, 6},\n\t\t\thasPages:  true,\n\t\t\tnextPath:  \"?foo=bar\u0026page=2\",\n\t\t\tpageSize:  5,\n\t\t\tpage:      1,\n\t\t\tpageCount: 2,\n\t\t},\n\t\t{\n\t\t\tname:      \"page 2\",\n\t\t\turi:       \"gno.land/r/demo/test:foo/bar?page=2\u0026foo=bar\",\n\t\t\titems:     []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},\n\t\t\thasPages:  true,\n\t\t\tprevPath:  \"?foo=bar\u0026page=1\",\n\t\t\tnextPath:  \"\",\n\t\t\toffset:    5,\n\t\t\tpageSize:  5,\n\t\t\tpage:      2,\n\t\t\tpageCount: 2,\n\t\t},\n\t\t{\n\t\t\tname:      \"custom query param\",\n\t\t\turi:       \"gno.land/r/demo/test:foo/bar?current=2\u0026foo=bar\",\n\t\t\titems:     []int{1, 2, 3},\n\t\t\tparam:     \"current\",\n\t\t\thasPages:  true,\n\t\t\tprevPath:  \"?current=1\u0026foo=bar\",\n\t\t\tnextPath:  \"\",\n\t\t\toffset:    2,\n\t\t\tpageSize:  2,\n\t\t\tpage:      2,\n\t\t\tpageCount: 2,\n\t\t},\n\t\t{\n\t\t\tname: \"missing page\",\n\t\t\turi:  \"gno.land/r/demo/test:foo/bar?page=3\u0026foo=bar\",\n\t\t\terr:  ErrInvalidPageNumber,\n\t\t},\n\t\t{\n\t\t\tname: \"invalid page zero\",\n\t\t\turi:  \"gno.land/r/demo/test:foo/bar?page=0\",\n\t\t\terr:  ErrInvalidPageNumber,\n\t\t},\n\t\t{\n\t\t\tname: \"invalid page number\",\n\t\t\turi:  \"gno.land/r/demo/test:foo/bar?page=foo\",\n\t\t\terr:  ErrInvalidPageNumber,\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t// Act\n\t\t\tp, err := New(tc.uri, len(tc.items), WithPageSize(tc.pageSize), WithPageQueryParam(tc.param))\n\n\t\t\t// Assert\n\t\t\tif tc.err != nil {\n\t\t\t\turequire.ErrorIs(t, err, tc.err, \"expected an error\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.NoError(t, err, \"expect no error\")\n\t\t\tuassert.Equal(t, len(tc.items), p.TotalItems(), \"total items\")\n\t\t\tuassert.Equal(t, tc.page, p.Page(), \"page number\")\n\t\t\tuassert.Equal(t, tc.pageCount, p.PageCount(), \"number of pages\")\n\t\t\tuassert.Equal(t, tc.pageSize, p.PageSize(), \"page size\")\n\t\t\tuassert.Equal(t, tc.prevPath, p.PrevPageURI(), \"prev URL page\")\n\t\t\tuassert.Equal(t, tc.nextPath, p.NextPageURI(), \"next URL page\")\n\t\t\tuassert.Equal(t, tc.hasPages, p.HasPages(), \"has pages\")\n\t\t\tuassert.Equal(t, tc.offset, p.Offset(), \"item offset\")\n\t\t})\n\t}\n}\n\nfunc TestPagerIterate(t *testing.T) {\n\tcases := []struct {\n\t\tname, uri   string\n\t\titems, page []int\n\t\tstop        bool\n\t}{\n\t\t{\n\t\t\tname:  \"page 1\",\n\t\t\turi:   \"gno.land/r/demo/test:foo/bar?page=1\",\n\t\t\titems: []int{1, 2, 3, 4, 5, 6, 7},\n\t\t\tpage:  []int{1, 2, 3},\n\t\t},\n\t\t{\n\t\t\tname:  \"page 2\",\n\t\t\turi:   \"gno.land/r/demo/test:foo/bar?page=2\",\n\t\t\titems: []int{1, 2, 3, 4, 5, 6, 7},\n\t\t\tpage:  []int{4, 5, 6},\n\t\t},\n\t\t{\n\t\t\tname:  \"page 3\",\n\t\t\turi:   \"gno.land/r/demo/test:foo/bar?page=3\",\n\t\t\titems: []int{1, 2, 3, 4, 5, 6, 7},\n\t\t\tpage:  []int{7},\n\t\t},\n\t\t{\n\t\t\tname:  \"stop iteration\",\n\t\t\turi:   \"gno.land/r/demo/test:foo/bar?page=1\",\n\t\t\titems: []int{1, 2, 3},\n\t\t\tstop:  true,\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t// Arrange\n\t\t\tvar (\n\t\t\t\titems []int\n\t\t\t\tp     = MustNew(tc.uri, len(tc.items), WithPageSize(3))\n\t\t\t)\n\n\t\t\t// Act\n\t\t\tstopped := p.Iterate(func(i int) bool {\n\t\t\t\tif tc.stop {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t\titems = append(items, tc.items[i])\n\t\t\t\treturn false\n\t\t\t})\n\n\t\t\t// Assert\n\t\t\tuassert.Equal(t, tc.stop, stopped)\n\t\t\turequire.Equal(t, len(tc.page), len(items), \"expect iteration of the right number of items\")\n\n\t\t\tfor i, v := range items {\n\t\t\t\turequire.Equal(t, tc.page[i], v, \"expect iterated items to match\")\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestPicker(t *testing.T) {\n\tpageSize := 3\n\tcases := []struct {\n\t\tname, uri, output string\n\t\ttotalItems        int\n\t}{\n\t\t{\n\t\t\tname:       \"one page\",\n\t\t\turi:        \"gno.land/r/demo/test:foo/bar?page=1\",\n\t\t\ttotalItems: 3,\n\t\t\toutput:     \"\",\n\t\t},\n\t\t{\n\t\t\tname:       \"two pages\",\n\t\t\turi:        \"gno.land/r/demo/test:foo/bar?page=1\",\n\t\t\ttotalItems: 4,\n\t\t\toutput:     \"\\\\- | page 1 of 2 | [»](?page=2)\",\n\t\t},\n\t\t{\n\t\t\tname:       \"three pages\",\n\t\t\turi:        \"gno.land/r/demo/test:foo/bar?page=1\",\n\t\t\ttotalItems: 7,\n\t\t\toutput:     \"\\\\- | page 1 of 3 | [»](?page=2)\",\n\t\t},\n\t\t{\n\t\t\tname:       \"three pages second page\",\n\t\t\turi:        \"gno.land/r/demo/test:foo/bar?page=2\",\n\t\t\ttotalItems: 7,\n\t\t\toutput:     \"[«](?page=1) | page 2 of 3 | [»](?page=3)\",\n\t\t},\n\t\t{\n\t\t\tname:       \"three pages third page\",\n\t\t\turi:        \"gno.land/r/demo/test:foo/bar?page=3\",\n\t\t\ttotalItems: 7,\n\t\t\toutput:     \"[«](?page=2) | page 3 of 3 | \\\\-\",\n\t\t},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t// Arrange\n\t\t\tp := MustNew(tc.uri, tc.totalItems, WithPageSize(pageSize))\n\n\t\t\t// Act\n\t\t\toutput := Picker(p)\n\n\t\t\t// Assert\n\t\t\tuassert.Equal(t, tc.output, output)\n\t\t})\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"4ccGPZd9bydRbqUXozQy4l7YQXIRtCKQAnmVFR6hU70rxEXoiBk7WDsrc1tzE0xIBLKoOT8vL2Md6HcdPn6lmA=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g125em6arxsnj49vx35f0n0z34putv5ty3376fg5","package":{"name":"coinsort","path":"gno.land/p/leon/coinsort","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":"coinsort_test.gno","body":"package coinsort\n\nimport (\n\t\"chain\"\n\t\"testing\"\n)\n\nfunc TestSortByBalance(t *testing.T) {\n\tcoins := chain.Coins{\n\t\tchain.Coin{Denom: \"b\", Amount: 50},\n\t\tchain.Coin{Denom: \"c\", Amount: 10},\n\t\tchain.Coin{Denom: \"a\", Amount: 100},\n\t}\n\n\texpected := chain.Coins{\n\t\tchain.Coin{Denom: \"c\", Amount: 10},\n\t\tchain.Coin{Denom: \"b\", Amount: 50},\n\t\tchain.Coin{Denom: \"a\", Amount: 100},\n\t}\n\n\tSortByBalance(coins)\n\n\tfor i := range coins {\n\t\tif coins[i] != expected[i] {\n\t\t\tt.Errorf(\"SortByBalance failed at index %d: got %+v, want %+v\", i, coins[i], expected[i])\n\t\t}\n\t}\n}\n\nfunc TestSortByCustomDescendingAmount(t *testing.T) {\n\tcoins := chain.Coins{\n\t\tchain.Coin{Denom: \"a\", Amount: 2},\n\t\tchain.Coin{Denom: \"b\", Amount: 3},\n\t\tchain.Coin{Denom: \"c\", Amount: 1},\n\t}\n\n\texpected := chain.Coins{\n\t\tchain.Coin{Denom: \"b\", Amount: 3},\n\t\tchain.Coin{Denom: \"a\", Amount: 2},\n\t\tchain.Coin{Denom: \"c\", Amount: 1},\n\t}\n\n\tSortBy(coins, func(a, b chain.Coin) bool {\n\t\treturn a.Amount \u003e b.Amount // descending\n\t})\n\n\tfor i := range coins {\n\t\tif coins[i] != expected[i] {\n\t\t\tt.Errorf(\"SortBy custom descending failed at index %d: got %+v, want %+v\", i, coins[i], expected[i])\n\t\t}\n\t}\n}\n\nfunc TestSortByNilFunc(t *testing.T) {\n\tcoins := chain.Coins{\n\t\tchain.Coin{Denom: \"x\", Amount: 5},\n\t\tchain.Coin{Denom: \"z\", Amount: 20},\n\t\tchain.Coin{Denom: \"y\", Amount: 10},\n\t}\n\n\texpected := chain.Coins{\n\t\tchain.Coin{Denom: \"x\", Amount: 5},\n\t\tchain.Coin{Denom: \"z\", Amount: 20},\n\t\tchain.Coin{Denom: \"y\", Amount: 10},\n\t}\n\n\tSortBy(coins, nil)\n\n\t// should stay the same\n\tfor i := range coins {\n\t\tif coins[i] != expected[i] {\n\t\t\tt.Errorf(\"SortBy nil func failed at index %d: got %+v, want %+v\", i, coins[i], expected[i])\n\t\t}\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/leon/coinsort\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g125em6arxsnj49vx35f0n0z34putv5ty3376fg5\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"+T/VkjNjetgWfz7M3LyFNT8XOZaysy2KEpxe2lcfeW06Ttf8GUzDJm343kwcMY3EMu+7LJ44uWC9I5PD2jNoiQ=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g125em6arxsnj49vx35f0n0z34putv5ty3376fg5","package":{"name":"ctg","path":"gno.land/p/leon/ctg","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":"converter_test.gno","body":"package ctg\n\nimport (\n\t\"testing\"\n)\n\nfunc TestConvertKnownAddress(t *testing.T) {\n\tconst (\n\t\tcosmosAddr = \"cosmos1jg8mtutu9khhfwc4nxmuhcpftf0pajdh6svrgs\"\n\t\tgnoAddr    = \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"\n\t)\n\tgot, err := ConvertCosmosToGno(cosmosAddr)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif got != gnoAddr {\n\t\tt.Fatalf(\"got %s, want %s\", got, gnoAddr)\n\t}\n}\n\nfunc TestConvertCosmosToGno(t *testing.T) {\n\tdecoded := []byte{\n\t\t0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,\n\t\t0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,\n\t\t0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,\n\t\t0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00,\n\t}\n\n\tcosmosAddr := mustEncode(\"cosmos\", decoded)\n\twantGno := mustEncode(\"g\", decoded)\n\n\tgot, err := ConvertCosmosToGno(cosmosAddr)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif string(got) != wantGno {\n\t\tt.Fatalf(\"got %s, want %s\", got, wantGno)\n\t}\n\n\t// invalid bech32\n\tif _, err := ConvertCosmosToGno(\"not-bech32\"); err == nil {\n\t\tt.Fatalf(\"expected error for invalid bech32\")\n\t}\n\n\t// wrong prefix\n\tgAddr := mustEncode(\"g\", decoded)\n\tif _, err := ConvertCosmosToGno(gAddr); err == nil {\n\t\tt.Fatalf(\"expected error for non-cosmos prefix\")\n\t}\n}\n\nfunc TestConvertAnyToGno(t *testing.T) {\n\tpayload := []byte{\n\t\t0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,\n\t\t0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,\n\t\t0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,\n\t\t0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00,\n\t}\n\n\ttests := []struct {\n\t\tname    string\n\t\tinput   string\n\t\twant    string\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname:  \"cosmos→g\",\n\t\t\tinput: mustEncode(\"cosmos\", payload),\n\t\t\twant:  mustEncode(\"g\", payload),\n\t\t},\n\t\t{\n\t\t\tname:  \"osmo→g\",\n\t\t\tinput: mustEncode(\"osmo\", payload),\n\t\t\twant:  mustEncode(\"g\", payload),\n\t\t},\n\t\t{\n\t\t\tname:    \"invalid bech32\",\n\t\t\tinput:   \"xyz123\",\n\t\t\twantErr: true,\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tgot, err := ConvertAnyToGno(tc.input)\n\t\t\tif tc.wantErr {\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Fatalf(\"expected error, got nil\")\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t\t\t}\n\t\t\tif string(got) != tc.want {\n\t\t\t\tt.Fatalf(\"got %s, want %s\", got, tc.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestConvertGnoToAny(t *testing.T) {\n\tpayload := []byte{\n\t\t0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,\n\t\t0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,\n\t\t0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,\n\t\t0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00,\n\t}\n\n\tgno := address(mustEncode(\"g\", payload))\n\n\tt.Run(\"g→cosmos\", func(t *testing.T) {\n\t\tgot, err := ConvertGnoToAny(\"cosmos\", gno)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t\t}\n\t\tif got != mustEncode(\"cosmos\", payload) {\n\t\t\tt.Fatalf(\"conversion incorrect: %s\", got)\n\t\t}\n\t})\n\n\tt.Run(\"g→foobar\", func(t *testing.T) {\n\t\tgot, err := ConvertGnoToAny(\"foobar\", gno)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t\t}\n\t\tif got != mustEncode(\"foobar\", payload) {\n\t\t\tt.Fatalf(\"conversion incorrect: %s\", got)\n\t\t}\n\t})\n\n\tt.Run(\"g→osmo\", func(t *testing.T) {\n\t\tgot, err := ConvertGnoToAny(\"osmo\", gno)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t\t}\n\t\tif got != mustEncode(\"osmo\", payload) {\n\t\t\tt.Fatalf(\"conversion incorrect: %s\", got)\n\t\t}\n\t})\n\n\tt.Run(\"wrong source prefix\", func(t *testing.T) {\n\t\tcosmos := mustEncode(\"cosmos\", payload)\n\t\tif _, err := ConvertGnoToAny(\"g\", address(cosmos)); err == nil {\n\t\t\tt.Fatalf(\"expected error for non-g source prefix\")\n\t\t}\n\t})\n\n\tt.Run(\"invalid bech32\", func(t *testing.T) {\n\t\tif _, err := ConvertGnoToAny(\"cosmos\", address(\"nope\")); err == nil {\n\t\t\tt.Fatalf(\"expected error for invalid bech32\")\n\t\t}\n\t})\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/leon/ctg\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g125em6arxsnj49vx35f0n0z34putv5ty3376fg5\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"fHnyn6eewmalBj9jbFDzUFAdr9d3VdvKIEKTeQIvTR56XC1atcuBkfwDxiCCQl3Z4MhR3zCpSpplt3QD+u9WZg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g125em6arxsnj49vx35f0n0z34putv5ty3376fg5","package":{"name":"svgbtn","path":"gno.land/p/leon/svgbtn","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/leon/svgbtn\"\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/demo/svg\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"34hYyGTM8r118MBl2YtPtjlfGSs9mtlqYGNJzIF5VuI6nCw0U2odCmCcij6pNqQ6c5VMmZDx81V40faTSdEakw=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"md","path":"gno.land/p/mason/md","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/mason/md\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"CKbGmavcd92BodpeWF1DPzfchkOFsCMntZRxL14m3Vw8K8QPD9I3lIbXdcYc08L8AGP5NZKQg9sAkAGI+h2P0w=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1manfred47kzduec920z88wfr64ylksmdcedlf5","package":{"name":"once","path":"gno.land/p/moul/once","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/once\"\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"},{"name":"once_test.gno","body":"package once\n\nimport (\n\t\"errors\"\n\t\"testing\"\n)\n\nfunc TestOnce_Do(t *testing.T) {\n\tcounter := 0\n\tonce := New()\n\n\tincrement := func() {\n\t\tcounter++\n\t}\n\n\t// First call should execute\n\tonce.Do(increment)\n\tif counter != 1 {\n\t\tt.Errorf(\"expected counter to be 1, got %d\", counter)\n\t}\n\n\t// Second call should not execute\n\tonce.Do(increment)\n\tif counter != 1 {\n\t\tt.Errorf(\"expected counter to still be 1, got %d\", counter)\n\t}\n}\n\nfunc TestOnce_DoErr(t *testing.T) {\n\tonce := New()\n\texpectedErr := errors.New(\"test error\")\n\n\tfn := func() error {\n\t\treturn expectedErr\n\t}\n\n\t// First call should return error\n\tif err := once.DoErr(fn); err != expectedErr {\n\t\tt.Errorf(\"expected error %v, got %v\", expectedErr, err)\n\t}\n\n\t// Second call should return same error\n\tif err := once.DoErr(fn); err != expectedErr {\n\t\tt.Errorf(\"expected error %v, got %v\", expectedErr, err)\n\t}\n}\n\nfunc TestOnce_DoOrPanic(t *testing.T) {\n\tonce := New()\n\texecuted := false\n\n\tfn := func() {\n\t\texecuted = true\n\t}\n\n\t// First call should execute\n\tonce.DoOrPanic(fn)\n\tif !executed {\n\t\tt.Error(\"function should have executed\")\n\t}\n\n\t// Second call should panic\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Error(\"expected panic on second execution\")\n\t\t}\n\t}()\n\tonce.DoOrPanic(fn)\n}\n\nfunc TestOnce_DoValue(t *testing.T) {\n\tonce := New()\n\texpected := \"test value\"\n\tcounter := 0\n\n\tfn := func() any {\n\t\tcounter++\n\t\treturn expected\n\t}\n\n\t// First call should return value\n\tif result := once.DoValue(fn); result != expected {\n\t\tt.Errorf(\"expected %v, got %v\", expected, result)\n\t}\n\n\t// Second call should return cached value\n\tif result := once.DoValue(fn); result != expected {\n\t\tt.Errorf(\"expected %v, got %v\", expected, result)\n\t}\n\n\tif counter != 1 {\n\t\tt.Errorf(\"function should have executed only once, got %d executions\", counter)\n\t}\n}\n\nfunc TestOnce_DoValueErr(t *testing.T) {\n\tonce := New()\n\texpectedVal := \"test value\"\n\texpectedErr := errors.New(\"test error\")\n\tcounter := 0\n\n\tfn := func() (any, error) {\n\t\tcounter++\n\t\treturn expectedVal, expectedErr\n\t}\n\n\t// First call should return value and error\n\tval, err := once.DoValueErr(fn)\n\tif val != expectedVal || err != expectedErr {\n\t\tt.Errorf(\"expected (%v, %v), got (%v, %v)\", expectedVal, expectedErr, val, err)\n\t}\n\n\t// Second call should return cached value and error\n\tval, err = once.DoValueErr(fn)\n\tif val != expectedVal || err != expectedErr {\n\t\tt.Errorf(\"expected (%v, %v), got (%v, %v)\", expectedVal, expectedErr, val, err)\n\t}\n\n\tif counter != 1 {\n\t\tt.Errorf(\"function should have executed only once, got %d executions\", counter)\n\t}\n}\n\nfunc TestOnce_Reset(t *testing.T) {\n\tonce := New()\n\tcounter := 0\n\n\tfn := func() {\n\t\tcounter++\n\t}\n\n\tonce.Do(fn)\n\tif counter != 1 {\n\t\tt.Errorf(\"expected counter to be 1, got %d\", counter)\n\t}\n\n\tonce.Reset()\n\tonce.Do(fn)\n\tif counter != 2 {\n\t\tt.Errorf(\"expected counter to be 2 after reset, got %d\", counter)\n\t}\n}\n\nfunc TestOnce_IsDone(t *testing.T) {\n\tonce := New()\n\n\tif once.IsDone() {\n\t\tt.Error(\"new Once instance should not be done\")\n\t}\n\n\tonce.Do(func() {})\n\n\tif !once.IsDone() {\n\t\tt.Error(\"Once instance should be done after execution\")\n\t}\n}\n\nfunc TestOnce_Error(t *testing.T) {\n\tonce := New()\n\texpectedErr := errors.New(\"test error\")\n\n\tif err := once.Error(); err != nil {\n\t\tt.Errorf(\"expected nil error, got %v\", err)\n\t}\n\n\tonce.DoErr(func() error {\n\t\treturn expectedErr\n\t})\n\n\tif err := once.Error(); err != expectedErr {\n\t\tt.Errorf(\"expected error %v, got %v\", expectedErr, err)\n\t}\n}\n\nfunc TestOnce_Value(t *testing.T) {\n\tonce := New()\n\n\t// Test unexecuted state\n\tval, err := once.Value()\n\tif err != ErrNotExecuted {\n\t\tt.Errorf(\"expected ErrNotExecuted, got %v\", err)\n\t}\n\tif val != nil {\n\t\tt.Errorf(\"expected nil value, got %v\", val)\n\t}\n\n\t// Test after execution\n\texpected := \"test value\"\n\tonce.DoValue(func() any {\n\t\treturn expected\n\t})\n\n\tval, err = once.Value()\n\tif err != nil {\n\t\tt.Errorf(\"expected nil error, got %v\", err)\n\t}\n\tif val != expected {\n\t\tt.Errorf(\"expected value %v, got %v\", expected, val)\n\t}\n}\n\nfunc TestOnce_DoValueErr_Panic_MarkedDone(t *testing.T) {\n\tonce := New()\n\tcount := 0\n\tfn := func() (any, error) {\n\t\tcount++\n\t\tpanic(\"panic\")\n\t}\n\tvar r any\n\tfunc() {\n\t\tdefer func() { r = recover() }()\n\t\tonce.DoValueErr(fn)\n\t}()\n\tif r == nil {\n\t\tt.Error(\"expected panic on first call\")\n\t}\n\tif !once.IsDone() {\n\t\tt.Error(\"expected once to be marked as done after panic\")\n\t}\n\tr = nil\n\tfunc() {\n\t\tdefer func() { r = recover() }()\n\t\tonce.DoValueErr(fn)\n\t}()\n\tif r != nil {\n\t\tt.Error(\"expected no panic on subsequent call\")\n\t}\n\tif count != 1 {\n\t\tt.Errorf(\"expected count to be 1, got %d\", count)\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"SKfecflqUL7WA0e/eza8W87lAoR2gVitLTk7irgGYSRw+7w783GXEARhIaPTICVh5uqnm63YAT3zKPOYosgj+A=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1manfred47kzduec920z88wfr64ylksmdcedlf5","package":{"name":"authz","path":"gno.land/p/moul/authz","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: Async authorization (e.g., via DAO)\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: Delegates to another contract\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\"\n\t\"gno.land/p/moul/once\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/avl/v0/rotree\"\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// 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\nfunc (a *Authorizer) String() string {\n\tauthStr := a.auth.String()\n\n\tswitch a.auth.(type) {\n\tcase *MemberAuthority:\n\tcase *ContractAuthority:\n\tcase *AutoAcceptAuthority:\n\tcase *droppedAuthority:\n\tdefault:\n\t\t// this way official \"dropped\" is different from \"*custom*: dropped\" (autoclaimed).\n\t\treturn ufmt.Sprintf(\"custom_authority[%s]\", authStr)\n\t}\n\treturn authStr\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 creates a new contract-based authority.\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 guards \"execute action only from contractAddr\" but the\n// handler can call wrappedAction however it likes (multiple times, never,\n// out of order). Register only trusted handler functions; treat handler\n// registration as the trust boundary.\nfunc NewContractAuthority(path string, handler PrivilegedActionHandler) *ContractAuthority {\n\treturn \u0026ContractAuthority{\n\t\tcontractPath:    path,\n\t\tcontractAddr:    chain.PackageAddress(path),\n\t\tcontractHandler: handler,\n\t\tproposer:        NewAutoAcceptAuthority(), // default: anyone can propose\n\t}\n}\n\n// NewRestrictedContractAuthority creates a new contract authority with a\n// proposer restriction.\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.\nfunc NewRestrictedContractAuthority(path string, handler PrivilegedActionHandler, proposer Authority) Authority {\n\tif path == \"\" {\n\t\tpanic(\"contract path cannot be empty\")\n\t}\n\tif handler == nil {\n\t\tpanic(\"contract handler cannot be nil\")\n\t}\n\tif proposer == nil {\n\t\tpanic(\"proposer cannot be nil\")\n\t}\n\treturn \u0026ContractAuthority{\n\t\tcontractPath:    path,\n\t\tcontractAddr:    chain.PackageAddress(path),\n\t\tcontractHandler: handler,\n\t\tproposer:        proposer,\n\t}\n}\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\t// Use the proposer authority to control who can create proposals\n\treturn a.proposer.Authorize(caller, title+\"_proposal\", 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}, args...)\n}\n\nfunc (a *ContractAuthority) String() string {\n\treturn ufmt.Sprintf(\"contract_authority[contract=%s]\", a.contractPath)\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\"chain/runtime/unsafe\"\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 — must come from the\n\t// contract realm so ContractAuthority's wrappedAction CurrentRealm\n\t// check passes. Use the test frame's cur directly (SetRealm mutates\n\t// it in place); a crossing closure would push a new frame whose cur\n\t// is the test package, breaking the runtime.CurrentRealm match.\n\tautoAuth := NewAutoAcceptAuthority()\n\tcodeRealm := testing.NewCodeRealm(\"gno.land/r/test\")\n\ttesting.SetRealm(codeRealm)\n\terr = auth.Transfer(0, cur, autoAuth)\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// Test Tree() functionality\n\ttree := auth.Tree()\n\tuassert.True(t, tree.Size() == 2, \"tree should have 2 members\")\n\n\t// Verify both members are in the tree\n\tfound := make(map[address]bool)\n\ttree.Iterate(\"\", \"\", func(key string, _ any) bool {\n\t\tfound[address(key)] = true\n\t\treturn false\n\t})\n\tuassert.True(t, found[alice], \"alice should be in the tree\")\n\tuassert.True(t, found[bob], \"bob should be in the tree\")\n\tuassert.False(t, found[carol], \"carol should not be in the tree\")\n\n\t// Test read-only nature of the tree\n\tdefer func() {\n\t\tr := recover()\n\t\tuassert.True(t, r != nil, \"modifying read-only tree should panic\")\n\t}()\n\ttree.Set(string(carol), nil) // This should panic\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\t/*\n\t\t// Test empty path - should panic\n\t\tpanicked := false\n\t\tfunc() {\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tpanicked = true\n\t\t\t\t}\n\t\t\t}()\n\t\t\tNewContractAuthority(\"\", nil)\n\t\t}()\n\t\tuassert.True(t, panicked, \"expected panic for empty path\")\n\t*/\n\n\t// Test nil handler - should return error on Authorize\n\tauth := NewContractAuthority(\"gno.land/r/test\", nil)\n\tcode := testing.NewCodeRealm(\"gno.land/r/test\").Address()\n\terr := auth.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\thandler := func(title string, action PrivilegedAction) error {\n\t\treturn nil\n\t}\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\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]\"\n\tuassert.Equal(t, contractStr, expectedContractStr)\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\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// Handler that checks the caller before proceeding\n\thandlerExecutedCorrectly := false // Tracks if handler logic ran correctly\n\thandlerErrorMsg := \"handler: caller is not the contract\"\n\tcontractHandler := func(title string, action PrivilegedAction) error {\n\t\tcaller := unsafe.CurrentRealm().Address()\n\t\tif caller != contractAddr {\n\t\t\treturn errors.New(handlerErrorMsg)\n\t\t}\n\t\t// Only execute action and mark success if caller is correct\n\t\thandlerExecutedCorrectly = true\n\t\treturn action()\n\t}\n\n\tcontractAuth := NewContractAuthority(contractPath, contractHandler)\n\tauthorizer := NewWithAuthority(contractAuth) // Start with ContractAuthority\n\n\tactionExecuted := false\n\tprivilegedAction := func() error {\n\t\tactionExecuted = true\n\t\treturn nil\n\t}\n\n\t// 1. Attempt action from unauthorized user\n\ttesting.SetRealm(testing.NewUserRealm(unauthorizedAddr))\n\terr := authorizer.DoByCurrent(0, cur, \"test_action_unauthorized\", privilegedAction)\n\n\t// Assertions for unauthorized call\n\tuassert.Error(t, err, \"DoByCurrent should return an error for unauthorized caller\")\n\tuassert.ErrorContains(t, err, handlerErrorMsg, \"Error should originate from the handler check\")\n\tuassert.False(t, handlerExecutedCorrectly, \"Handler should not have executed successfully for unauthorized caller\")\n\tuassert.False(t, actionExecuted, \"Privileged action should not have executed for unauthorized caller\")\n\n\t// 2. Attempt action from the correct contract\n\thandlerExecutedCorrectly = false // Reset flag\n\tactionExecuted = false           // Reset flag\n\ttesting.SetRealm(testing.NewCodeRealm(contractPath))\n\terr = authorizer.DoByCurrent(0, cur, \"test_action_authorized\", privilegedAction)\n\n\t// Assertions for authorized call\n\tuassert.NoError(t, err, \"DoByCurrent should succeed for authorized contract caller\")\n\tuassert.True(t, handlerExecutedCorrectly, \"Handler should have executed successfully for authorized caller\")\n\tuassert.True(t, actionExecuted, \"Privileged action should have executed for authorized 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"},{"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// Use the authority to perform a privileged action\n\tauth.DoByCurrent(0, cur, \"update_config\", func() error {\n\t\t// config = newValue\n\t\treturn nil\n\t})\n}\n\n// Example_addingMembers demonstrates how to add new members to a member authority\nfunc Example_addingMembers(cur realm) {\n\t// Initialize with the calling realm as the initial authority\n\tauth := NewWithMembers(cur.Address())\n\n\t// Add a new member to the authority\n\tmemberAuth := auth.Authority().(*MemberAuthority)\n\tmemberAuth.AddMember(0, cur, address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"))\n}\n\n// Example_contractAuthority demonstrates using a contract-based authority\nfunc Example_contractAuthority(cur realm) {\n\t// Initialize with contract authority (e.g., DAO)\n\tauth := NewWithAuthority(\n\t\tNewContractAuthority(\n\t\t\t\"gno.land/r/demo/dao\",\n\t\t\tmockDAOHandler, // defined elsewhere for example\n\t\t),\n\t)\n\n\t// Privileged actions will be handled by the contract\n\tauth.DoByCurrent(0, cur, \"update_params\", func() error {\n\t\t// Executes after DAO approval\n\t\treturn nil\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\tauth.DoByCurrent(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})\n}\n\n// Example_switchingAuthority demonstrates switching from member to contract authority\nfunc Example_switchingAuthority(cur realm) {\n\t// Start with member authority (the calling realm)\n\tauth := NewWithMembers(cur.Address())\n\n\t// Create and switch to contract authority\n\tdaoAuthority := NewContractAuthority(\n\t\t\"gno.land/r/demo/dao\",\n\t\tmockDAOHandler,\n\t)\n\tauth.Transfer(0, cur, daoAuthority)\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\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"DBk/OzItuot3PJkzF6qmOckMnwV6/QZKG3n0csApEsoYg0L29fzW+aqDTAkcwxENLgelD9Xd/YGeD2tEBJPQEw=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1manfred47kzduec920z88wfr64ylksmdcedlf5","package":{"name":"dynreplacer","path":"gno.land/p/moul/dynreplacer","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":"dynreplacer_test.gno","body":"package dynreplacer\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestNew(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tpairs []Pair\n\t}{\n\t\t{\n\t\t\tname:  \"empty constructor\",\n\t\t\tpairs: []Pair{},\n\t\t},\n\t\t{\n\t\t\tname: \"single pair\",\n\t\t\tpairs: []Pair{\n\t\t\t\t{\":name:\", func() string { return \"World\" }},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"multiple pairs\",\n\t\t\tpairs: []Pair{\n\t\t\t\t{\":greeting:\", func() string { return \"Hello\" }},\n\t\t\t\t{\":name:\", func() string { return \"World\" }},\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\tr := New(tt.pairs...)\n\t\t\tuassert.True(t, r.callbacks != nil, \"callbacks map should be initialized\")\n\t\t\tuassert.True(t, r.cachedValues != nil, \"cachedValues map should be initialized\")\n\n\t\t\t// Verify all callbacks were registered\n\t\t\tfor _, pair := range tt.pairs {\n\t\t\t\t_, exists := r.callbacks[pair.Placeholder]\n\t\t\t\tuassert.True(t, exists, \"callback should be registered for \"+pair.Placeholder)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestReplace(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tlayout   string\n\t\tsetup    func(*Replacer)\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"empty layout\",\n\t\t\tlayout:   \"\",\n\t\t\tsetup:    func(r *Replacer) {},\n\t\t\texpected: \"\",\n\t\t},\n\t\t{\n\t\t\tname:   \"single replacement\",\n\t\t\tlayout: \"Hello :name:!\",\n\t\t\tsetup: func(r *Replacer) {\n\t\t\t\tr.RegisterCallback(\":name:\", func() string { return \"World\" })\n\t\t\t},\n\t\t\texpected: \"Hello World!\",\n\t\t},\n\t\t{\n\t\t\tname:   \"multiple replacements\",\n\t\t\tlayout: \":greeting: :name:!\",\n\t\t\tsetup: func(r *Replacer) {\n\t\t\t\tr.RegisterCallback(\":greeting:\", func() string { return \"Hello\" })\n\t\t\t\tr.RegisterCallback(\":name:\", func() string { return \"World\" })\n\t\t\t},\n\t\t\texpected: \"Hello World!\",\n\t\t},\n\t\t{\n\t\t\tname:   \"no recursive replacement\",\n\t\t\tlayout: \":outer:\",\n\t\t\tsetup: func(r *Replacer) {\n\t\t\t\tr.RegisterCallback(\":outer:\", func() string { return \":inner:\" })\n\t\t\t\tr.RegisterCallback(\":inner:\", func() string { return \"content\" })\n\t\t\t},\n\t\t\texpected: \":inner:\",\n\t\t},\n\t\t{\n\t\t\tname:   \"unused callbacks\",\n\t\t\tlayout: \"Hello :name:!\",\n\t\t\tsetup: func(r *Replacer) {\n\t\t\t\tr.RegisterCallback(\":name:\", func() string { return \"World\" })\n\t\t\t\tr.RegisterCallback(\":unused:\", func() string { return \"Never Called\" })\n\t\t\t},\n\t\t\texpected: \"Hello World!\",\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 := New()\n\t\t\ttt.setup(r)\n\t\t\tresult := r.Replace(tt.layout)\n\t\t\tuassert.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestCaching(t *testing.T) {\n\tr := New()\n\tcallCount := 0\n\tr.RegisterCallback(\":expensive:\", func() string {\n\t\tcallCount++\n\t\treturn \"computed\"\n\t})\n\n\tlayout := \"Value: :expensive:\"\n\n\t// First call should compute\n\tresult1 := r.Replace(layout)\n\tuassert.Equal(t, \"Value: computed\", result1)\n\tuassert.Equal(t, 1, callCount)\n\n\t// Second call should use cache\n\tresult2 := r.Replace(layout)\n\tuassert.Equal(t, \"Value: computed\", result2)\n\tuassert.Equal(t, 1, callCount)\n\n\t// After clearing cache, should recompute\n\tr.ClearCache()\n\tresult3 := r.Replace(layout)\n\tuassert.Equal(t, \"Value: computed\", result3)\n\tuassert.Equal(t, 2, callCount)\n}\n\nfunc TestComplexExample(t *testing.T) {\n\tlayout := `\n\t\t# Welcome to gno.land\n\n\t\t## Blog\n\t\t:latest-blogposts:\n\n\t\t## Events\n\t\t:next-events:\n\n\t\t## Awesome Gno\n\t\t:awesome-gno:\n\t`\n\n\tr := New(\n\t\tPair{\":latest-blogposts:\", func() string { return \"Latest blog posts content here\" }},\n\t\tPair{\":next-events:\", func() string { return \"Upcoming events listed here\" }},\n\t\tPair{\":awesome-gno:\", func() string { return \":latest-blogposts: (This should NOT be replaced again)\" }},\n\t)\n\n\tresult := r.Replace(layout)\n\n\t// Check that original placeholders are replaced\n\tuassert.True(t, !strings.Contains(result, \":latest-blogposts:\\n\"), \"':latest-blogposts:' placeholder should be replaced\")\n\tuassert.True(t, !strings.Contains(result, \":next-events:\\n\"), \"':next-events:' placeholder should be replaced\")\n\tuassert.True(t, !strings.Contains(result, \":awesome-gno:\\n\"), \"':awesome-gno:' placeholder should be replaced\")\n\n\t// Check that the replacement content is present\n\tuassert.True(t, strings.Contains(result, \"Latest blog posts content here\"), \"Blog posts content should be present\")\n\tuassert.True(t, strings.Contains(result, \"Upcoming events listed here\"), \"Events content should be present\")\n\tuassert.True(t, strings.Contains(result, \":latest-blogposts: (This should NOT be replaced again)\"),\n\t\t\"Nested placeholder should not be replaced\")\n}\n\nfunc TestEdgeCases(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tlayout   string\n\t\tsetup    func(*Replacer)\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:   \"empty string placeholder\",\n\t\t\tlayout: \"Hello :\",\n\t\t\tsetup: func(r *Replacer) {\n\t\t\t\tr.RegisterCallback(\"\", func() string { return \"World\" })\n\t\t\t},\n\t\t\texpected: \"WorldHWorldeWorldlWorldlWorldoWorld World:World\",\n\t\t},\n\t\t{\n\t\t\tname:   \"overlapping placeholders\",\n\t\t\tlayout: \"Hello :name::greeting:\",\n\t\t\tsetup: func(r *Replacer) {\n\t\t\t\tr.RegisterCallback(\":name:\", func() string { return \"World\" })\n\t\t\t\tr.RegisterCallback(\":greeting:\", func() string { return \"Hi\" })\n\t\t\t\tr.RegisterCallback(\":name::greeting:\", func() string { return \"Should not match\" })\n\t\t\t},\n\t\t\texpected: \"Hello WorldHi\",\n\t\t},\n\t\t{\n\t\t\tname:   \"replacement order\",\n\t\t\tlayout: \":a::b::c:\",\n\t\t\tsetup: func(r *Replacer) {\n\t\t\t\tr.RegisterCallback(\":c:\", func() string { return \"3\" })\n\t\t\t\tr.RegisterCallback(\":b:\", func() string { return \"2\" })\n\t\t\t\tr.RegisterCallback(\":a:\", func() string { return \"1\" })\n\t\t\t},\n\t\t\texpected: \"123\",\n\t\t},\n\t\t{\n\t\t\tname:   \"special characters in placeholders\",\n\t\t\tlayout: \"Hello :$name#123:!\",\n\t\t\tsetup: func(r *Replacer) {\n\t\t\t\tr.RegisterCallback(\":$name#123:\", func() string { return \"World\" })\n\t\t\t},\n\t\t\texpected: \"Hello World!\",\n\t\t},\n\t\t{\n\t\t\tname:   \"multiple occurrences of same placeholder\",\n\t\t\tlayout: \":name: and :name: again\",\n\t\t\tsetup: func(r *Replacer) {\n\t\t\t\tcallCount := 0\n\t\t\t\tr.RegisterCallback(\":name:\", func() string {\n\t\t\t\t\tcallCount++\n\t\t\t\t\treturn \"World\"\n\t\t\t\t})\n\t\t\t},\n\t\t\texpected: \"World and World again\",\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 := New()\n\t\t\ttt.setup(r)\n\t\t\tresult := r.Replace(tt.layout)\n\t\t\tuassert.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/dynreplacer\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"i9paAYE3mc/+kNJmH/Ng0ekJ3nD7cKew93C6zHYK9IpFjaFmhXiR2ri4a2NW3u8w2/uNZJOBF0afrd+ia+iWwg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1manfred47kzduec920z88wfr64ylksmdcedlf5","package":{"name":"fifo","path":"gno.land/p/moul/fifo","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":"fifo_test.gno","body":"package fifo\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nfunc TestNew(t *testing.T) {\n\tl := New(5)\n\tuassert.Equal(t, 5, l.MaxSize())\n\tuassert.Equal(t, 0, l.Size())\n}\n\nfunc TestAppend(t *testing.T) {\n\tl := New(3)\n\n\t// Test adding within capacity\n\tl.Append(1)\n\tl.Append(2)\n\tuassert.Equal(t, 2, l.Size())\n\tuassert.Equal(t, 1, l.Get(0))\n\tuassert.Equal(t, 2, l.Get(1))\n\n\t// Test overflow behavior\n\tl.Append(3)\n\tl.Append(4)\n\tuassert.Equal(t, 3, l.Size())\n\tuassert.Equal(t, 2, l.Get(0))\n\tuassert.Equal(t, 3, l.Get(1))\n\tuassert.Equal(t, 4, l.Get(2))\n}\n\nfunc TestPrepend(t *testing.T) {\n\tl := New(3)\n\n\t// Test adding within capacity\n\tl.Prepend(1)\n\tl.Prepend(2)\n\tuassert.Equal(t, 2, l.Size())\n\tuassert.Equal(t, 2, l.Get(0))\n\tuassert.Equal(t, 1, l.Get(1))\n\n\t// Test overflow behavior\n\tl.Prepend(3)\n\tl.Prepend(4)\n\tuassert.Equal(t, 3, l.Size())\n\tuassert.Equal(t, 4, l.Get(0))\n\tuassert.Equal(t, 3, l.Get(1))\n\tuassert.Equal(t, 2, l.Get(2))\n}\n\nfunc TestGet(t *testing.T) {\n\tl := New(3)\n\tl.Append(1)\n\tl.Append(2)\n\tl.Append(3)\n\n\t// Test valid indices\n\tuassert.Equal(t, 1, l.Get(0))\n\tuassert.Equal(t, 2, l.Get(1))\n\tuassert.Equal(t, 3, l.Get(2))\n\n\t// Test invalid indices\n\tuassert.True(t, l.Get(-1) == nil)\n\tuassert.True(t, l.Get(3) == nil)\n}\n\nfunc TestEntries(t *testing.T) {\n\tl := New(3)\n\tl.Append(1)\n\tl.Append(2)\n\tl.Append(3)\n\n\tentries := l.Entries()\n\tuassert.Equal(t, 3, len(entries))\n\tuassert.Equal(t, 1, entries[0])\n\tuassert.Equal(t, 2, entries[1])\n\tuassert.Equal(t, 3, entries[2])\n}\n\nfunc TestLatest(t *testing.T) {\n\tl := New(5)\n\n\t// Test empty list\n\tuassert.True(t, l.Latest() == nil)\n\n\t// Test single entry\n\tl.Append(1)\n\tuassert.Equal(t, 1, l.Latest())\n\n\t// Test multiple entries\n\tl.Append(2)\n\tl.Append(3)\n\tuassert.Equal(t, 3, l.Latest())\n\n\t// Test after overflow\n\tl.Append(4)\n\tl.Append(5)\n\tl.Append(6)\n\tuassert.Equal(t, 6, l.Latest())\n}\n\nfunc TestIterator(t *testing.T) {\n\tl := New(3)\n\tl.Append(1)\n\tl.Append(2)\n\tl.Append(3)\n\n\titer := l.Iterator()\n\tuassert.Equal(t, 1, iter())\n\tuassert.Equal(t, 2, iter())\n\tuassert.Equal(t, 3, iter())\n\tuassert.True(t, iter() == nil)\n}\n\nfunc TestMixedOperations(t *testing.T) {\n\tl := New(3)\n\n\t// Mix of append and prepend operations\n\tl.Append(1)  // [1]\n\tl.Prepend(2) // [2,1]\n\tl.Append(3)  // [2,1,3]\n\tl.Prepend(4) // [4,2,1]\n\n\tentries := l.Entries()\n\tuassert.Equal(t, 3, len(entries))\n\tuassert.Equal(t, 4, entries[0])\n\tuassert.Equal(t, 2, entries[1])\n\tuassert.Equal(t, 1, entries[2])\n}\n\nfunc TestEmptyList(t *testing.T) {\n\tl := New(3)\n\n\t// Test operations on empty list\n\tuassert.Equal(t, 0, l.Size())\n\tuassert.True(t, l.Get(0) == nil)\n\tuassert.Equal(t, 0, len(l.Entries()))\n\tuassert.True(t, l.Latest() == nil)\n\n\titer := l.Iterator()\n\tuassert.True(t, iter() == nil)\n}\n\nfunc TestEdgeCases(t *testing.T) {\n\t// Test zero-size list\n\tl := New(0)\n\tuassert.Equal(t, 0, l.MaxSize())\n\tl.Append(1) // Should be no-op\n\tuassert.Equal(t, 0, l.Size())\n\n\t// Test single-element list\n\tl = New(1)\n\tl.Append(1)\n\tl.Append(2) // Should replace 1\n\tuassert.Equal(t, 1, l.Size())\n\tuassert.Equal(t, 2, l.Latest())\n\n\t// Test rapid append/prepend alternation\n\tl = New(3)\n\tl.Append(1)  // [1]\n\tl.Prepend(2) // [2,1]\n\tl.Append(3)  // [2,1,3]\n\tl.Prepend(4) // [4,2,1]\n\tl.Append(5)  // [2,1,5]\n\tuassert.Equal(t, 3, l.Size())\n\tentries := l.Entries()\n\tuassert.Equal(t, 2, entries[0])\n\tuassert.Equal(t, 1, entries[1])\n\tuassert.Equal(t, 5, entries[2])\n\n\t// Test nil values\n\tl = New(2)\n\tl.Append(nil)\n\tl.Prepend(nil)\n\tuassert.Equal(t, 2, l.Size())\n\tuassert.True(t, l.Get(0) == nil)\n\tuassert.True(t, l.Get(1) == nil)\n\n\t// Test index bounds\n\tl = New(3)\n\tl.Append(1)\n\tuassert.True(t, l.Get(-1) == nil)\n\tuassert.True(t, l.Get(1) == nil)\n\n\t// Test iterator exhaustion\n\tl = New(2)\n\tl.Append(1)\n\tl.Append(2)\n\titer := l.Iterator()\n\tuassert.Equal(t, 1, iter())\n\tuassert.Equal(t, 2, iter())\n\tuassert.True(t, iter() == nil)\n\tuassert.True(t, iter() == nil)\n\n\t// Test prepend on full list\n\tl = New(2)\n\tl.Append(1)\n\tl.Append(2)  // [1,2]\n\tl.Prepend(3) // [3,1]\n\tuassert.Equal(t, 2, l.Size())\n\tentries = l.Entries()\n\tuassert.Equal(t, 3, entries[0])\n\tuassert.Equal(t, 1, entries[1])\n}\n\nfunc TestSetMaxSize(t *testing.T) {\n\tl := New(5)\n\n\t// Fill the list\n\tl.Append(1)\n\tl.Append(2)\n\tl.Append(3)\n\tl.Append(4)\n\tl.Append(5)\n\n\t// Test increasing maxSize\n\tl.SetMaxSize(7)\n\tuassert.Equal(t, 7, l.MaxSize())\n\tuassert.Equal(t, 5, l.Size())\n\n\t// Test reducing maxSize\n\tl.SetMaxSize(3)\n\tuassert.Equal(t, 3, l.Size())\n\tentries := l.Entries()\n\tuassert.Equal(t, 3, entries[0])\n\tuassert.Equal(t, 4, entries[1])\n\tuassert.Equal(t, 5, entries[2])\n\n\t// Test setting to zero\n\tl.SetMaxSize(0)\n\tuassert.Equal(t, 0, l.Size())\n\tuassert.True(t, l.head == nil)\n\tuassert.True(t, l.tail == nil)\n\n\t// Test negative maxSize\n\tl.SetMaxSize(-1)\n\tuassert.Equal(t, 0, l.MaxSize())\n\n\t// Test setting back to positive\n\tl.SetMaxSize(2)\n\tl.Append(1)\n\tl.Append(2)\n\tl.Append(3)\n\tuassert.Equal(t, 2, l.Size())\n\tentries = l.Entries()\n\tuassert.Equal(t, 2, entries[0])\n\tuassert.Equal(t, 3, entries[1])\n}\n\nfunc TestDelete(t *testing.T) {\n\tl := New(5)\n\n\t// Test delete on empty list\n\tuassert.False(t, l.Delete(0))\n\tuassert.False(t, l.Delete(-1))\n\n\t// Fill list\n\tl.Append(1)\n\tl.Append(2)\n\tl.Append(3)\n\tl.Append(4)\n\n\t// Test invalid indices\n\tuassert.False(t, l.Delete(-1))\n\tuassert.False(t, l.Delete(4))\n\n\t// Test deleting from middle\n\tuassert.True(t, l.Delete(1))\n\tuassert.Equal(t, 3, l.Size())\n\tentries := l.Entries()\n\tuassert.Equal(t, 1, entries[0])\n\tuassert.Equal(t, 3, entries[1])\n\tuassert.Equal(t, 4, entries[2])\n\n\t// Test deleting from head\n\tuassert.True(t, l.Delete(0))\n\tuassert.Equal(t, 2, l.Size())\n\tentries = l.Entries()\n\tuassert.Equal(t, 3, entries[0])\n\tuassert.Equal(t, 4, entries[1])\n\n\t// Test deleting from tail\n\tuassert.True(t, l.Delete(1))\n\tuassert.Equal(t, 1, l.Size())\n\tuassert.Equal(t, 3, l.Latest())\n\n\t// Test deleting last element\n\tuassert.True(t, l.Delete(0))\n\tuassert.Equal(t, 0, l.Size())\n\tuassert.True(t, l.head == nil)\n\tuassert.True(t, l.tail == nil)\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/fifo\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"4xoH+DVCP00NUi/8ahCKGMsLpQ+iVoAxECUdAScvZp8/5Ja6Uc9W32NOFuhwpUl2XuLtyUsIACB7eTx1BuJIzw=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1manfred47kzduec920z88wfr64ylksmdcedlf5","package":{"name":"txlink","path":"gno.land/p/moul/txlink","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/txlink\"\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"},{"name":"txlink_test.gno","body":"package txlink\n\nimport (\n\t\"chain/runtime\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc TestCall(t *testing.T) {\n\tcd := runtime.ChainDomain()\n\n\ttests := []struct {\n\t\tfn        string\n\t\targs      []string\n\t\twant      string\n\t\trealm_XXX Realm\n\t}{\n\t\t{\"foo\", []string{\"bar\", \"1\", \"baz\", \"2\"}, \"/p/moul/txlink$help\u0026func=foo\u0026bar=1\u0026baz=2\", \"\"},\n\t\t{\"testFunc\", []string{\"key\", \"value\"}, \"/p/moul/txlink$help\u0026func=testFunc\u0026key=value\", \"\"},\n\t\t{\"noArgsFunc\", []string{}, \"/p/moul/txlink$help\u0026func=noArgsFunc\", \"\"},\n\t\t{\"oddArgsFunc\", []string{\"key\"}, \"/p/moul/txlink$help\u0026func=oddArgsFunc\u0026error=odd+number+of+arguments\", \"\"},\n\t\t{\"foo\", []string{\"bar\", \"1\", \"baz\", \"2\"}, \"/r/lorem/ipsum$help\u0026func=foo\u0026bar=1\u0026baz=2\", Realm(cd + \"/r/lorem/ipsum\")},\n\t\t{\"testFunc\", []string{\"key\", \"value\"}, \"/r/lorem/ipsum$help\u0026func=testFunc\u0026key=value\", Realm(cd + \"/r/lorem/ipsum\")},\n\t\t{\"noArgsFunc\", []string{}, \"/r/lorem/ipsum$help\u0026func=noArgsFunc\", Realm(cd + \"/r/lorem/ipsum\")},\n\t\t{\"oddArgsFunc\", []string{\"key\"}, \"/r/lorem/ipsum$help\u0026func=oddArgsFunc\u0026error=odd+number+of+arguments\", Realm(cd + \"/r/lorem/ipsum\")},\n\t\t{\"foo\", []string{\"bar\", \"1\", \"baz\", \"2\"}, \"https://gno.world/r/lorem/ipsum$help\u0026func=foo\u0026bar=1\u0026baz=2\", \"gno.world/r/lorem/ipsum\"},\n\t\t{\"testFunc\", []string{\"key\", \"value\"}, \"https://gno.world/r/lorem/ipsum$help\u0026func=testFunc\u0026key=value\", \"gno.world/r/lorem/ipsum\"},\n\t\t{\"noArgsFunc\", []string{}, \"https://gno.world/r/lorem/ipsum$help\u0026func=noArgsFunc\", \"gno.world/r/lorem/ipsum\"},\n\t\t{\"oddArgsFunc\", []string{\"key\"}, \"https://gno.world/r/lorem/ipsum$help\u0026func=oddArgsFunc\u0026error=odd+number+of+arguments\", \"gno.world/r/lorem/ipsum\"},\n\t\t{\"test\", []string{\"key\", \"hello world\"}, \"/p/moul/txlink$help\u0026func=test\u0026key=hello+world\", \"\"},\n\t\t{\"test\", []string{\"key\", \"a\u0026b=c\"}, \"/p/moul/txlink$help\u0026func=test\u0026key=a%26b%3Dc\", \"\"},\n\t\t{\"test\", []string{\"key\", \"\"}, \"/p/moul/txlink$help\u0026func=test\u0026key=\", \"\"},\n\t\t{\"testSend\", []string{\"key\", \"hello world\", \".send\", \"1000000ugnot\"}, \"/p/moul/txlink$help\u0026func=testSend\u0026.send=1000000ugnot\u0026key=hello+world\", \"\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\ttitle := string(tt.realm_XXX) + \"_\" + tt.fn\n\t\tt.Run(title, func(t *testing.T) {\n\t\t\tif tt.fn == \"oddArgsFunc\" {\n\t\t\t\tdefer func() {\n\t\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\t\tif r != \"odd number of arguments\" {\n\t\t\t\t\t\t\tt.Errorf(\"expected panic with message 'odd number of arguments', got: %v\", r)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tt.Error(\"expected panic for odd number of arguments, but did not panic\")\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t}\n\t\t\tgot := tt.realm_XXX.Call(tt.fn, tt.args...)\n\t\t\turequire.Equal(t, tt.want, got)\n\t\t})\n\t}\n}\n\nfunc TestBuilder(t *testing.T) {\n\tcases := []struct {\n\t\tname     string\n\t\tbuild    func() string\n\t\texpected string\n\t}{\n\t\t// Basic functionality tests\n\t\t{\n\t\t\tname: \"empty_function\",\n\t\t\tbuild: func() string {\n\t\t\t\treturn NewLink(\"\").URL()\n\t\t\t},\n\t\t\texpected: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"function_without_args\",\n\t\t\tbuild: func() string {\n\t\t\t\treturn NewLink(\"MyFunc\").URL()\n\t\t\t},\n\t\t\texpected: \"/p/moul/txlink$help\u0026func=MyFunc\",\n\t\t},\n\n\t\t// Realm tests\n\t\t{\n\t\t\tname: \"gnoland_realm\",\n\t\t\tbuild: func() string {\n\t\t\t\treturn Realm(\"gno.land/r/demo\").\n\t\t\t\t\tNewLink(\"MyFunc\").\n\t\t\t\t\tAddArgs(\"key\", \"value\").\n\t\t\t\t\tURL()\n\t\t\t},\n\t\t\texpected: \"/r/demo$help\u0026func=MyFunc\u0026key=value\",\n\t\t},\n\t\t{\n\t\t\tname: \"external_realm\",\n\t\t\tbuild: func() string {\n\t\t\t\treturn Realm(\"gno.world/r/demo\").\n\t\t\t\t\tNewLink(\"MyFunc\").\n\t\t\t\t\tAddArgs(\"key\", \"value\").\n\t\t\t\t\tURL()\n\t\t\t},\n\t\t\texpected: \"https://gno.world/r/demo$help\u0026func=MyFunc\u0026key=value\",\n\t\t},\n\t\t{\n\t\t\tname: \"empty_realm\",\n\t\t\tbuild: func() string {\n\t\t\t\treturn Realm(\"\").\n\t\t\t\t\tNewLink(\"func\").\n\t\t\t\t\tAddArgs(\"key\", \"value\").\n\t\t\t\t\tURL()\n\t\t\t},\n\t\t\texpected: \"/p/moul/txlink$help\u0026func=func\u0026key=value\",\n\t\t},\n\n\t\t// URL encoding tests\n\t\t{\n\t\t\tname: \"url_encoding_with_spaces\",\n\t\t\tbuild: func() string {\n\t\t\t\treturn NewLink(\"test\").\n\t\t\t\t\tAddArgs(\"key\", \"hello world\").\n\t\t\t\t\tURL()\n\t\t\t},\n\t\t\texpected: \"/p/moul/txlink$help\u0026func=test\u0026key=hello+world\",\n\t\t},\n\t\t{\n\t\t\tname: \"url_encoding_with_special_chars\",\n\t\t\tbuild: func() string {\n\t\t\t\treturn NewLink(\"test\").\n\t\t\t\t\tAddArgs(\"key\", \"a\u0026b=c\").\n\t\t\t\t\tURL()\n\t\t\t},\n\t\t\texpected: \"/p/moul/txlink$help\u0026func=test\u0026key=a%26b%3Dc\",\n\t\t},\n\t\t{\n\t\t\tname: \"url_encoding_with_unicode\",\n\t\t\tbuild: func() string {\n\t\t\t\treturn NewLink(\"func\").\n\t\t\t\t\tAddArgs(\"key\", \"🌟\").\n\t\t\t\t\tURL()\n\t\t\t},\n\t\t\texpected: \"/p/moul/txlink$help\u0026func=func\u0026key=%F0%9F%8C%9F\",\n\t\t},\n\t\t{\n\t\t\tname: \"url_encoding_with_special_chars_in_key\",\n\t\t\tbuild: func() string {\n\t\t\t\treturn NewLink(\"func\").\n\t\t\t\t\tAddArgs(\"my/key\", \"value\").\n\t\t\t\t\tURL()\n\t\t\t},\n\t\t\texpected: \"/p/moul/txlink$help\u0026func=func\u0026my%2Fkey=value\",\n\t\t},\n\n\t\t// AddArgs tests\n\t\t{\n\t\t\tname: \"addargs_with_multiple_pairs\",\n\t\t\tbuild: func() string {\n\t\t\t\treturn NewLink(\"MyFunc\").\n\t\t\t\t\tAddArgs(\"key1\", \"value1\", \"key2\", \"value2\").\n\t\t\t\t\tURL()\n\t\t\t},\n\t\t\texpected: \"/p/moul/txlink$help\u0026func=MyFunc\u0026key1=value1\u0026key2=value2\",\n\t\t},\n\t\t{\n\t\t\tname: \"addargs_with_odd_number_of_args\",\n\t\t\tbuild: func() string {\n\t\t\t\tdefer func() {\n\t\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\t\tif r != \"odd number of arguments\" {\n\t\t\t\t\t\t\tt.Errorf(\"expected panic with message 'odd number of arguments', got: %v\", r)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tt.Error(\"expected panic for odd number of arguments, but did not panic\")\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t\treturn NewLink(\"MyFunc\").\n\t\t\t\t\tAddArgs(\"key1\", \"value1\", \"orphan\").\n\t\t\t\t\tURL()\n\t\t\t},\n\t\t\texpected: \"\",\n\t\t},\n\n\t\t// Empty values tests\n\t\t{\n\t\t\tname: \"empty_key_should_be_ignored\",\n\t\t\tbuild: func() string {\n\t\t\t\treturn NewLink(\"func\").\n\t\t\t\t\tAddArgs(\"\", \"value\").\n\t\t\t\t\tURL()\n\t\t\t},\n\t\t\texpected: \"/p/moul/txlink$help\u0026func=func\",\n\t\t},\n\t\t{\n\t\t\tname: \"empty_value_should_be_kept\",\n\t\t\tbuild: func() string {\n\t\t\t\treturn NewLink(\"func\").\n\t\t\t\t\tAddArgs(\"key\", \"\").\n\t\t\t\t\tURL()\n\t\t\t},\n\t\t\texpected: \"/p/moul/txlink$help\u0026func=func\u0026key=\",\n\t\t},\n\n\t\t// Send tests\n\t\t{\n\t\t\tname: \"send_via_addsend_method\",\n\t\t\tbuild: func() string {\n\t\t\t\treturn NewLink(\"MyFunc\").\n\t\t\t\t\tAddArgs(\"key\", \"value\").\n\t\t\t\t\tSetSend(\"1000000ugnot\").\n\t\t\t\t\tURL()\n\t\t\t},\n\t\t\texpected: \"/p/moul/txlink$help\u0026func=MyFunc\u0026.send=1000000ugnot\u0026key=value\",\n\t\t},\n\t\t{\n\t\t\tname: \"send_via_addarg_method_panic\",\n\t\t\tbuild: func() string {\n\t\t\t\tdefer func() {\n\t\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\t\tif r != \"invalid key\" {\n\t\t\t\t\t\t\tt.Errorf(\"expected panic with message 'invalid key', got: %v\", r)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tt.Errorf(\"expected panic for .send key, but did not panic\")\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t\tNewLink(\"MyFunc\").AddArgs(\".send\", \"1000000ugnot\")\n\t\t\t\treturn \"no panic occurred\"\n\t\t\t},\n\t\t\texpected: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"addsend_should_override_previous_addsend\",\n\t\t\tbuild: func() string {\n\t\t\t\treturn NewLink(\"MyFunc\").\n\t\t\t\t\tSetSend(\"1000000ugnot\").\n\t\t\t\t\tSetSend(\"2000000ugnot\").\n\t\t\t\t\tURL()\n\t\t\t},\n\t\t\texpected: \"/p/moul/txlink$help\u0026func=MyFunc\u0026.send=2000000ugnot\",\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tgot := tc.build()\n\t\t\turequire.Equal(t, tc.expected, got)\n\t\t})\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"hHr4BGNouKWySfaV5WwXw1SkwH5Nd6u8TpkZEWMCutsmpLoymogwxKwhpuUvkXj1v+Lwe7N7hXCUDs2FbEJA7A=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1manfred47kzduec920z88wfr64ylksmdcedlf5","package":{"name":"helplink","path":"gno.land/p/moul/helplink","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/helplink\"\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\"\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"},{"name":"helplink_test.gno","body":"package helplink\n\nimport (\n\t\"chain/runtime\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc TestFunc(t *testing.T) {\n\tcd := runtime.ChainDomain()\n\ttests := []struct {\n\t\ttitle     string\n\t\tfn        string\n\t\targs      []string\n\t\twant      string\n\t\trealm_XXX Realm\n\t}{\n\t\t{\"Example\", \"foo\", []string{\"bar\", \"1\", \"baz\", \"2\"}, \"[Example](/p/moul/helplink$help\u0026func=foo\u0026bar=1\u0026baz=2)\", \"\"},\n\t\t{\"Realm Example\", \"foo\", []string{\"bar\", \"1\", \"baz\", \"2\"}, \"[Realm Example](/r/lorem/ipsum$help\u0026func=foo\u0026bar=1\u0026baz=2)\", Realm(cd + \"/r/lorem/ipsum\")},\n\t\t{\"Single Arg\", \"testFunc\", []string{\"key\", \"value\"}, \"[Single Arg](/p/moul/helplink$help\u0026func=testFunc\u0026key=value)\", \"\"},\n\t\t{\"No Args\", \"noArgsFunc\", []string{}, \"[No Args](/p/moul/helplink$help\u0026func=noArgsFunc)\", \"\"},\n\t\t{\"Odd Args\", \"oddArgsFunc\", []string{\"key\"}, \"[Odd Args](/p/moul/helplink$help\u0026func=oddArgsFunc\u0026error=odd+number+of+arguments)\", \"\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.title, func(t *testing.T) {\n\t\t\tif tt.fn == \"oddArgsFunc\" {\n\t\t\t\tdefer func() {\n\t\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\t\tif r != \"odd number of arguments\" {\n\t\t\t\t\t\t\tt.Errorf(\"expected panic with message 'odd number of arguments', got: %v\", r)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tt.Error(\"expected panic for odd number of arguments, but did not panic\")\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t}\n\t\t\tgot := tt.realm_XXX.Func(tt.title, tt.fn, tt.args...)\n\t\t\turequire.Equal(t, tt.want, got)\n\t\t})\n\t}\n}\n\nfunc TestFuncURL(t *testing.T) {\n\tcd := runtime.ChainDomain()\n\ttests := []struct {\n\t\tfn        string\n\t\targs      []string\n\t\twant      string\n\t\trealm_XXX Realm\n\t}{\n\t\t{\"foo\", []string{\"bar\", \"1\", \"baz\", \"2\"}, \"/p/moul/helplink$help\u0026func=foo\u0026bar=1\u0026baz=2\", \"\"},\n\t\t{\"testFunc\", []string{\"key\", \"value\"}, \"/p/moul/helplink$help\u0026func=testFunc\u0026key=value\", \"\"},\n\t\t{\"noArgsFunc\", []string{}, \"/p/moul/helplink$help\u0026func=noArgsFunc\", \"\"},\n\t\t{\"oddArgsFunc\", []string{\"key\"}, \"/p/moul/helplink$help\u0026func=oddArgsFunc\u0026error=odd+number+of+arguments\", \"\"},\n\t\t{\"foo\", []string{\"bar\", \"1\", \"baz\", \"2\"}, \"/r/lorem/ipsum$help\u0026func=foo\u0026bar=1\u0026baz=2\", Realm(cd + \"/r/lorem/ipsum\")},\n\t\t{\"testFunc\", []string{\"key\", \"value\"}, \"/r/lorem/ipsum$help\u0026func=testFunc\u0026key=value\", Realm(cd + \"/r/lorem/ipsum\")},\n\t\t{\"noArgsFunc\", []string{}, \"/r/lorem/ipsum$help\u0026func=noArgsFunc\", Realm(cd + \"/r/lorem/ipsum\")},\n\t\t{\"oddArgsFunc\", []string{\"key\"}, \"/r/lorem/ipsum$help\u0026func=oddArgsFunc\u0026error=odd+number+of+arguments\", Realm(cd + \"/r/lorem/ipsum\")},\n\t\t{\"foo\", []string{\"bar\", \"1\", \"baz\", \"2\"}, \"https://gno.world/r/lorem/ipsum$help\u0026func=foo\u0026bar=1\u0026baz=2\", \"gno.world/r/lorem/ipsum\"},\n\t\t{\"testFunc\", []string{\"key\", \"value\"}, \"https://gno.world/r/lorem/ipsum$help\u0026func=testFunc\u0026key=value\", \"gno.world/r/lorem/ipsum\"},\n\t\t{\"noArgsFunc\", []string{}, \"https://gno.world/r/lorem/ipsum$help\u0026func=noArgsFunc\", \"gno.world/r/lorem/ipsum\"},\n\t\t{\"oddArgsFunc\", []string{\"key\"}, \"https://gno.world/r/lorem/ipsum$help\u0026func=oddArgsFunc\u0026error=odd+number+of+arguments\", \"gno.world/r/lorem/ipsum\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\ttitle := tt.fn\n\t\tt.Run(title, func(t *testing.T) {\n\t\t\tif tt.fn == \"oddArgsFunc\" {\n\t\t\t\tdefer func() {\n\t\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\t\tif r != \"odd number of arguments\" {\n\t\t\t\t\t\t\tt.Errorf(\"expected panic with message 'odd number of arguments', got: %v\", r)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tt.Error(\"expected panic for odd number of arguments, but did not panic\")\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t}\n\t\t\tgot := tt.realm_XXX.FuncURL(tt.fn, tt.args...)\n\t\t\turequire.Equal(t, tt.want, got)\n\t\t})\n\t}\n}\n\nfunc TestHome(t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/test/helplink\"))\n\tcd := runtime.ChainDomain()\n\ttests := []struct {\n\t\trealm_XXX Realm\n\t\twant      string\n\t}{\n\t\t{\"\", \"/r/test/helplink$help\"},\n\t\t{Realm(cd + \"/r/lorem/ipsum\"), \"/r/lorem/ipsum$help\"},\n\t\t{\"gno.world/r/lorem/ipsum\", \"https://gno.world/r/lorem/ipsum$help\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(string(tt.realm_XXX), func(t *testing.T) {\n\t\t\tgot := tt.realm_XXX.Home()\n\t\t\turequire.Equal(t, tt.want, got)\n\t\t})\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"i7a/jJjneFOoXG+MdzdFtkstX/yVLYligWESarnEhVwlLYQRvUMlzuCPnKNif0v7IUwWa2ltDuEAG9w3sr9sMA=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1manfred47kzduec920z88wfr64ylksmdcedlf5","package":{"name":"mdtable","path":"gno.land/p/moul/mdtable","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/mdtable\"\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\"\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"},{"name":"mdtable_test.gno","body":"package mdtable_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/mdtable\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\n// XXX: switch to `func Example() {}` when supported.\nfunc TestExample(t *testing.T) {\n\ttable := mdtable.Table{\n\t\tHeaders: []string{\"ID\", \"Title\", \"Status\"},\n\t\tRows: [][]string{\n\t\t\t{\"#1\", \"Add a new validator\", \"succeed\"},\n\t\t\t{\"#2\", \"Change parameter\", \"timed out\"},\n\t\t\t{\"#3\", \"Fill pool\", \"active\"},\n\t\t},\n\t}\n\n\tgot := table.String()\n\texpected := `| ID | Title | Status |\n| --- | --- | --- |\n| #1 | Add a new validator | succeed |\n| #2 | Change parameter | timed out |\n| #3 | Fill pool | active |\n`\n\n\turequire.Equal(t, got, expected)\n}\n\nfunc TestTableString(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\ttable    mdtable.Table\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname: \"With Headers and Rows\",\n\t\t\ttable: mdtable.Table{\n\t\t\t\tHeaders: []string{\"ID\", \"Title\", \"Status\", \"Date\"},\n\t\t\t\tRows: [][]string{\n\t\t\t\t\t{\"#1\", \"Add a new validator\", \"succeed\", \"2024-01-01\"},\n\t\t\t\t\t{\"#2\", \"Change parameter\", \"timed out\", \"2024-01-02\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `| ID | Title | Status | Date |\n| --- | --- | --- | --- |\n| #1 | Add a new validator | succeed | 2024-01-01 |\n| #2 | Change parameter | timed out | 2024-01-02 |\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"Without Headers\",\n\t\t\ttable: mdtable.Table{\n\t\t\t\tRows: [][]string{\n\t\t\t\t\t{\"#1\", \"Add a new validator\", \"succeed\", \"2024-01-01\"},\n\t\t\t\t\t{\"#2\", \"Change parameter\", \"timed out\", \"2024-01-02\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `|  |  |  |  |\n| --- | --- | --- | --- |\n| #1 | Add a new validator | succeed | 2024-01-01 |\n| #2 | Change parameter | timed out | 2024-01-02 |\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"Without Rows\",\n\t\t\ttable: mdtable.Table{\n\t\t\t\tHeaders: []string{\"ID\", \"Title\", \"Status\", \"Date\"},\n\t\t\t},\n\t\t\texpected: `| ID | Title | Status | Date |\n| --- | --- | --- | --- |\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"With Pipe Character in Content\",\n\t\t\ttable: mdtable.Table{\n\t\t\t\tHeaders: []string{\"ID\", \"Title\", \"Status\", \"Date\"},\n\t\t\t\tRows: [][]string{\n\t\t\t\t\t{\"#1\", \"Add a new | validator\", \"succeed\", \"2024-01-01\"},\n\t\t\t\t\t{\"#2\", \"Change parameter\", \"timed out\", \"2024-01-02\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `| ID | Title | Status | Date |\n| --- | --- | --- | --- |\n| #1 | Add a new \u0026#124; validator | succeed | 2024-01-01 |\n| #2 | Change parameter | timed out | 2024-01-02 |\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"With Varying Row Sizes\", // XXX: should we have a different behavior?\n\t\t\ttable: mdtable.Table{\n\t\t\t\tHeaders: []string{\"ID\", \"Title\"},\n\t\t\t\tRows: [][]string{\n\t\t\t\t\t{\"#1\", \"Add a new validator\"},\n\t\t\t\t\t{\"#2\", \"Change parameter\", \"Extra Column\"},\n\t\t\t\t\t{\"#3\", \"Fill pool\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `| ID | Title |\n| --- | --- |\n| #1 | Add a new validator |\n| #2 | Change parameter | Extra Column |\n| #3 | Fill pool |\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"With UTF-8 Characters\",\n\t\t\ttable: mdtable.Table{\n\t\t\t\tHeaders: []string{\"ID\", \"Title\", \"Status\", \"Date\"},\n\t\t\t\tRows: [][]string{\n\t\t\t\t\t{\"#1\", \"Café\", \"succeed\", \"2024-01-01\"},\n\t\t\t\t\t{\"#2\", \"München\", \"timed out\", \"2024-01-02\"},\n\t\t\t\t\t{\"#3\", \"São Paulo\", \"active\", \"2024-01-03\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `| ID | Title | Status | Date |\n| --- | --- | --- | --- |\n| #1 | Café | succeed | 2024-01-01 |\n| #2 | München | timed out | 2024-01-02 |\n| #3 | São Paulo | active | 2024-01-03 |\n`,\n\t\t},\n\t\t{\n\t\t\tname:     \"With no Headers and no Rows\",\n\t\t\ttable:    mdtable.Table{},\n\t\t\texpected: ``,\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.table.String()\n\t\t\turequire.Equal(t, got, tt.expected)\n\t\t})\n\t}\n}\n\nfunc TestTableAppend(t *testing.T) {\n\ttable := mdtable.Table{\n\t\tHeaders: []string{\"ID\", \"Title\", \"Status\", \"Date\"},\n\t}\n\n\t// Use the Append method to add rows to the table\n\ttable.Append([]string{\"#1\", \"Add a new validator\", \"succeed\", \"2024-01-01\"})\n\ttable.Append([]string{\"#2\", \"Change parameter\", \"timed out\", \"2024-01-02\"})\n\ttable.Append([]string{\"#3\", \"Fill pool\", \"active\", \"2024-01-03\"})\n\tgot := table.String()\n\n\texpected := `| ID | Title | Status | Date |\n| --- | --- | --- | --- |\n| #1 | Add a new validator | succeed | 2024-01-01 |\n| #2 | Change parameter | timed out | 2024-01-02 |\n| #3 | Fill pool | active | 2024-01-03 |\n`\n\turequire.Equal(t, got, expected)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"5eGry/ib0k1Pdi1abuImdN8XnQiidrCEgrE1SSfInyZDuKwc4XdQXb1cMFRpyWwRd9No8wboGh+9r+z5Q7V6kA=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1manfred47kzduec920z88wfr64ylksmdcedlf5","package":{"name":"realmpath","path":"gno.land/p/moul/realmpath","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/moul/realmpath\"\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\"\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"},{"name":"realmpath_test.gno","body":"package realmpath_test\n\nimport (\n\t\"chain/runtime\"\n\t\"net/url\"\n\t\"testing\"\n\n\t\"gno.land/p/moul/realmpath\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc TestExample(t *testing.T) {\n\tcd := runtime.ChainDomain()\n\ttesting.SetRealm(testing.NewCodeRealm(cd + \"/r/lorem/ipsum\"))\n\n\t// initial parsing\n\tpath := \"hello/world?foo=bar\u0026baz=foobar\"\n\treq := realmpath.Parse(path)\n\turequire.False(t, req == nil, \"req should not be nil\")\n\tuassert.Equal(t, req.Path, \"hello/world\")\n\tuassert.Equal(t, req.Query.Get(\"foo\"), \"bar\")\n\tuassert.Equal(t, req.Query.Get(\"baz\"), \"foobar\")\n\tuassert.Equal(t, req.String(), \"/r/lorem/ipsum:hello/world?baz=foobar\u0026foo=bar\")\n\n\t// alter query\n\treq.Query.Set(\"hey\", \"salut\")\n\tuassert.Equal(t, req.String(), \"/r/lorem/ipsum:hello/world?baz=foobar\u0026foo=bar\u0026hey=salut\")\n\n\t// alter path\n\treq.Path = \"bye/ciao\"\n\tuassert.Equal(t, req.String(), \"/r/lorem/ipsum:bye/ciao?baz=foobar\u0026foo=bar\u0026hey=salut\")\n}\n\nfunc TestParse(t *testing.T) {\n\tcd := runtime.ChainDomain()\n\ttesting.SetRealm(testing.NewCodeRealm(cd + \"/r/lorem/ipsum\"))\n\n\ttests := []struct {\n\t\trawPath        string\n\t\trealm_XXX      string // optional\n\t\texpectedPath   string\n\t\texpectedQuery  url.Values\n\t\texpectedString string\n\t}{\n\t\t{\n\t\t\trawPath:      \"hello/world?foo=bar\u0026baz=foobar\",\n\t\t\texpectedPath: \"hello/world\",\n\t\t\texpectedQuery: url.Values{\n\t\t\t\t\"foo\": []string{\"bar\"},\n\t\t\t\t\"baz\": []string{\"foobar\"},\n\t\t\t},\n\t\t\texpectedString: \"/r/lorem/ipsum:hello/world?baz=foobar\u0026foo=bar\",\n\t\t},\n\t\t{\n\t\t\trawPath:      \"api/v1/resource?search=test\u0026limit=10\",\n\t\t\texpectedPath: \"api/v1/resource\",\n\t\t\texpectedQuery: url.Values{\n\t\t\t\t\"search\": []string{\"test\"},\n\t\t\t\t\"limit\":  []string{\"10\"},\n\t\t\t},\n\t\t\texpectedString: \"/r/lorem/ipsum:api/v1/resource?limit=10\u0026search=test\",\n\t\t},\n\t\t{\n\t\t\trawPath:        \"singlepath\",\n\t\t\texpectedPath:   \"singlepath\",\n\t\t\texpectedQuery:  url.Values{},\n\t\t\texpectedString: \"/r/lorem/ipsum:singlepath\",\n\t\t},\n\t\t{\n\t\t\trawPath:        \"path/with/trailing/slash/\",\n\t\t\texpectedPath:   \"path/with/trailing/slash/\",\n\t\t\texpectedQuery:  url.Values{},\n\t\t\texpectedString: \"/r/lorem/ipsum:path/with/trailing/slash\",\n\t\t},\n\t\t{\n\t\t\trawPath:        \"emptyquery?\",\n\t\t\texpectedPath:   \"emptyquery\",\n\t\t\texpectedQuery:  url.Values{},\n\t\t\texpectedString: \"/r/lorem/ipsum:emptyquery\",\n\t\t},\n\t\t{\n\t\t\trawPath:      \"path/with/special/characters/?key=val%20ue\u0026anotherKey=with%21special%23chars\",\n\t\t\texpectedPath: \"path/with/special/characters/\",\n\t\t\texpectedQuery: url.Values{\n\t\t\t\t\"key\":        []string{\"val ue\"},\n\t\t\t\t\"anotherKey\": []string{\"with!special#chars\"},\n\t\t\t},\n\t\t\texpectedString: \"/r/lorem/ipsum:path/with/special/characters?anotherKey=with%21special%23chars\u0026key=val+ue\",\n\t\t},\n\t\t{\n\t\t\trawPath:      \"path/with/empty/key?keyEmpty\u0026=valueEmpty\",\n\t\t\texpectedPath: \"path/with/empty/key\",\n\t\t\texpectedQuery: url.Values{\n\t\t\t\t\"keyEmpty\": []string{\"\"},\n\t\t\t\t\"\":         []string{\"valueEmpty\"},\n\t\t\t},\n\t\t\texpectedString: \"/r/lorem/ipsum:path/with/empty/key?=valueEmpty\u0026keyEmpty=\",\n\t\t},\n\t\t{\n\t\t\trawPath:      \"path/with/multiple/empty/keys?=empty1\u0026=empty2\",\n\t\t\texpectedPath: \"path/with/multiple/empty/keys\",\n\t\t\texpectedQuery: url.Values{\n\t\t\t\t\"\": []string{\"empty1\", \"empty2\"},\n\t\t\t},\n\t\t\texpectedString: \"/r/lorem/ipsum:path/with/multiple/empty/keys?=empty1\u0026=empty2\",\n\t\t},\n\t\t{\n\t\t\trawPath:      \"path/with/percent-encoded/%20space?query=hello%20world\",\n\t\t\texpectedPath: \"path/with/percent-encoded/%20space\", // XXX: should we decode?\n\t\t\texpectedQuery: url.Values{\n\t\t\t\t\"query\": []string{\"hello world\"},\n\t\t\t},\n\t\t\texpectedString: \"/r/lorem/ipsum:path/with/percent-encoded/%20space?query=hello+world\",\n\t\t},\n\t\t{\n\t\t\trawPath:      \"path/with/very/long/query?key1=value1\u0026key2=value2\u0026key3=value3\u0026key4=value4\u0026key5=value5\u0026key6=value6\",\n\t\t\texpectedPath: \"path/with/very/long/query\",\n\t\t\texpectedQuery: url.Values{\n\t\t\t\t\"key1\": []string{\"value1\"},\n\t\t\t\t\"key2\": []string{\"value2\"},\n\t\t\t\t\"key3\": []string{\"value3\"},\n\t\t\t\t\"key4\": []string{\"value4\"},\n\t\t\t\t\"key5\": []string{\"value5\"},\n\t\t\t\t\"key6\": []string{\"value6\"},\n\t\t\t},\n\t\t\texpectedString: \"/r/lorem/ipsum:path/with/very/long/query?key1=value1\u0026key2=value2\u0026key3=value3\u0026key4=value4\u0026key5=value5\u0026key6=value6\",\n\t\t},\n\t\t{\n\t\t\trawPath:      \"custom/realm?foo=bar\u0026baz=foobar\",\n\t\t\trealm_XXX:    cd + \"/r/foo/bar\",\n\t\t\texpectedPath: \"custom/realm\",\n\t\t\texpectedQuery: url.Values{\n\t\t\t\t\"foo\": []string{\"bar\"},\n\t\t\t\t\"baz\": []string{\"foobar\"},\n\t\t\t},\n\t\t\texpectedString: \"/r/foo/bar:custom/realm?baz=foobar\u0026foo=bar\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.rawPath, func(t *testing.T) {\n\t\t\treq := realmpath.Parse(tt.rawPath)\n\t\t\treq.Realm = tt.realm_XXX // set optional realm\n\t\t\turequire.False(t, req == nil, \"req should not be nil\")\n\t\t\tuassert.Equal(t, req.Path, tt.expectedPath)\n\t\t\turequire.Equal(t, len(req.Query), len(tt.expectedQuery))\n\t\t\tuassert.Equal(t, req.Query.Encode(), tt.expectedQuery.Encode())\n\t\t\t// XXX: uassert.Equal(t, req.Query, tt.expectedQuery)\n\t\t\tuassert.Equal(t, req.String(), tt.expectedString)\n\t\t})\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"Sts/7k2lGA4hf9BSRB+czijYqgeC8bVhsMA9bpx7azxPTOgUBvX0A9dDgJx0cf3NJm1rVEX9HJ/K54d9B7qhdg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g15ge0ae9077eh40erwrn2eq0xw6wupwqthpv34l","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 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":"addrset_test.gno","body":"package addrset\n\nimport (\n\t\"strconv\"\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\nconst (\n\taddr1 = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n\taddr2 = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\")\n\taddr3 = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\")\n)\n\nfunc TestSetBasics(t *testing.T) {\n\tvar set Set // the zero value is a usable empty set\n\n\tuassert.Equal(t, 0, set.Size())\n\tuassert.False(t, set.Has(addr1))\n\tuassert.False(t, set.Remove(addr1))\n\n\tuassert.True(t, set.Add(addr1), \"expect newly added\")\n\tuassert.False(t, set.Add(addr1), \"expect duplicate add to report existing\")\n\tuassert.True(t, set.Has(addr1))\n\tuassert.Equal(t, 1, set.Size())\n\n\tuassert.True(t, set.Add(addr2))\n\tuassert.True(t, set.Add(addr3))\n\tuassert.Equal(t, 3, set.Size())\n\n\tuassert.True(t, set.Remove(addr2), \"expect removal of present address\")\n\tuassert.False(t, set.Remove(addr2), \"expect second removal to report absent\")\n\tuassert.False(t, set.Has(addr2))\n\tuassert.Equal(t, 2, set.Size())\n}\n\nfunc TestSetIteration(t *testing.T) {\n\tvar set Set\n\tset.Add(addr1)\n\tset.Add(addr2)\n\tset.Add(addr3)\n\n\t// Sorted (bech32-string) order: addr3 \u003c addr1 \u003c addr2.\n\tvar got []address\n\tset.IterateByOffset(0, set.Size(), func(a address) bool {\n\t\tgot = append(got, a)\n\t\treturn false\n\t})\n\turequire.Equal(t, 3, len(got))\n\tuassert.True(t, got[0] == addr3 \u0026\u0026 got[1] == addr1 \u0026\u0026 got[2] == addr2, \"expect sorted order\")\n\n\t// Offset and count window.\n\tgot = nil\n\tset.IterateByOffset(1, 1, func(a address) bool {\n\t\tgot = append(got, a)\n\t\treturn false\n\t})\n\turequire.Equal(t, 1, len(got))\n\tuassert.True(t, got[0] == addr1, \"expect the middle element\")\n\n\t// Early stop.\n\tcount := 0\n\tset.IterateByOffset(0, set.Size(), func(a address) bool {\n\t\tcount++\n\t\treturn true\n\t})\n\tuassert.Equal(t, 1, count)\n\n\t// Reverse order.\n\tgot = nil\n\tset.ReverseIterateByOffset(0, set.Size(), func(a address) bool {\n\t\tgot = append(got, a)\n\t\treturn false\n\t})\n\turequire.Equal(t, 3, len(got))\n\tuassert.True(t, got[0] == addr2 \u0026\u0026 got[2] == addr3, \"expect reverse order\")\n}\n\nfunc TestSetIterationLimits(t *testing.T) {\n\tvar set Set\n\tset.Add(addr1)\n\tset.Add(addr2)\n\tset.Add(addr3)\n\n\t// Offset at/beyond the size visits nothing, in both directions.\n\tvisits := 0\n\tcount := func(a address) bool { visits++; return false }\n\tset.IterateByOffset(3, 10, count)\n\tset.IterateByOffset(99, 10, count)\n\tset.ReverseIterateByOffset(3, 10, count)\n\tuassert.Equal(t, 0, visits)\n\n\t// A count larger than the remainder visits just the remainder.\n\tset.IterateByOffset(1, 10, count)\n\tuassert.Equal(t, 2, visits)\n\n\t// The reverse offset counts from the END: offset 1, count 1 is the\n\t// second-to-last address in sorted order (addr1: addr3 \u003c addr1 \u003c addr2).\n\tvar got []address\n\tset.ReverseIterateByOffset(1, 1, func(a address) bool {\n\t\tgot = append(got, a)\n\t\treturn false\n\t})\n\turequire.Equal(t, 1, len(got))\n\tuassert.True(t, got[0] == addr1, \"expect reverse offset anchored at the end\")\n}\n\n// TestSetAcrossLeafSplits exercises the wrapper over a multi-leaf tree\n// (the backing splits past fanout 32): ordering, offset windows in both\n// directions, and removal back down through merges.\nfunc TestSetAcrossLeafSplits(t *testing.T) {\n\tconst n = 100\n\n\tvar (\n\t\tset   Set\n\t\taddrs []address\n\t)\n\tfor i := 0; i \u003c n; i++ {\n\t\t// Zero-padded so generation order == lexicographic order.\n\t\ts := strconv.Itoa(i)\n\t\taddrs = append(addrs, address(\"g1\"+strings.Repeat(\"0\", 38-len(s))+s))\n\t}\n\tfor _, a := range addrs {\n\t\turequire.True(t, set.Add(a), \"expect newly added\")\n\t}\n\turequire.Equal(t, n, set.Size())\n\n\t// Full forward iteration is complete and sorted (keys were generated\n\t// in sorted order).\n\ti := 0\n\tset.IterateByOffset(0, n, func(a address) bool {\n\t\turequire.True(t, a == addrs[i], \"expect sorted order at \"+strconv.Itoa(i))\n\t\ti++\n\t\treturn false\n\t})\n\turequire.Equal(t, n, i)\n\n\t// An offset window that crosses leaf boundaries.\n\tvar got []address\n\tset.IterateByOffset(30, 10, func(a address) bool {\n\t\tgot = append(got, a)\n\t\treturn false\n\t})\n\turequire.Equal(t, 10, len(got))\n\tuassert.True(t, got[0] == addrs[30] \u0026\u0026 got[9] == addrs[39], \"expect window [30,40)\")\n\n\t// Reverse window anchored from the end.\n\tgot = nil\n\tset.ReverseIterateByOffset(10, 5, func(a address) bool {\n\t\tgot = append(got, a)\n\t\treturn false\n\t})\n\turequire.Equal(t, 5, len(got))\n\tuassert.True(t, got[0] == addrs[n-11] \u0026\u0026 got[4] == addrs[n-15], \"expect reverse window from the end\")\n\n\t// Remove every other address (drives leaf merges), then verify.\n\tfor i := 0; i \u003c n; i += 2 {\n\t\turequire.True(t, set.Remove(addrs[i]), \"expect removal\")\n\t}\n\turequire.Equal(t, n/2, set.Size())\n\tfor i := 0; i \u003c n; i++ {\n\t\tuassert.Equal(t, i%2 == 1, set.Has(addrs[i]))\n\t}\n}\n\nfunc TestReadonlySet(t *testing.T) {\n\tvar set Set\n\tset.Add(addr1)\n\n\tview := set.Readonly()\n\tuassert.True(t, view.Has(addr1))\n\tuassert.Equal(t, 1, view.Size())\n\n\t// The view is a live handle, not a snapshot.\n\tset.Add(addr2)\n\tuassert.Equal(t, 2, view.Size())\n\tuassert.True(t, view.Has(addr2))\n\n\t// Iteration mirrors the set and reports early stop.\n\tstopped := view.IterateByOffset(0, view.Size(), func(a address) bool { return false })\n\tuassert.False(t, stopped)\n\tstopped = view.IterateByOffset(0, view.Size(), func(a address) bool { return true })\n\tuassert.True(t, stopped)\n\n\tstopped = view.ReverseIterateByOffset(0, view.Size(), func(a address) bool { return true })\n\tuassert.True(t, stopped)\n\n\t// An empty set's view iterates nothing and reports not-stopped.\n\tempty := NewReadonlySet(\u0026Set{})\n\tuassert.Equal(t, 0, empty.Size())\n\tstopped = empty.IterateByOffset(0, 10, func(a address) bool { return true })\n\tuassert.False(t, stopped)\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"MMbs5Fxg4xqx1BRTN0RyuZsfVXS7Ncvn4+6VA00xuuxef1UXDeHiNuVoGhCJ+QscjY2SyTmFFk6Px63vcpSf4A=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"rotree","path":"gno.land/p/nt/bptree/v0/rotree","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/bptree/v0/rotree\"\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"},{"name":"rotree_test.gno","body":"package rotree\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n)\n\nfunc TestExample(t *testing.T) {\n\t// User represents our internal data structure\n\ttype User struct {\n\t\tID       string\n\t\tName     string\n\t\tBalance  int\n\t\tInternal string // sensitive internal data\n\t}\n\n\t// Create and populate the original tree with user pointers\n\ttree := bptree.NewBPTree32()\n\ttree.Set(\"alice\", \u0026User{\n\t\tID:       \"1\",\n\t\tName:     \"Alice\",\n\t\tBalance:  100,\n\t\tInternal: \"sensitive_data_1\",\n\t})\n\ttree.Set(\"bob\", \u0026User{\n\t\tID:       \"2\",\n\t\tName:     \"Bob\",\n\t\tBalance:  200,\n\t\tInternal: \"sensitive_data_2\",\n\t})\n\n\t// Define a makeEntrySafeFn that:\n\t// 1. Creates a defensive copy of the User struct\n\t// 2. Omits sensitive internal data\n\tmakeEntrySafeFn := func(v any) any {\n\t\toriginalUser := v.(*User)\n\t\treturn \u0026User{\n\t\t\tID:       originalUser.ID,\n\t\t\tName:     originalUser.Name,\n\t\t\tBalance:  originalUser.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\troTree := Wrap(tree, makeEntrySafeFn)\n\n\t// Test retrieving and verifying a user\n\tt.Run(\"Get User\", func(t *testing.T) {\n\t\t// Get user from read-only tree\n\t\tvalue := roTree.Get(\"alice\")\n\t\tif value == nil {\n\t\t\tt.Fatal(\"User 'alice' not found\")\n\t\t}\n\n\t\tuser := value.(*User)\n\n\t\t// Verify user data is correct\n\t\tif user.Name != \"Alice\" || user.Balance != 100 {\n\t\t\tt.Errorf(\"Unexpected user data: got name=%s balance=%d\", user.Name, user.Balance)\n\t\t}\n\n\t\t// Verify sensitive data is not exposed\n\t\tif user.Internal != \"\" {\n\t\t\tt.Error(\"Sensitive data should not be exposed\")\n\t\t}\n\n\t\t// Verify it's a different instance than the original\n\t\toriginalValue := tree.Get(\"alice\")\n\t\toriginalUser := originalValue.(*User)\n\t\tif user == originalUser {\n\t\t\tt.Error(\"Read-only tree should return a copy, not the original pointer\")\n\t\t}\n\t})\n\n\t// Test iterating over users\n\tt.Run(\"Iterate Users\", func(t *testing.T) {\n\t\tcount := 0\n\t\troTree.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\t\tuser := value.(*User)\n\t\t\t// Verify each user has empty Internal field\n\t\t\tif user.Internal != \"\" {\n\t\t\t\tt.Error(\"Sensitive data exposed during iteration\")\n\t\t\t}\n\t\t\tcount++\n\t\t\treturn false\n\t\t})\n\n\t\tif count != 2 {\n\t\t\tt.Errorf(\"Expected 2 users, got %d\", count)\n\t\t}\n\t})\n\n\t// Verify that modifications to the returned user don't affect the original\n\tt.Run(\"Modification Safety\", func(t *testing.T) {\n\t\tvalue := roTree.Get(\"alice\")\n\t\tuser := value.(*User)\n\n\t\t// Try to modify the returned user\n\t\tuser.Balance = 999\n\t\tuser.Internal = \"hacked\"\n\n\t\t// Verify original is unchanged\n\t\toriginalValue := tree.Get(\"alice\")\n\t\toriginalUser := originalValue.(*User)\n\t\tif originalUser.Balance != 100 || originalUser.Internal != \"sensitive_data_1\" {\n\t\t\tt.Error(\"Original user data was modified\")\n\t\t}\n\t})\n}\n\nfunc TestReadOnlyTree(t *testing.T) {\n\t// Example of a makeEntrySafeFn that appends \"_readonly\" to demonstrate transformation\n\tmakeEntrySafeFn := func(value any) any {\n\t\treturn value.(string) + \"_readonly\"\n\t}\n\n\ttree := bptree.NewBPTree32()\n\ttree.Set(\"key1\", \"value1\")\n\ttree.Set(\"key2\", \"value2\")\n\ttree.Set(\"key3\", \"value3\")\n\n\troTree := Wrap(tree, makeEntrySafeFn)\n\n\ttests := []struct {\n\t\tname     string\n\t\tkey      string\n\t\texpected any\n\t}{\n\t\t{\"ExistingKey1\", \"key1\", \"value1_readonly\"},\n\t\t{\"ExistingKey2\", \"key2\", \"value2_readonly\"},\n\t\t{\"NonExistingKey\", \"key4\", nil},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvalue := roTree.Get(tt.key)\n\t\t\tif value != tt.expected {\n\t\t\t\tt.Errorf(\"For key %s, expected %v, got %v\", tt.key, tt.expected, value)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Add example tests showing different makeEntrySafeFn implementations\nfunc TestMakeEntrySafeFnVariants(t *testing.T) {\n\ttree := bptree.NewBPTree32()\n\ttree.Set(\"slice\", []int{1, 2, 3})\n\ttree.Set(\"map\", map[string]int{\"a\": 1})\n\n\ttests := []struct {\n\t\tname            string\n\t\tmakeEntrySafeFn func(any) any\n\t\tkey             string\n\t\tvalidate        func(t *testing.T, value any)\n\t}{\n\t\t{\n\t\t\tname: \"Defensive Copy Slice\",\n\t\t\tmakeEntrySafeFn: func(v any) any {\n\t\t\t\toriginal := v.([]int)\n\t\t\t\treturn append([]int{}, original...)\n\t\t\t},\n\t\t\tkey: \"slice\",\n\t\t\tvalidate: func(t *testing.T, value any) {\n\t\t\t\tslice := value.([]int)\n\t\t\t\t// Modify the returned slice\n\t\t\t\tslice[0] = 999\n\t\t\t\t// Verify original is unchanged\n\t\t\t\toriginalValue := tree.Get(\"slice\")\n\t\t\t\toriginal := originalValue.([]int)\n\t\t\t\tif original[0] != 1 {\n\t\t\t\t\tt.Error(\"Original slice was modified\")\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t// Add more test cases for different makeEntrySafeFn implementations\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\troTree := Wrap(tree, tt.makeEntrySafeFn)\n\t\t\tvalue := roTree.Get(tt.key)\n\t\t\tif value == nil {\n\t\t\t\tt.Fatal(\"Key not found\")\n\t\t\t}\n\t\t\ttt.validate(t, value)\n\t\t})\n\t}\n}\n\nfunc TestNilMakeEntrySafeFn(t *testing.T) {\n\t// Create a tree with some test data\n\ttree := bptree.NewBPTree32()\n\toriginalValue := []int{1, 2, 3}\n\ttree.Set(\"test\", originalValue)\n\n\t// Create a ReadOnlyTree with nil makeEntrySafeFn\n\troTree := Wrap(tree, nil)\n\n\t// Test that we get back the original value\n\tvalue := roTree.Get(\"test\")\n\tif value == nil {\n\t\tt.Fatal(\"Key not found\")\n\t}\n\n\t// Verify it's the exact same slice (not a copy)\n\tretrievedSlice := value.([]int)\n\tif \u0026retrievedSlice[0] != \u0026originalValue[0] {\n\t\tt.Error(\"Expected to get back the original slice reference\")\n\t}\n\n\t// Test through iteration as well\n\troTree.Iterate(\"\", \"\", func(key string, value any) bool {\n\t\tretrievedSlice := value.([]int)\n\t\tif \u0026retrievedSlice[0] != \u0026originalValue[0] {\n\t\t\tt.Error(\"Expected to get back the original slice reference in iteration\")\n\t\t}\n\t\treturn false\n\t})\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"S1W4XO6yGEXaW+vv723IegmbuhsYnaUIu4gonopFhmEMvLe3u5aAoTsoR2LkcPLltvCfXw8campWJm25U7zu4w=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"list","path":"gno.land/p/nt/bptree/v0/list","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/bptree/v0/list\"\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/v0\"\n\t\"gno.land/p/nt/bptree/v0/rotree\"\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"},{"name":"list_test.gno","body":"package list\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nfunc TestList_Basic(t *testing.T) {\n\tvar l List\n\n\t// Test empty list\n\tif l.Len() != 0 {\n\t\tt.Errorf(\"new list should be empty, got len %d\", l.Len())\n\t}\n\n\t// Test append and length\n\tl.Append(1, 2, 3)\n\tif l.Len() != 3 {\n\t\tt.Errorf(\"expected len 3, got %d\", l.Len())\n\t}\n\n\t// Test get\n\tif v, _ := l.Get(0); v != 1 {\n\t\tt.Errorf(\"expected 1 at index 0, got %v\", v)\n\t}\n\tif v, _ := l.Get(1); v != 2 {\n\t\tt.Errorf(\"expected 2 at index 1, got %v\", v)\n\t}\n\tif v, _ := l.Get(2); v != 3 {\n\t\tt.Errorf(\"expected 3 at index 2, got %v\", v)\n\t}\n\n\t// Test out of bounds\n\tif _, ok := l.Get(-1); ok {\n\t\tt.Error(\"expected ok=false for negative index\")\n\t}\n\tif _, ok := l.Get(3); ok {\n\t\tt.Error(\"expected ok=false for out of bounds index\")\n\t}\n}\n\nfunc TestList_Set(t *testing.T) {\n\tvar l List\n\tl.Append(1, 2, 3)\n\n\t// Test valid set within bounds\n\tif ok := l.Set(1, 42); !ok {\n\t\tt.Error(\"Set should return true for valid index\")\n\t}\n\tif v, _ := l.Get(1); v != 42 {\n\t\tt.Errorf(\"expected 42 after Set, got %v\", v)\n\t}\n\n\t// Test set at size (append)\n\tif ok := l.Set(3, 4); !ok {\n\t\tt.Error(\"Set should return true when appending at size\")\n\t}\n\tif v, _ := l.Get(3); v != 4 {\n\t\tt.Errorf(\"expected 4 after Set at size, got %v\", v)\n\t}\n\n\t// Test invalid sets\n\tif ok := l.Set(-1, 10); ok {\n\t\tt.Error(\"Set should return false for negative index\")\n\t}\n\tif ok := l.Set(5, 10); ok {\n\t\tt.Error(\"Set should return false for index \u003e size\")\n\t}\n\n\t// Verify list state hasn't changed after invalid operations\n\texpected := []any{1, 42, 3, 4}\n\tfor i, want := range expected {\n\t\tif got, _ := l.Get(i); got != want {\n\t\t\tt.Errorf(\"index %d = %v; want %v\", i, got, want)\n\t\t}\n\t}\n}\n\nfunc TestList_Delete(t *testing.T) {\n\tvar l List\n\tl.Append(1, 2, 3)\n\n\t// Test valid delete\n\tif v, ok := l.Delete(1); !ok || v != 2 {\n\t\tt.Errorf(\"Delete(1) = %v, %v; want 2, true\", v, ok)\n\t}\n\tif l.Len() != 2 {\n\t\tt.Errorf(\"expected len 2 after delete, got %d\", l.Len())\n\t}\n\tif v, _ := l.Get(1); v != 3 {\n\t\tt.Errorf(\"expected 3 at index 1 after delete, got %v\", v)\n\t}\n\n\t// Test invalid delete\n\tif v, ok := l.Delete(-1); ok || v != nil {\n\t\tt.Errorf(\"Delete(-1) = %v, %v; want nil, false\", v, ok)\n\t}\n\tif v, ok := l.Delete(2); ok || v != nil {\n\t\tt.Errorf(\"Delete(2) = %v, %v; want nil, false\", v, ok)\n\t}\n}\n\nfunc TestList_Slice(t *testing.T) {\n\tvar l List\n\tl.Append(1, 2, 3, 4, 5)\n\n\t// Test valid ranges\n\tvalues := l.Slice(1, 4)\n\texpected := []any{2, 3, 4}\n\tif !sliceEqual(values, expected) {\n\t\tt.Errorf(\"Slice(1,4) = %v; want %v\", values, expected)\n\t}\n\n\t// Test edge cases\n\tif values := l.Slice(-1, 2); !sliceEqual(values, []any{1, 2}) {\n\t\tt.Errorf(\"Slice(-1,2) = %v; want [1 2]\", values)\n\t}\n\tif values := l.Slice(3, 10); !sliceEqual(values, []any{4, 5}) {\n\t\tt.Errorf(\"Slice(3,10) = %v; want [4 5]\", values)\n\t}\n\tif values := l.Slice(3, 2); values != nil {\n\t\tt.Errorf(\"Slice(3,2) = %v; want nil\", values)\n\t}\n}\n\nfunc TestList_ForEach(t *testing.T) {\n\tvar l List\n\tl.Append(1, 2, 3)\n\n\tsum := 0\n\tl.ForEach(func(index int, value any) bool {\n\t\tsum += value.(int)\n\t\treturn false\n\t})\n\n\tif sum != 6 {\n\t\tt.Errorf(\"ForEach sum = %d; want 6\", sum)\n\t}\n\n\t// Test early termination\n\tcount := 0\n\tl.ForEach(func(index int, value any) bool {\n\t\tcount++\n\t\treturn true // stop after first item\n\t})\n\n\tif count != 1 {\n\t\tt.Errorf(\"ForEach early termination count = %d; want 1\", count)\n\t}\n}\n\nfunc TestList_Clone(t *testing.T) {\n\tvar l List\n\tl.Append(1, 2, 3)\n\n\tclone := l.Clone()\n\n\t// Test same length\n\tif clone.Len() != l.Len() {\n\t\tt.Errorf(\"clone.Len() = %d; want %d\", clone.Len(), l.Len())\n\t}\n\n\t// Test same values\n\tfor i := 0; i \u003c l.Len(); i++ {\n\t\tcv, _ := clone.Get(i)\n\t\tlv, _ := l.Get(i)\n\t\tif cv != lv {\n\t\t\tt.Errorf(\"clone.Get(%d) = %v; want %v\", i, cv, lv)\n\t\t}\n\t}\n\n\t// Test independence\n\tl.Set(0, 42)\n\tcv, _ := clone.Get(0)\n\tlv, _ := l.Get(0)\n\tif cv == lv {\n\t\tt.Error(\"clone should be independent of original\")\n\t}\n\n\t// Test that appending to both after clone works independently.\n\tvar l2 List\n\tl2.Append(\"a\", \"b\", \"c\")\n\tclone2 := l2.Clone()\n\n\tl2.Append(\"d\", \"e\")\n\tclone2.Append(\"x\", \"y\")\n\n\tif l2.Len() != 5 {\n\t\tt.Errorf(\"original after append: Len() = %d; want 5\", l2.Len())\n\t}\n\tif clone2.Len() != 5 {\n\t\tt.Errorf(\"clone after append: Len() = %d; want 5\", clone2.Len())\n\t}\n\torigExpected := []any{\"a\", \"b\", \"c\", \"d\", \"e\"}\n\tcloneExpected := []any{\"a\", \"b\", \"c\", \"x\", \"y\"}\n\tfor i := 0; i \u003c 5; i++ {\n\t\tov, _ := l2.Get(i)\n\t\tif ov != origExpected[i] {\n\t\t\tt.Errorf(\"original.Get(%d) = %v; want %v\", i, ov, origExpected[i])\n\t\t}\n\t\tcv, _ := clone2.Get(i)\n\t\tif cv != cloneExpected[i] {\n\t\t\tt.Errorf(\"clone.Get(%d) = %v; want %v\", i, cv, cloneExpected[i])\n\t\t}\n\t}\n}\n\nfunc TestList_DeleteRange(t *testing.T) {\n\tvar l List\n\tl.Append(1, 2, 3, 4, 5)\n\n\t// Test valid range delete\n\tdeleted := l.DeleteRange(1, 4)\n\tif deleted != 3 {\n\t\tt.Errorf(\"DeleteRange(1,4) deleted %d elements; want 3\", deleted)\n\t}\n\tif l.Len() != 2 {\n\t\tt.Errorf(\"after DeleteRange(1,4) len = %d; want 2\", l.Len())\n\t}\n\texpected := []any{1, 5}\n\tfor i, want := range expected {\n\t\tif got, _ := l.Get(i); got != want {\n\t\t\tt.Errorf(\"after DeleteRange(1,4) index %d = %v; want %v\", i, got, want)\n\t\t}\n\t}\n\n\t// Test edge cases\n\tl = List{}\n\tl.Append(1, 2, 3)\n\n\t// Delete with negative start\n\tif deleted := l.DeleteRange(-1, 2); deleted != 2 {\n\t\tt.Errorf(\"DeleteRange(-1,2) deleted %d elements; want 2\", deleted)\n\t}\n\n\t// Delete with end \u003e length\n\tl = List{}\n\tl.Append(1, 2, 3)\n\tif deleted := l.DeleteRange(1, 5); deleted != 2 {\n\t\tt.Errorf(\"DeleteRange(1,5) deleted %d elements; want 2\", deleted)\n\t}\n\n\t// Delete invalid range\n\tif deleted := l.DeleteRange(2, 1); deleted != 0 {\n\t\tt.Errorf(\"DeleteRange(2,1) deleted %d elements; want 0\", deleted)\n\t}\n\n\t// Delete empty range\n\tif deleted := l.DeleteRange(1, 1); deleted != 0 {\n\t\tt.Errorf(\"DeleteRange(1,1) deleted %d elements; want 0\", deleted)\n\t}\n}\n\nfunc TestList_Tree(t *testing.T) {\n\tvar l List\n\tl.Append(1, 2, 3)\n\n\trotree := l.Tree()\n\texpected := 3\n\n\t// Reverse iterate through the ReadOnlyTree\n\trotree.ReverseIterateByOffset(0, rotree.Size(), func(key string, value any) bool {\n\t\tintValue := value.(int)\n\t\tif intValue != expected {\n\t\t\tt.Errorf(\"ReadOnlyTree expected %d, got %d\", expected, intValue)\n\t\t}\n\t\texpected--\n\t\treturn false\n\t})\n}\n\nfunc TestList_EmptyOperations(t *testing.T) {\n\tvar l List\n\n\t// Operations on empty list\n\tif _, ok := l.Get(0); ok {\n\t\tt.Error(\"Get(0) on empty list should return ok=false\")\n\t}\n\n\t// Set should work at index 0 for empty list (append case)\n\tif ok := l.Set(0, 1); !ok {\n\t\tt.Error(\"Set(0,1) on empty list = false; want true\")\n\t}\n\tif v, _ := l.Get(0); v != 1 {\n\t\tt.Errorf(\"Get(0) after Set = %v; want 1\", v)\n\t}\n\n\tl = List{} // Reset to empty list\n\tif v, ok := l.Delete(0); ok || v != nil {\n\t\tt.Errorf(\"Delete(0) on empty list = %v, %v; want nil, false\", v, ok)\n\t}\n\tif values := l.Slice(0, 1); values != nil {\n\t\tt.Errorf(\"Range(0,1) on empty list = %v; want nil\", values)\n\t}\n}\n\nfunc TestList_DifferentTypes(t *testing.T) {\n\tvar l List\n\n\t// Test with different types\n\tl.Append(42, \"hello\", true, 3.14)\n\n\tv0, _ := l.Get(0)\n\tif v := v0.(int); v != 42 {\n\t\tt.Errorf(\"Get(0) = %v; want 42\", v)\n\t}\n\tv1, _ := l.Get(1)\n\tif v := v1.(string); v != \"hello\" {\n\t\tt.Errorf(\"Get(1) = %v; want 'hello'\", v)\n\t}\n\tv2, _ := l.Get(2)\n\tif v := v2.(bool); !v {\n\t\tt.Errorf(\"Get(2) = %v; want true\", v)\n\t}\n\tv3, _ := l.Get(3)\n\tif v := v3.(float64); v != 3.14 {\n\t\tt.Errorf(\"Get(3) = %v; want 3.14\", v)\n\t}\n}\n\nfunc TestList_LargeOperations(t *testing.T) {\n\tvar l List\n\n\t// Test with larger number of elements\n\tn := 1000\n\tfor i := 0; i \u003c n; i++ {\n\t\tl.Append(i)\n\t}\n\n\tif l.Len() != n {\n\t\tt.Errorf(\"Len() = %d; want %d\", l.Len(), n)\n\t}\n\n\t// Test range on large list\n\tvalues := l.Slice(n-3, n)\n\texpected := []any{n - 3, n - 2, n - 1}\n\tif !sliceEqual(values, expected) {\n\t\tt.Errorf(\"Range(%d,%d) = %v; want %v\", n-3, n, values, expected)\n\t}\n\n\t// Test large range deletion\n\tdeleted := l.DeleteRange(100, 900)\n\tif deleted != 800 {\n\t\tt.Errorf(\"DeleteRange(100,900) = %d; want 800\", deleted)\n\t}\n\tif l.Len() != 200 {\n\t\tt.Errorf(\"Len() after large delete = %d; want 200\", l.Len())\n\t}\n}\n\nfunc TestList_ChainedOperations(t *testing.T) {\n\tvar l List\n\n\t// Test sequence of operations\n\tl.Append(1, 2, 3)\n\tl.Delete(1)\n\tl.Append(4)\n\tl.Set(1, 5)\n\n\texpected := []any{1, 5, 4}\n\tfor i, want := range expected {\n\t\tif got, _ := l.Get(i); got != want {\n\t\t\tt.Errorf(\"index %d = %v; want %v\", i, got, want)\n\t\t}\n\t}\n}\n\nfunc TestList_RangeEdgeCases(t *testing.T) {\n\tvar l List\n\tl.Append(1, 2, 3, 4, 5)\n\n\t// Test various edge cases for Range\n\tcases := []struct {\n\t\tstart, end int\n\t\twant       []any\n\t}{\n\t\t{-10, 2, []any{1, 2}},\n\t\t{3, 10, []any{4, 5}},\n\t\t{0, 0, nil},\n\t\t{5, 5, nil},\n\t\t{4, 3, nil},\n\t\t{-1, -1, nil},\n\t}\n\n\tfor _, tc := range cases {\n\t\tgot := l.Slice(tc.start, tc.end)\n\t\tif !sliceEqual(got, tc.want) {\n\t\t\tt.Errorf(\"Slice(%d,%d) = %v; want %v\", tc.start, tc.end, got, tc.want)\n\t\t}\n\t}\n}\n\nfunc TestList_IndexConsistency(t *testing.T) {\n\tvar l List\n\n\t// Initial additions\n\tl.Append(1, 2, 3, 4, 5) // [1,2,3,4,5]\n\n\t// Delete from middle\n\tl.Delete(2) // [1,2,4,5]\n\n\t// Add more elements\n\tl.Append(6, 7) // [1,2,4,5,6,7]\n\n\t// Delete range from middle\n\tl.DeleteRange(1, 4) // [1,6,7]\n\n\t// Add more elements\n\tl.Append(8, 9, 10) // [1,6,7,8,9,10]\n\n\t// Verify sequence is continuous\n\texpected := []any{1, 6, 7, 8, 9, 10}\n\tfor i, want := range expected {\n\t\tif got, _ := l.Get(i); got != want {\n\t\t\tt.Errorf(\"index %d = %v; want %v\", i, got, want)\n\t\t}\n\t}\n\n\t// Verify no extra elements exist\n\tif l.Len() != len(expected) {\n\t\tt.Errorf(\"length = %d; want %d\", l.Len(), len(expected))\n\t}\n\n\t// Verify all indices are accessible\n\tallValues := l.Slice(0, l.Len())\n\tif !sliceEqual(allValues, expected) {\n\t\tt.Errorf(\"Slice(0, Len()) = %v; want %v\", allValues, expected)\n\t}\n\n\t// Verify no gaps in iteration\n\tvar iteratedValues []any\n\tvar indices []int\n\tl.ForEach(func(index int, value any) bool {\n\t\titeratedValues = append(iteratedValues, value)\n\t\tindices = append(indices, index)\n\t\treturn false\n\t})\n\n\t// Check values from iteration\n\tif !sliceEqual(iteratedValues, expected) {\n\t\tt.Errorf(\"ForEach values = %v; want %v\", iteratedValues, expected)\n\t}\n\n\t// Check indices are sequential\n\tfor i, idx := range indices {\n\t\tif idx != i {\n\t\t\tt.Errorf(\"ForEach index %d = %d; want %d\", i, idx, i)\n\t\t}\n\t}\n}\n\nfunc TestList_RecursiveSafety(t *testing.T) {\n\t// Create a new list\n\tl := \u0026List{}\n\n\t// Add some initial values\n\tl.Append(\"id1\")\n\tl.Append(\"id2\")\n\tl.Append(\"id3\")\n\n\t// Test deep list traversal\n\tfound := false\n\tl.ForEach(func(i int, v any) bool {\n\t\tif str, ok := v.(string); ok {\n\t\t\tif str == \"id2\" {\n\t\t\t\tfound = true\n\t\t\t\treturn true // stop iteration\n\t\t\t}\n\t\t}\n\t\treturn false // continue iteration\n\t})\n\n\tif !found {\n\t\tt.Error(\"Failed to find expected value in list\")\n\t}\n\n\tshort := testing.Short()\n\n\t// Test recursive safety by performing multiple operations\n\tfor i := 0; i \u003c 1000; i++ {\n\t\t// Add new value\n\t\tl.Append(ufmt.Sprintf(\"id%d\", i+4))\n\n\t\tif !short {\n\t\t\t// Search for a value\n\t\t\tvar lastFound bool\n\t\t\tl.ForEach(func(j int, v any) bool {\n\t\t\t\tif str, ok := v.(string); ok {\n\t\t\t\t\tif str == ufmt.Sprintf(\"id%d\", i+3) {\n\t\t\t\t\t\tlastFound = true\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t})\n\n\t\t\tif !lastFound {\n\t\t\t\tt.Errorf(\"Failed to find value id%d after insertion\", i+3)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Verify final length\n\texpectedLen := 1003 // 3 initial + 1000 added\n\tif l.Len() != expectedLen {\n\t\tt.Errorf(\"Expected length %d, got %d\", expectedLen, l.Len())\n\t}\n\n\tif short {\n\t\tt.Skip(\"skipping extended recursive safety test in short mode\")\n\t}\n}\n\nfunc TestList_NilValueDistinguishable(t *testing.T) {\n\tvar l List\n\tl.Append(nil)\n\tl.Append(\"hello\")\n\n\t// Stored nil is distinguishable from out-of-bounds.\n\tv, ok := l.Get(0)\n\tif !ok {\n\t\tt.Error(\"Get(0) should return ok=true for stored nil\")\n\t}\n\tif v != nil {\n\t\tt.Errorf(\"Get(0) should return nil value, got %v\", v)\n\t}\n\n\t// Out of bounds returns false.\n\t_, ok = l.Get(5)\n\tif ok {\n\t\tt.Error(\"Get(5) should return ok=false for out of bounds\")\n\t}\n\n\t// Normal value still works.\n\tv, ok = l.Get(1)\n\tif !ok || v != \"hello\" {\n\t\tt.Errorf(\"Get(1) = (%v, %v); want (hello, true)\", v, ok)\n\t}\n}\n\n// Helper function to compare slices\nfunc sliceEqual(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"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"Bbmql4Mp1W3m5U8C6c6xNnRZ0zrD0p9fxumJTjukA9F+NV3lH4UDTkGiYkRmiTJY2aVZNR18/3r+RvpiWtgeJQ=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"pager","path":"gno.land/p/nt/bptree/v0/pager","files":[{"name":"example_test.gno","body":"package pager\n\nimport (\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)\n\nfunc ExamplePager() {\n\t// Create a new tree and populate it with some key-value pairs.\n\tvar id seqid.ID\n\ttree := bptree.NewBPTree32()\n\tfor i := 0; i \u003c 42; i++ {\n\t\ttree.Set(id.Next().String(), i)\n\t}\n\n\t// Create a new pager.\n\tpager1 := NewPager(tree, 7, false)\n\n\tfor pn := -1; pn \u003c 8; pn++ {\n\t\tpage := pager1.GetPage(pn)\n\n\t\tprintln(ufmt.Sprintf(\"## Page %d of %d\", page.PageNumber, page.TotalPages))\n\t\tfor idx, item := range page.Items {\n\t\t\tprintln(ufmt.Sprintf(\"- idx=%d key=%s value=%d\", idx, item.Key, item.Value))\n\t\t}\n\t\tprintln(page.Picker(\"/\"))\n\t\tprintln()\n\t}\n\n\t// Output:\n\t// ## Page 0 of 6\n\t// _0_ | [1](?page=1) | [2](?page=2) | … | [6](?page=6)\n\t//\n\t// ## Page 0 of 6\n\t// _0_ | [1](?page=1) | [2](?page=2) | … | [6](?page=6)\n\t//\n\t// ## Page 1 of 6\n\t// - idx=0 key=0000001 value=0\n\t// - idx=1 key=0000002 value=1\n\t// - idx=2 key=0000003 value=2\n\t// - idx=3 key=0000004 value=3\n\t// - idx=4 key=0000005 value=4\n\t// - idx=5 key=0000006 value=5\n\t// - idx=6 key=0000007 value=6\n\t// **1** | [2](?page=2) | [3](?page=3) | … | [6](?page=6)\n\t//\n\t// ## Page 2 of 6\n\t// - idx=0 key=0000008 value=7\n\t// - idx=1 key=0000009 value=8\n\t// - idx=2 key=000000a value=9\n\t// - idx=3 key=000000b value=10\n\t// - idx=4 key=000000c value=11\n\t// - idx=5 key=000000d value=12\n\t// - idx=6 key=000000e value=13\n\t// [1](?page=1) | **2** | [3](?page=3) | [4](?page=4) | … | [6](?page=6)\n\t//\n\t// ## Page 3 of 6\n\t// - idx=0 key=000000f value=14\n\t// - idx=1 key=000000g value=15\n\t// - idx=2 key=000000h value=16\n\t// - idx=3 key=000000j value=17\n\t// - idx=4 key=000000k value=18\n\t// - idx=5 key=000000m value=19\n\t// - idx=6 key=000000n value=20\n\t// [1](?page=1) | [2](?page=2) | **3** | [4](?page=4) | [5](?page=5) | [6](?page=6)\n\t//\n\t// ## Page 4 of 6\n\t// - idx=0 key=000000p value=21\n\t// - idx=1 key=000000q value=22\n\t// - idx=2 key=000000r value=23\n\t// - idx=3 key=000000s value=24\n\t// - idx=4 key=000000t value=25\n\t// - idx=5 key=000000v value=26\n\t// - idx=6 key=000000w value=27\n\t// [1](?page=1) | [2](?page=2) | [3](?page=3) | **4** | [5](?page=5) | [6](?page=6)\n\t//\n\t// ## Page 5 of 6\n\t// - idx=0 key=000000x value=28\n\t// - idx=1 key=000000y value=29\n\t// - idx=2 key=000000z value=30\n\t// - idx=3 key=0000010 value=31\n\t// - idx=4 key=0000011 value=32\n\t// - idx=5 key=0000012 value=33\n\t// - idx=6 key=0000013 value=34\n\t// [1](?page=1) | … | [3](?page=3) | [4](?page=4) | **5** | [6](?page=6)\n\t//\n\t// ## Page 6 of 6\n\t// - idx=0 key=0000014 value=35\n\t// - idx=1 key=0000015 value=36\n\t// - idx=2 key=0000016 value=37\n\t// - idx=3 key=0000017 value=38\n\t// - idx=4 key=0000018 value=39\n\t// - idx=5 key=0000019 value=40\n\t// - idx=6 key=000001a value=41\n\t// [1](?page=1) | … | [4](?page=4) | [5](?page=5) | **6**\n\t//\n\t// ## Page 7 of 6\n\t// [1](?page=1) | … | [5](?page=5) | [6](?page=6) | _7_\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/bptree/v0/pager\"\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/v0/rotree\"\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"},{"name":"pager_test.gno","body":"package pager\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc TestPager_GetPage(t *testing.T) {\n\t// Create a new B+ tree and populate it with some key-value pairs.\n\ttree := bptree.NewBPTree32()\n\ttree.Set(\"a\", 1)\n\ttree.Set(\"b\", 2)\n\ttree.Set(\"c\", 3)\n\ttree.Set(\"d\", 4)\n\ttree.Set(\"e\", 5)\n\n\tt.Run(\"normal ordering\", func(t *testing.T) {\n\t\t// Create a new pager.\n\t\tpager := NewPager(tree, 10, false)\n\n\t\t// Define test cases.\n\t\ttests := []struct {\n\t\t\tpageNumber int\n\t\t\tpageSize   int\n\t\t\texpected   []Item\n\t\t}{\n\t\t\t{1, 2, []Item{{Key: \"a\", Value: 1}, {Key: \"b\", Value: 2}}},\n\t\t\t{2, 2, []Item{{Key: \"c\", Value: 3}, {Key: \"d\", Value: 4}}},\n\t\t\t{3, 2, []Item{{Key: \"e\", Value: 5}}},\n\t\t\t{1, 3, []Item{{Key: \"a\", Value: 1}, {Key: \"b\", Value: 2}, {Key: \"c\", Value: 3}}},\n\t\t\t{2, 3, []Item{{Key: \"d\", Value: 4}, {Key: \"e\", Value: 5}}},\n\t\t\t{1, 5, []Item{{Key: \"a\", Value: 1}, {Key: \"b\", Value: 2}, {Key: \"c\", Value: 3}, {Key: \"d\", Value: 4}, {Key: \"e\", Value: 5}}},\n\t\t\t{2, 5, []Item{}},\n\t\t}\n\n\t\tfor _, tt := range tests {\n\t\t\tpage := pager.GetPageWithSize(tt.pageNumber, tt.pageSize)\n\n\t\t\tuassert.Equal(t, len(tt.expected), len(page.Items))\n\n\t\t\tfor i, item := range page.Items {\n\t\t\t\tuassert.Equal(t, tt.expected[i].Key, item.Key)\n\t\t\t\tuassert.Equal(t, tt.expected[i].Value, item.Value)\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"reversed ordering\", func(t *testing.T) {\n\t\t// Create a new pager.\n\t\tpager := NewPager(tree, 10, true)\n\n\t\t// Define test cases.\n\t\ttests := []struct {\n\t\t\tpageNumber int\n\t\t\tpageSize   int\n\t\t\texpected   []Item\n\t\t}{\n\t\t\t{1, 2, []Item{{Key: \"e\", Value: 5}, {Key: \"d\", Value: 4}}},\n\t\t\t{2, 2, []Item{{Key: \"c\", Value: 3}, {Key: \"b\", Value: 2}}},\n\t\t\t{3, 2, []Item{{Key: \"a\", Value: 1}}},\n\t\t\t{1, 3, []Item{{Key: \"e\", Value: 5}, {Key: \"d\", Value: 4}, {Key: \"c\", Value: 3}}},\n\t\t\t{2, 3, []Item{{Key: \"b\", Value: 2}, {Key: \"a\", Value: 1}}},\n\t\t\t{1, 5, []Item{{Key: \"e\", Value: 5}, {Key: \"d\", Value: 4}, {Key: \"c\", Value: 3}, {Key: \"b\", Value: 2}, {Key: \"a\", Value: 1}}},\n\t\t\t{2, 5, []Item{}},\n\t\t}\n\n\t\tfor _, tt := range tests {\n\t\t\tpage := pager.GetPageWithSize(tt.pageNumber, tt.pageSize)\n\n\t\t\tuassert.Equal(t, len(tt.expected), len(page.Items))\n\n\t\t\tfor i, item := range page.Items {\n\t\t\t\tuassert.Equal(t, tt.expected[i].Key, item.Key)\n\t\t\t\tuassert.Equal(t, tt.expected[i].Value, item.Value)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestPager_GetPageByPath(t *testing.T) {\n\t// Create a new B+ tree and populate it with some key-value pairs.\n\ttree := bptree.NewBPTree32()\n\tfor i := 0; i \u003c 50; i++ {\n\t\ttree.Set(ufmt.Sprintf(\"key%d\", i), i)\n\t}\n\n\t// Create a new pager.\n\tpager := NewPager(tree, 10, false)\n\n\t// Define test cases.\n\ttests := []struct {\n\t\trawURL       string\n\t\texpectedPage int\n\t\texpectedSize int\n\t}{\n\t\t{\"/r/foo:bar/baz?size=10\u0026page=1\", 1, 10},\n\t\t{\"/r/foo:bar/baz?size=10\u0026page=2\", 2, 10},\n\t\t{\"/r/foo:bar/baz?page=3\", 3, pager.DefaultPageSize},\n\t\t{\"/r/foo:bar/baz?size=20\", 1, 20},\n\t\t{\"/r/foo:bar/baz\", 1, pager.DefaultPageSize},\n\t}\n\n\tfor _, tt := range tests {\n\t\tpage, err := pager.GetPageByPath(tt.rawURL)\n\t\turequire.NoError(t, err, ufmt.Sprintf(\"GetPageByPath(%s) returned error: %v\", tt.rawURL, err))\n\n\t\tuassert.Equal(t, tt.expectedPage, page.PageNumber)\n\t\tuassert.Equal(t, tt.expectedSize, page.PageSize)\n\t}\n}\n\nfunc TestPage_Picker(t *testing.T) {\n\t// Create a new B+ tree and populate it with some key-value pairs.\n\ttree := bptree.NewBPTree32()\n\ttree.Set(\"a\", 1)\n\ttree.Set(\"b\", 2)\n\ttree.Set(\"c\", 3)\n\ttree.Set(\"d\", 4)\n\ttree.Set(\"e\", 5)\n\n\t// Create a new pager.\n\tpager := NewPager(tree, 10, false)\n\n\t// Define test cases.\n\ttests := []struct {\n\t\tpageNumber int\n\t\tpageSize   int\n\t\tpath       string\n\t\texpected   string\n\t}{\n\t\t{1, 2, \"/test\", \"**1** | [2](?page=2) | [3](?page=3)\"},\n\t\t{2, 2, \"/test\", \"[1](?page=1) | **2** | [3](?page=3)\"},\n\t\t{3, 2, \"/test\", \"[1](?page=1) | [2](?page=2) | **3**\"},\n\t\t{1, 2, \"/test?foo=bar\", \"**1** | [2](?page=2\u0026foo=bar) | [3](?page=3\u0026foo=bar)\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tpage := pager.GetPageWithSize(tt.pageNumber, tt.pageSize)\n\n\t\tui := page.Picker(tt.path)\n\t\tuassert.Equal(t, tt.expected, ui)\n\t}\n}\n\nfunc TestPager_UI_WithManyPages(t *testing.T) {\n\t// Create a new B+ tree and populate it with many key-value pairs.\n\ttree := bptree.NewBPTree32()\n\tfor i := 0; i \u003c 100; i++ {\n\t\ttree.Set(ufmt.Sprintf(\"key%d\", i), i)\n\t}\n\n\t// Create a new pager.\n\tpager := NewPager(tree, 10, false)\n\n\t// Define test cases for a large number of pages.\n\ttests := []struct {\n\t\tpageNumber int\n\t\tpageSize   int\n\t\tpath       string\n\t\texpected   string\n\t}{\n\t\t{1, 10, \"/test\", \"**1** | [2](?page=2) | [3](?page=3) | … | [10](?page=10)\"},\n\t\t{2, 10, \"/test\", \"[1](?page=1) | **2** | [3](?page=3) | [4](?page=4) | … | [10](?page=10)\"},\n\t\t{3, 10, \"/test\", \"[1](?page=1) | [2](?page=2) | **3** | [4](?page=4) | [5](?page=5) | … | [10](?page=10)\"},\n\t\t{4, 10, \"/test\", \"[1](?page=1) | [2](?page=2) | [3](?page=3) | **4** | [5](?page=5) | [6](?page=6) | … | [10](?page=10)\"},\n\t\t{5, 10, \"/test\", \"[1](?page=1) | … | [3](?page=3) | [4](?page=4) | **5** | [6](?page=6) | [7](?page=7) | … | [10](?page=10)\"},\n\t\t{6, 10, \"/test\", \"[1](?page=1) | … | [4](?page=4) | [5](?page=5) | **6** | [7](?page=7) | [8](?page=8) | … | [10](?page=10)\"},\n\t\t{7, 10, \"/test\", \"[1](?page=1) | … | [5](?page=5) | [6](?page=6) | **7** | [8](?page=8) | [9](?page=9) | [10](?page=10)\"},\n\t\t{8, 10, \"/test\", \"[1](?page=1) | … | [6](?page=6) | [7](?page=7) | **8** | [9](?page=9) | [10](?page=10)\"},\n\t\t{9, 10, \"/test\", \"[1](?page=1) | … | [7](?page=7) | [8](?page=8) | **9** | [10](?page=10)\"},\n\t\t{10, 10, \"/test\", \"[1](?page=1) | … | [8](?page=8) | [9](?page=9) | **10**\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tpage := pager.GetPageWithSize(tt.pageNumber, tt.pageSize)\n\n\t\tui := page.Picker(tt.path)\n\t\tuassert.Equal(t, tt.expected, ui)\n\t}\n}\n\nfunc TestPager_ParseQuery(t *testing.T) {\n\t// Create a new B+ tree and populate it with some key-value pairs.\n\ttree := bptree.NewBPTree32()\n\ttree.Set(\"a\", 1)\n\ttree.Set(\"b\", 2)\n\ttree.Set(\"c\", 3)\n\ttree.Set(\"d\", 4)\n\ttree.Set(\"e\", 5)\n\n\t// Create a new pager.\n\tpager := NewPager(tree, 10, false)\n\n\t// Define test cases.\n\ttests := []struct {\n\t\trawURL        string\n\t\texpectedPage  int\n\t\texpectedSize  int\n\t\texpectedError bool\n\t}{\n\t\t{\"/r/foo:bar/baz?size=2\u0026page=1\", 1, 2, false},\n\t\t{\"/r/foo:bar/baz?size=3\u0026page=2\", 2, 3, false},\n\t\t{\"/r/foo:bar/baz?size=5\u0026page=3\", 3, 5, false},\n\t\t{\"/r/foo:bar/baz?page=2\", 2, pager.DefaultPageSize, false},\n\t\t{\"/r/foo:bar/baz?size=3\", 1, 3, false},\n\t\t{\"/r/foo:bar/baz\", 1, pager.DefaultPageSize, false},\n\t\t{\"/r/foo:bar/baz?size=0\u0026page=0\", 1, pager.DefaultPageSize, false},\n\t}\n\n\tfor _, tt := range tests {\n\t\tpage, size, err := pager.ParseQuery(tt.rawURL)\n\t\tif tt.expectedError {\n\t\t\tuassert.Error(t, err, ufmt.Sprintf(\"ParseQuery(%s) expected error but got none\", tt.rawURL))\n\t\t} else {\n\t\t\turequire.NoError(t, err, ufmt.Sprintf(\"ParseQuery(%s) returned error: %v\", tt.rawURL, err))\n\t\t\tuassert.Equal(t, tt.expectedPage, page, ufmt.Sprintf(\"ParseQuery(%s) returned page %d, expected %d\", tt.rawURL, page, tt.expectedPage))\n\t\t\tuassert.Equal(t, tt.expectedSize, size, ufmt.Sprintf(\"ParseQuery(%s) returned size %d, expected %d\", tt.rawURL, size, tt.expectedSize))\n\t\t}\n\t}\n}\n\nfunc TestPage_PickerQueryParamPreservation(t *testing.T) {\n\ttree := bptree.NewBPTree32()\n\tfor i := 1; i \u003c= 6; i++ {\n\t\ttree.Set(ufmt.Sprintf(\"key%d\", i), i)\n\t}\n\n\tpager := NewPager(tree, 2, false)\n\n\ttests := []struct {\n\t\tname       string\n\t\tpageNumber int\n\t\tpath       string\n\t\texpected   string\n\t}{\n\t\t{\n\t\t\tname:       \"single query param\",\n\t\t\tpageNumber: 1,\n\t\t\tpath:       \"/test?foo=bar\",\n\t\t\texpected:   \"**1** | [2](?page=2\u0026foo=bar) | [3](?page=3\u0026foo=bar)\",\n\t\t},\n\t\t{\n\t\t\tname:       \"multiple query params\",\n\t\t\tpageNumber: 2,\n\t\t\tpath:       \"/test?foo=bar\u0026baz=qux\",\n\t\t\texpected:   \"[1](?page=1\u0026baz=qux\u0026foo=bar) | **2** | [3](?page=3\u0026baz=qux\u0026foo=bar)\",\n\t\t},\n\t\t{\n\t\t\tname:       \"overwrite existing page param\",\n\t\t\tpageNumber: 1,\n\t\t\tpath:       \"/test?param1=value1\u0026page=999\u0026param2=value2\",\n\t\t\texpected:   \"**1** | [2](?page=2\u0026param1=value1\u0026param2=value2) | [3](?page=3\u0026param1=value1\u0026param2=value2)\",\n\t\t},\n\t\t{\n\t\t\tname:       \"empty query string\",\n\t\t\tpageNumber: 2,\n\t\t\tpath:       \"/test\",\n\t\t\texpected:   \"[1](?page=1) | **2** | [3](?page=3)\",\n\t\t},\n\t\t{\n\t\t\tname:       \"query string with only page param\",\n\t\t\tpageNumber: 2,\n\t\t\tpath:       \"/test?page=2\",\n\t\t\texpected:   \"[1](?page=1) | **2** | [3](?page=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\tpage := pager.GetPageWithSize(tt.pageNumber, 2)\n\t\t\tresult := page.Picker(tt.path)\n\t\t\tif result != tt.expected {\n\t\t\t\tt.Errorf(\"\\nwant: %s\\ngot:  %s\", tt.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"6EY58KD9z6wwlRl/NwQOTYNzJBw+1HjURne2COOcsAM1du8yqEY0lXBcwJIjMecP2CVS9kRoPZ+ThCCeCqfEjA=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g15ge0ae9077eh40erwrn2eq0xw6wupwqthpv34l","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":"bylaws_test.gno","body":"package bylaws\n\nimport (\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 TestIsValidPath(t *testing.T) {\n\tvalid := []string{\n\t\t\"bylaws.md\",\n\t\t\"bylaws/quorum.md\",\n\t\t\"mandates/treasury/spend-policy.txt\",\n\t\t\"a\",\n\t\t\"A-b_c.d/e\",\n\t}\n\tfor _, p := range valid {\n\t\tuassert.True(t, IsValidPath(p), \"expect valid: \"+p)\n\t}\n\n\tinvalid := []string{\n\t\t\"\",\n\t\t\"/bylaws.md\",\n\t\t\"bylaws.md/\",\n\t\t\"bylaws//quorum.md\",\n\t\t\"bylaws/./quorum.md\",\n\t\t\"bylaws/../quorum.md\",\n\t\t\".\",\n\t\t\"..\",\n\t\t\"bylaws quorum.md\", // space\n\t\t\"bylaws:quorum\",    // encoding delimiter\n\t\t\"bylaws;quorum\",\n\t\t\"byläws.md\", // non-ASCII\n\t\t\"a\\nb\",\n\t\tstrings.Repeat(\"a\", MaxPathLen+1),\n\t}\n\tfor _, p := range invalid {\n\t\tuassert.False(t, IsValidPath(p), \"expect invalid: \"+p)\n\t}\n}\n\nfunc TestStoreReads(t *testing.T) {\n\tb := New()\n\n\t// Empty set.\n\tuassert.Equal(t, 0, b.Size())\n\tuassert.False(t, b.Has(\"bylaws/a.md\"))\n\t_, ok := b.Get(\"bylaws/a.md\")\n\tuassert.False(t, ok)\n\tuassert.Equal(t, \"\", b.Hash(\"bylaws/a.md\"))\n\tuassert.Equal(t, 0, len(b.List(\"\")))\n\n\t// Documents enter only through Apply.\n\tmustCreate(t, b, \"bylaws/quorum.md\", \"Quorum is half.\")\n\tmustCreate(t, b, \"bylaws/voting.md\", \"One member one vote.\")\n\tmustCreate(t, b, \"mandates/treasury.md\", \"Spend only by vote.\")\n\n\tuassert.Equal(t, 3, b.Size())\n\ttext, ok := b.Get(\"bylaws/quorum.md\")\n\turequire.True(t, ok, \"expect document\")\n\tuassert.Equal(t, \"Quorum is half.\", text)\n\tuassert.Equal(t, HashText(\"Quorum is half.\"), b.Hash(\"bylaws/quorum.md\"))\n\n\t// List is sorted; a prefix scopes to a folder.\n\tall := b.List(\"\")\n\turequire.Equal(t, 3, len(all))\n\tuassert.Equal(t, \"bylaws/quorum.md\", all[0])\n\tuassert.Equal(t, \"bylaws/voting.md\", all[1])\n\tuassert.Equal(t, \"mandates/treasury.md\", all[2])\n\n\tfolder := b.List(\"bylaws/\")\n\turequire.Equal(t, 2, len(folder))\n\tuassert.Equal(t, \"bylaws/quorum.md\", folder[0])\n\tuassert.Equal(t, \"bylaws/voting.md\", folder[1])\n\n\t// The prefix is raw: without the trailing slash it also matches a\n\t// sibling file sharing the prefix (documented List behavior).\n\tmustCreate(t, b, \"mandates-old.md\", \"Superseded.\")\n\traw := b.List(\"mandates\")\n\turequire.Equal(t, 2, len(raw))\n\tuassert.Equal(t, \"mandates-old.md\", raw[0])\n\tuassert.Equal(t, \"mandates/treasury.md\", raw[1])\n\tuassert.Equal(t, 1, len(b.List(\"mandates/\")))\n\n\t// Iterate stops when fn returns true.\n\tcount := 0\n\tstopped := b.Iterate(\"\", func(path, text string) bool {\n\t\tcount++\n\t\treturn true\n\t})\n\tuassert.True(t, stopped, \"expect stopped iteration\")\n\tuassert.Equal(t, 1, count)\n}\n\nfunc TestHashText(t *testing.T) {\n\t// sha256(\"\") — the fixed empty-text digest; documents are never stored\n\t// empty, so the \"\" base sentinel (absent) can never collide with it.\n\tuassert.Equal(t,\n\t\t\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\",\n\t\tHashText(\"\"))\n\tuassert.NotEqual(t, HashText(\"a\"), HashText(\"b\"))\n}\n\n// mustCreate applies a create patch for a new document.\nfunc mustCreate(t *testing.T, b *Bylaws, path, text string) {\n\tt.Helper()\n\n\tp, err := b.Diff(path, text)\n\turequire.NoError(t, err)\n\turequire.NoError(t, b.Apply(p))\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\"\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"},{"name":"patch_test.gno","body":"package bylaws\n\nimport (\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 TestDiffApplyLifecycle(t *testing.T) {\n\tb := New()\n\n\t// Create: diff against an absent document is a create patch.\n\tcreate, err := b.Diff(\"bylaws/quorum.md\", \"Quorum is half the council.\")\n\turequire.NoError(t, err)\n\tuassert.True(t, create.IsCreate(), \"expect create patch\")\n\tuassert.False(t, create.IsNoop())\n\turequire.NoError(t, b.Apply(create))\n\ttext, _ := b.Get(\"bylaws/quorum.md\")\n\tuassert.Equal(t, \"Quorum is half the council.\", text)\n\n\t// Amend: a small edit patches to the new text and re-pins the hash.\n\tamend, err := b.Diff(\"bylaws/quorum.md\", \"Quorum is two thirds of the council.\")\n\turequire.NoError(t, err)\n\tuassert.False(t, amend.IsCreate())\n\tuassert.Equal(t, HashText(\"Quorum is half the council.\"), amend.Base)\n\turequire.NoError(t, b.Apply(amend))\n\ttext, _ = b.Get(\"bylaws/quorum.md\")\n\tuassert.Equal(t, \"Quorum is two thirds of the council.\", text)\n\n\t// Remove: empty proposed text deletes the document.\n\tremove, err := b.Diff(\"bylaws/quorum.md\", \"\")\n\turequire.NoError(t, err)\n\tuassert.True(t, remove.IsRemove(), \"expect remove patch\")\n\turequire.NoError(t, b.Apply(remove))\n\tuassert.False(t, b.Has(\"bylaws/quorum.md\"))\n\tuassert.Equal(t, 0, b.Size())\n}\n\nfunc TestApplyStale(t *testing.T) {\n\tb := New()\n\tmustCreate(t, b, \"a.md\", \"one\")\n\n\t// Both patches diff against \"one\"; the first to apply wins.\n\tp1, err := b.Diff(\"a.md\", \"two\")\n\turequire.NoError(t, err)\n\tp2, err := b.Diff(\"a.md\", \"three\")\n\turequire.NoError(t, err)\n\n\turequire.NoError(t, b.Apply(p1))\n\tuassert.ErrorIs(t, b.Apply(p2), ErrStalePatch)\n\ttext, _ := b.Get(\"a.md\")\n\tuassert.Equal(t, \"two\", text) // loser did not clobber\n\n\t// A create patch against a now-existing document is stale too.\n\tcreate, err := DiffTexts(\"a.md\", \"\", \"fresh\", false)\n\turequire.NoError(t, err)\n\tuassert.ErrorIs(t, b.Apply(create), ErrStalePatch)\n\n\t// A patch pinning sha256(\"\") is NOT a create: documents are never\n\t// stored empty, so it can never match anything.\n\tnotCreate := Patch{Path: \"b.md\", Base: HashText(\"\"), Ops: []Op{{Type: OpInsert, Text: \"x\"}}}\n\tuassert.ErrorIs(t, b.Apply(notCreate), ErrStalePatch)\n}\n\nfunc TestApplyRejectsBadScripts(t *testing.T) {\n\tb := New()\n\tmustCreate(t, b, \"a.md\", \"abcdef\")\n\tbase := b.Hash(\"a.md\")\n\n\tcases := []struct {\n\t\tname string\n\t\tops  []Op\n\t}{\n\t\t{\"keep overruns the base\", []Op{{Type: OpKeep, N: 7}}},\n\t\t{\"delete overruns the base\", []Op{{Type: OpDelete, N: 7}}},\n\t\t{\"script underconsumes the base\", []Op{{Type: OpKeep, N: 3}}},\n\t\t{\"zero keep\", []Op{{Type: OpKeep, N: 0}, {Type: OpKeep, N: 6}}},\n\t\t{\"negative delete\", []Op{{Type: OpDelete, N: -1}, {Type: OpKeep, N: 6}}},\n\t\t{\"empty insert\", []Op{{Type: OpKeep, N: 6}, {Type: OpInsert}}},\n\t\t{\"unknown op\", []Op{{Type: OpType('X'), N: 6}}},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\terr := b.Apply(Patch{Path: \"a.md\", Base: base, Ops: tc.ops})\n\t\t\tuassert.ErrorIs(t, err, ErrInvalidPatch)\n\t\t\ttext, _ := b.Get(\"a.md\")\n\t\t\tuassert.Equal(t, \"abcdef\", text) // unchanged on error\n\t\t})\n\t}\n\n\t// Path and size guards.\n\tuassert.ErrorIs(t, b.Apply(Patch{Path: \"bad path\"}), ErrInvalidPath)\n\tgrow := Patch{Path: \"a.md\", Base: base, Ops: []Op{\n\t\t{Type: OpDelete, N: 6},\n\t\t{Type: OpInsert, Text: strings.Repeat(\"x\", MaxDocLen+1)},\n\t}}\n\tuassert.ErrorIs(t, b.Apply(grow), ErrDocTooLarge)\n\n\t_, err := DiffTexts(\"a.md\", \"\", strings.Repeat(\"x\", MaxDocLen+1), false)\n\tuassert.ErrorIs(t, err, ErrDocTooLarge)\n}\n\nfunc TestApplyUnicode(t *testing.T) {\n\tb := New()\n\tmustCreate(t, b, \"a.md\", \"héllo wörld ✓\")\n\n\t// Ops count runes, not bytes: a diff over multi-byte text replays\n\t// exactly.\n\tp, err := b.Diff(\"a.md\", \"héllo brave wörld ✓✓\")\n\turequire.NoError(t, err)\n\turequire.NoError(t, b.Apply(p))\n\ttext, _ := b.Get(\"a.md\")\n\tuassert.Equal(t, \"héllo brave wörld ✓✓\", text)\n}\n\nfunc TestEncodeDecodeRoundTrip(t *testing.T) {\n\tb := New()\n\tmustCreate(t, b, \"bylaws/quorum.md\", \"Quorum is half the council.\\nVotes are public.\")\n\n\tpatches := []Patch{}\n\tp1, err := b.Diff(\"bylaws/quorum.md\", \"Quorum is two thirds.\\nVotes are public.\")\n\turequire.NoError(t, err)\n\tpatches = append(patches, p1)\n\tp2, err := DiffTexts(\"new/doc.md\", \"\", \"Created; with punct: [x] (y) \\\"z\\\"\\nand a second line.\", false)\n\turequire.NoError(t, err)\n\tpatches = append(patches, p2)\n\tp3, err := b.Diff(\"bylaws/quorum.md\", \"\") // remove\n\turequire.NoError(t, err)\n\tpatches = append(patches, p3)\n\n\tfor _, p := range patches {\n\t\tenc := p.Encode()\n\t\tdec, err := DecodePatch(enc)\n\t\turequire.NoError(t, err)\n\t\tuassert.Equal(t, p.Path, dec.Path)\n\t\tuassert.Equal(t, p.Base, dec.Base)\n\t\turequire.Equal(t, len(p.Ops), len(dec.Ops))\n\t\tfor i := range p.Ops {\n\t\t\tuassert.True(t, p.Ops[i].Type == dec.Ops[i].Type, \"op type\")\n\t\t\tuassert.Equal(t, p.Ops[i].N, dec.Ops[i].N)\n\t\t\tuassert.Equal(t, p.Ops[i].Text, dec.Ops[i].Text)\n\t\t}\n\t\t// Deterministic: encoding is stable.\n\t\tuassert.Equal(t, enc, dec.Encode())\n\t}\n\n\t// The decoded patch applies like the original.\n\tdec, err := DecodePatch(p1.Encode())\n\turequire.NoError(t, err)\n\turequire.NoError(t, b.Apply(dec))\n\ttext, _ := b.Get(\"bylaws/quorum.md\")\n\tuassert.Equal(t, \"Quorum is two thirds.\\nVotes are public.\", text)\n}\n\nfunc TestDecodePatchRejectsMalformed(t *testing.T) {\n\tvalid, err := DiffTexts(\"a.md\", \"\", \"hello\", false)\n\turequire.NoError(t, err)\n\tenc := valid.Encode()\n\tuassert.Equal(t, \"v0:a.md::I5:hello;\", enc) // pin the wire format\n\n\tbad := []string{\n\t\t\"\",\n\t\t\"v1:a.md::I5:hello;\",           // unknown version\n\t\t\"v0:bad path::I5:hello;\",       // invalid path\n\t\t\"v0:a.md:zz:I5:hello;\",         // malformed base\n\t\t\"v0:a.md::X5:hello;\",           // unknown op\n\t\t\"v0:a.md::I5:hell\",             // truncated literal\n\t\t\"v0:a.md::I5:helloX\",           // missing op terminator\n\t\t\"v0:a.md::K0;\",                 // zero count\n\t\t\"v0:a.md::K-1;\",                // negative count\n\t\t\"v0:a.md::Kx;\",                 // non-numeric count\n\t\t\"v0:a.md::K05;\",                // non-canonical count (leading zero)\n\t\t\"v0:a.md::K+5;\",                // non-canonical count (sign)\n\t\t\"v0:a.md::I+5:hello;\",          // non-canonical insert length\n\t\t\"v0:a.md::K1\",                  // missing terminator\n\t\t\"v0:a.md::I0:;\",                // empty insert\n\t\t\"v0:a.md\",                      // missing base separator\n\t\t\"v0:a.md::K99999999999999999;\", // over MaxDocLen\n\t\t\"v0:a.md::I1:\\xc3;\",            // insert is not valid UTF-8\n\t}\n\tfor _, s := range bad {\n\t\t_, err := DecodePatch(s)\n\t\tuassert.Error(t, err, \"expect decode error: \"+s)\n\t}\n}\n\nfunc TestDecodePatchMaxOps(t *testing.T) {\n\t// Exactly MaxOps ops decode; one more is rejected. (Shape-only: the\n\t// script need not fit any document to decode.)\n\tpayload := \"v0:a.md::\" + strings.Repeat(\"K1;\", MaxOps)\n\t_, err := DecodePatch(payload)\n\tuassert.NoError(t, err)\n\n\t_, err = DecodePatch(payload + \"K1;\")\n\tuassert.ErrorIs(t, err, ErrInvalidPatch)\n}\n\nfunc TestEncodeDecodeMultibyteInsert(t *testing.T) {\n\t// The insert length prefix is a BYTE length: pin the exact wire form\n\t// for a multi-byte literal so a rune-length regression cannot pass.\n\tp, err := DiffTexts(\"a.md\", \"\", \"héllo ✓ wörld\", false)\n\turequire.NoError(t, err)\n\tenc := p.Encode()\n\tuassert.Equal(t, \"v0:a.md::I17:héllo ✓ wörld;\", enc)\n\n\tdec, err := DecodePatch(enc)\n\turequire.NoError(t, err)\n\tb := New()\n\turequire.NoError(t, b.Apply(dec))\n\ttext, _ := b.Get(\"a.md\")\n\tuassert.Equal(t, \"héllo ✓ wörld\", text)\n}\n\nfunc TestDiffTextsRejectsInvalidUTF8(t *testing.T) {\n\t_, err := DiffTexts(\"a.md\", \"\", \"bad \\xc3 byte\", false)\n\tuassert.ErrorIs(t, err, ErrInvalidText)\n\n\t_, err = DiffTexts(\"a.md\", \"bad \\xc3 base\", \"fine\", true)\n\tuassert.ErrorIs(t, err, ErrInvalidText)\n}\n\nfunc TestFormat(t *testing.T) {\n\tb := New()\n\tmustCreate(t, b, \"a.md\", \"keep DELETE keep\")\n\n\tp, err := b.Diff(\"a.md\", \"keep INSERT keep\")\n\turequire.NoError(t, err)\n\tout, err := p.Format(\"keep DELETE keep\")\n\turequire.NoError(t, err)\n\tuassert.True(t, strings.Contains(out, \"unchanged\"), \"expect kept marker\")\n\n\t// The formatted change shows what leaves and what enters.\n\tuassert.True(t, strings.Contains(out, \"-\"), \"expect deletion marker\")\n\tuassert.True(t, strings.Contains(out, \"+\"), \"expect insertion marker\")\n\n\t// Format fails like replay on a script that does not fit the base by\n\t// rune count. (Fit is positional — content verification is the base\n\t// hash's job, checked by Apply, not Format.)\n\t_, err = p.Format(\"short\")\n\tuassert.ErrorIs(t, err, ErrInvalidPatch)\n}\n\nfunc TestDiffPrefixSuffixTrim(t *testing.T) {\n\tb := New()\n\tmustCreate(t, b, \"a.md\", \"The quick brown fox jumps over the lazy dog.\")\n\n\t// A small middle edit yields Keep(prefix), the middle change, and\n\t// Keep(suffix): the payload carries only the changed region.\n\tp, err := b.Diff(\"a.md\", \"The quick red fox jumps over the lazy dog.\")\n\turequire.NoError(t, err)\n\turequire.True(t, len(p.Ops) \u003e= 3, \"expect trimmed script\")\n\tuassert.True(t, p.Ops[0].Type == OpKeep, \"expect leading keep\")\n\tuassert.True(t, p.Ops[len(p.Ops)-1].Type == OpKeep, \"expect trailing keep\")\n\turequire.NoError(t, b.Apply(p))\n\ttext, _ := b.Get(\"a.md\")\n\tuassert.Equal(t, \"The quick red fox jumps over the lazy dog.\", text)\n}\n\nfunc TestDiffLargeRewriteFallsBackToReplace(t *testing.T) {\n\t// Two texts with a shared prefix/suffix but a differing middle beyond\n\t// the Myers budget: Diff must fall back to a whole-middle replace\n\t// (bounded ops, no quadratic diff) that still replays exactly.\n\tbase := \"HEAD\\n\" + strings.Repeat(\"ab\", 600) + \"\\nTAIL\"\n\tproposed := \"HEAD\\n\" + strings.Repeat(\"cd\", 600) + \"\\nTAIL\"\n\n\tp, err := DiffTexts(\"big.md\", base, proposed, true)\n\turequire.NoError(t, err)\n\turequire.True(t, len(p.Ops) \u003c= 4, \"expect fallback replace, got ops count\")\n\n\tb := New()\n\tcreate, err := b.Diff(\"big.md\", base)\n\turequire.NoError(t, err)\n\turequire.NoError(t, b.Apply(create))\n\turequire.NoError(t, b.Apply(p))\n\ttext, _ := b.Get(\"big.md\")\n\tuassert.Equal(t, proposed, text)\n}\n\nfunc TestFormatMarkerSpoof(t *testing.T) {\n\t// A multi-line insert literal gets every line marker-prefixed, so an\n\t// embedded \"- fake\" line cannot masquerade as a deletion marker.\n\tp, err := DiffTexts(\"a.md\", \"\", \"x\\n- fake deletion\", false)\n\turequire.NoError(t, err)\n\tout, err := p.Format(\"\")\n\turequire.NoError(t, err)\n\tuassert.True(t, strings.Contains(out, \"+ x\\n+ - fake deletion\\n\"), \"expect per-line insert markers\")\n\tuassert.False(t, strings.Contains(out, \"\\n- fake deletion\"), \"expect no bare deletion-marker line\")\n}\n\nfunc TestNoopPatch(t *testing.T) {\n\tb := New()\n\tmustCreate(t, b, \"a.md\", \"same\")\n\n\tp, err := b.Diff(\"a.md\", \"same\")\n\turequire.NoError(t, err)\n\tuassert.True(t, p.IsNoop(), \"expect noop patch\")\n\turequire.NoError(t, b.Apply(p)) // harmless\n\ttext, _ := b.Get(\"a.md\")\n\tuassert.Equal(t, \"same\", text)\n\n\t// Creating an empty document is a noop create: nothing is stored.\n\tpc, err := DiffTexts(\"empty.md\", \"\", \"\", false)\n\turequire.NoError(t, err)\n\tuassert.True(t, pc.IsNoop(), \"expect noop create\")\n\turequire.NoError(t, b.Apply(pc))\n\tuassert.False(t, b.Has(\"empty.md\"))\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"IQ6+ucgxCROt+xyUVIhpsbgDYEKMXjNkJhP1JqPtGHkMgEUfLwGRDScJXjqUop20c/PZBBMyPWdSRR86L/o6uw=="}],"memo":""}},{"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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"DINcI9/y19PZm+83868vuEyrU4SM9euZzGlItUt0mKEzxFkEQdKB9e+VQSIm1dNcafIanrbotN7m05joDtN3JA=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g15ge0ae9077eh40erwrn2eq0xw6wupwqthpv34l","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/v0\"\n\t\"gno.land/p/nt/bptree/v0/list\"\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":"commondao_test.gno","body":"package commondao_test\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n\n\t\"gno.land/p/nt/commondao/v0\"\n)\n\nconst (\n\tmemberA address = \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"\n\tmemberB address = \"g1w4ek2u33ta047h6lta047h6lta047h6ldvdwpn\"\n\tmemberC address = \"g1w4ek2u3jta047h6lta047h6lta047h6l9huexc\"\n\tmemberD address = \"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\"\n\tmemberE address = \"g1yx35a8f4lhhhrarljrgr37u55gkqdrl0949ycf\"\n\tmemberF address = \"g1cyh9qm4y43w38gfk77qxczrhqj2asdr8l7uk54\"\n\tmemberG address = \"g1x95kxqpwvqjf98qpkvsay7tppkh6zs9fr7wwda\"\n\tmemberH address = \"g12m7ryva2vsw3twqdtuc9awufwzwtk5al4v4ksd\"\n\tmemberI address = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n)\n\n// probeKind is a pass-through proposal kind for tests: args is the\n// proposal definition itself.\ntype probeKind struct{}\n\nfunc (probeKind) Name() string { return \"probe\" }\nfunc (probeKind) New(_ commondao.ReadonlyCommonDAO, args any) (commondao.ProposalDefinition, error) {\n\td, _ := args.(commondao.ProposalDefinition)\n\treturn d, nil\n}\n\n// namedKind is a probe kind with a configurable name.\ntype namedKind string\n\nfunc (k namedKind) Name() string { return string(k) }\nfunc (namedKind) New(_ commondao.ReadonlyCommonDAO, _ any) (commondao.ProposalDefinition, error) {\n\treturn propDef{period: time.Hour}, nil\n}\n\n// failingKind is a probe kind whose factory always fails.\ntype failingKind struct{ err error }\n\nfunc (failingKind) Name() string { return \"failing\" }\nfunc (k failingKind) New(_ commondao.ReadonlyCommonDAO, _ any) (commondao.ProposalDefinition, error) {\n\treturn nil, k.err\n}\n\n// hostKind is a probe kind that records the ID of the readonly host view\n// passed to its factory. New receives only a ReadonlyCommonDAO (no mutable\n// handle), so the kind can identify the host but cannot mutate it.\ntype hostKind struct{ hostID *uint64 }\n\nfunc (hostKind) Name() string { return \"host\" }\nfunc (k hostKind) New(dao commondao.ReadonlyCommonDAO, _ any) (commondao.ProposalDefinition, error) {\n\t*k.hostID = dao.ID()\n\treturn propDef{period: time.Hour}, nil\n}\n\n// reProposeKind.New re-enters Propose on the captured DAO. Only a trusted\n// kind holding the handle can attempt this (external kinds get a readonly\n// view); the proposing latch must panic before the nested Propose runs.\ntype reProposeKind struct{ dao *commondao.CommonDAO }\n\nfunc (reProposeKind) Name() string { return \"re-propose\" }\nfunc (k reProposeKind) New(_ commondao.ReadonlyCommonDAO, _ any) (commondao.ProposalDefinition, error) {\n\t// \"probe\" is registered, so this reaches the proposing latch (not the\n\t// kind-lookup) and panics.\n\tk.dao.Propose(memberA, \"probe\", defaultPropDef{period: time.Hour})\n\treturn defaultPropDef{period: time.Hour}, nil\n}\n\n// propDef is a base proposal definition decided by the default rules.\ntype propDef struct {\n\ttitle  string\n\tbody   string\n\tperiod time.Duration\n}\n\nfunc (d propDef) Title() string               { return d.title }\nfunc (d propDef) Body() string                { return d.body }\nfunc (d propDef) VotingPeriod() time.Duration { return d.period }\nfunc (propDef) Threshold() commondao.Threshold {\n\treturn commondao.ThresholdSupermajority\n}\n\n// mustPropose creates a proposal through the probe kind or fails the test.\nfunc mustPropose(t *testing.T, dao *commondao.CommonDAO, creator address, d commondao.ProposalDefinition) *commondao.Proposal {\n\tt.Helper()\n\tp, err := dao.Propose(creator, \"probe\", d)\n\turequire.NoError(t, err, \"propose\")\n\treturn p\n}\n\n// defaultPropDef is decided by the constitution's default rules.\ntype defaultPropDef struct {\n\tperiod    time.Duration\n\tthreshold commondao.Threshold\n\texecuted  *bool\n\texecErr   error\n}\n\nfunc (defaultPropDef) Title() string                 { return \"Default\" }\nfunc (defaultPropDef) Body() string                  { return \"\" }\nfunc (d defaultPropDef) VotingPeriod() time.Duration { return d.period }\nfunc (d defaultPropDef) Threshold() commondao.Threshold {\n\treturn d.threshold\n}\n\nfunc (d defaultPropDef) Executor() commondao.ExecFunc {\n\treturn func(_ int, sub realm) error {\n\t\tif d.executed != nil {\n\t\t\t*d.executed = true\n\t\t}\n\t\treturn d.execErr\n\t}\n}\n\n// exemptPropDef is exempt from the active proposals cap.\ntype exemptPropDef struct{ defaultPropDef }\n\nfunc (exemptPropDef) CapExempt() {}\n\n// execFnPropDef executes an arbitrary function on approval.\ntype execFnPropDef struct {\n\tpropDef\n\tfn commondao.ExecFunc\n}\n\nfunc (d execFnPropDef) Executor() commondao.ExecFunc { return d.fn }\n\n// validatingExecPropDef is a default rule definition with state validation.\ntype validatingExecPropDef struct {\n\tdefaultPropDef\n\terr *error\n}\n\nfunc (d validatingExecPropDef) Validate() error { return *d.err }\n\nfunc TestNew(t *testing.T) {\n\tdao := commondao.New()\n\tuassert.Equal(t, uint64(0), dao.ID())\n\tuassert.Equal(t, \"\", dao.Name())\n\tuassert.Equal(t, 0, dao.Council().Size())\n\tuassert.Equal(t, 0, dao.ActiveProposalsSize())\n\tuassert.Equal(t, 0, dao.FinishedProposalsSize())\n\tuassert.Equal(t, 0, len(dao.KindNames()))\n\tuassert.False(t, dao.IsDeleted())\n\turequire.True(t, dao.Parent() == nil, \"expect no parent\")\n\n\tparent := commondao.New(commondao.WithName(\"root\"))\n\tdao = commondao.New(\n\t\tcommondao.WithID(7),\n\t\tcommondao.WithName(\"child\"),\n\t\tcommondao.WithDescription(\"test\"),\n\t\tcommondao.WithParent(parent),\n\t\tcommondao.WithCouncilMember(memberA),\n\t\tcommondao.WithCouncilMember(memberB),\n\t)\n\tuassert.Equal(t, uint64(7), dao.ID())\n\tuassert.Equal(t, \"child\", dao.Name())\n\tuassert.Equal(t, \"test\", dao.Description())\n\tuassert.Equal(t, 2, dao.Council().Size())\n\tuassert.True(t, dao.Council().Has(memberA))\n\tuassert.Equal(t, \"root\", dao.Parent().Name())\n}\n\nfunc TestUpdateCouncil(t *testing.T) {\n\tdao := commondao.New(commondao.WithCouncilMember(memberA), commondao.WithProposalKind(probeKind{}))\n\n\t// Idempotent set semantics\n\turequire.NoError(t, dao.UpdateCouncil([]address{memberB, memberB}, nil))\n\tuassert.Equal(t, 2, dao.Council().Size())\n\turequire.NoError(t, dao.UpdateCouncil(nil, []address{memberC})) // absent remove\n\tuassert.Equal(t, 2, dao.Council().Size())\n\n\t// Overlapping add/remove is rejected\n\terr := dao.UpdateCouncil([]address{memberC}, []address{memberC})\n\tuassert.ErrorIs(t, err, commondao.ErrCouncilUpdateOverlap)\n\n\t// Emptying a non-empty council is rejected\n\terr = dao.UpdateCouncil(nil, []address{memberA, memberB})\n\tuassert.ErrorIs(t, err, commondao.ErrEmptyCouncil)\n\tuassert.Equal(t, 2, dao.Council().Size())\n\n\t// Removing all but one is allowed\n\turequire.NoError(t, dao.UpdateCouncil(nil, []address{memberA}))\n\tuassert.Equal(t, 1, dao.Council().Size())\n\tuassert.True(t, dao.Council().Has(memberB))\n\n\t// Full council replacement in a single update is legal\n\turequire.NoError(t, dao.UpdateCouncil([]address{memberC, memberD}, []address{memberB}))\n\tuassert.Equal(t, 2, dao.Council().Size())\n\tuassert.False(t, dao.Council().Has(memberB))\n\tuassert.True(t, dao.Council().Has(memberC))\n\tuassert.True(t, dao.Council().Has(memberD))\n\n\t// More removals than members is fine as long as a member survives\n\t// (the emptiness check is by identity, not by count)\n\turequire.NoError(t, dao.UpdateCouncil(nil, []address{memberE, memberF, memberG}))\n\tuassert.Equal(t, 2, dao.Council().Size())\n\n\t// An empty council can be seeded\n\tempty := commondao.New()\n\turequire.NoError(t, empty.UpdateCouncil(nil, nil))\n\turequire.NoError(t, empty.UpdateCouncil([]address{memberA}, nil))\n\tuassert.Equal(t, 1, empty.Council().Size())\n}\n\nfunc TestPropose(t *testing.T) {\n\tdao := commondao.New(\n\t\tcommondao.WithCouncilMember(memberA),\n\t\tcommondao.WithProposalKind(probeKind{}),\n\t)\n\n\tp, err := dao.Propose(memberA, \"probe\", propDef{period: time.Hour})\n\turequire.NoError(t, err)\n\tuassert.Equal(t, uint64(1), p.ID())\n\tuassert.Equal(t, 1, dao.ActiveProposalsSize())\n\turequire.True(t, dao.GetProposal(p.ID()) != nil, \"expect proposal to be found\")\n\n\t// The electorate is the council snapshot taken at proposal creation\n\tuassert.Equal(t, 1, p.Electorate().Size())\n\turequire.NoError(t, dao.UpdateCouncil([]address{memberB}, nil))\n\tuassert.Equal(t, 1, p.Electorate().Size())\n\tuassert.False(t, p.Electorate().Has(memberB))\n\n\t// Definitions are required\n\t_, err = dao.Propose(memberA, \"probe\", nil)\n\tuassert.ErrorIs(t, err, commondao.ErrProposalDefinitionRequired)\n\n\t// Deleted DAOs reject proposals\n\tdeleted := commondao.New(\n\t\tcommondao.WithCouncilMember(memberA),\n\t\tcommondao.WithProposalKind(probeKind{}),\n\t)\n\tdeleted.Dissolve(\"test\")\n\t_, err = deleted.Propose(memberA, \"probe\", propDef{})\n\tuassert.ErrorIs(t, err, commondao.ErrDAOIsDeleted)\n}\n\nfunc TestProposeCap(t *testing.T) {\n\tdao := commondao.New(\n\t\tcommondao.WithCouncilMember(memberA),\n\t\tcommondao.WithProposalKind(probeKind{}),\n\t)\n\tdao.SetMaxActiveProposals(2)\n\n\t_, err := dao.Propose(memberA, \"probe\", propDef{period: time.Hour})\n\turequire.NoError(t, err)\n\t_, err = dao.Propose(memberA, \"probe\", propDef{period: time.Hour})\n\turequire.NoError(t, err)\n\n\t// The cap rejects further proposals\n\t_, err = dao.Propose(memberA, \"probe\", propDef{period: time.Hour})\n\tuassert.ErrorIs(t, err, commondao.ErrMaxActiveProposals)\n\n\t// Cap exempt definitions bypass the cap\n\t_, err = dao.Propose(memberA, \"probe\", exemptPropDef{defaultPropDef{period: time.Hour}})\n\turequire.NoError(t, err)\n\n\t// But are bounded to one active exempt proposal per creator\n\t_, err = dao.Propose(memberA, \"probe\", exemptPropDef{defaultPropDef{period: time.Hour}})\n\tuassert.ErrorIs(t, err, commondao.ErrMaxCapExemptProposals)\n\t_, err = dao.Propose(memberB, \"probe\", exemptPropDef{defaultPropDef{period: time.Hour}})\n\turequire.NoError(t, err)\n}\n\nfunc TestProposeCapSlotFrees(t *testing.T) {\n\tdao := commondao.New(\n\t\tcommondao.WithCouncilMember(memberA),\n\t\tcommondao.WithCouncilMember(memberB),\n\t\tcommondao.WithCouncilMember(memberC),\n\t\tcommondao.WithProposalKind(probeKind{}),\n\t)\n\tdao.SetMaxActiveProposals(1)\n\n\tp := mustPropose(t, dao, memberA, defaultPropDef{period: time.Hour})\n\t_, err := dao.Propose(memberA, \"probe\", defaultPropDef{period: time.Hour})\n\turequire.ErrorIs(t, err, commondao.ErrMaxActiveProposals)\n\n\t// An immediate NO majority dismissal frees the slot\n\turequire.NoError(t, dao.Vote(memberA, p.ID(), commondao.ChoiceNo, \"\"))\n\turequire.NoError(t, dao.Vote(memberB, p.ID(), commondao.ChoiceNo, \"\"))\n\turequire.Equal(t, string(commondao.StatusDismissed), string(p.Status()))\n\n\t_, err = dao.Propose(memberA, \"probe\", defaultPropDef{period: time.Hour})\n\turequire.NoError(t, err)\n}\n\nfunc TestDissolve(t *testing.T) {\n\tdao := commondao.New(\n\t\tcommondao.WithCouncilMember(memberA),\n\t\tcommondao.WithProposalKind(probeKind{}),\n\t)\n\n\t// An early passed (but unexecuted) proposal is still in-flight\n\tp := mustPropose(t, dao, memberA, defaultPropDef{period: time.Hour})\n\turequire.NoError(t, dao.Vote(memberA, p.ID(), commondao.ChoiceYes, \"\"))\n\turequire.Equal(t, string(commondao.StatusPassed), string(p.Status()))\n\n\tdao.Dissolve(\"gone\")\n\n\tuassert.True(t, dao.IsDeleted())\n\tuassert.Equal(t, 0, dao.ActiveProposalsSize())\n\tuassert.Equal(t, 1, dao.FinishedProposalsSize())\n\tuassert.Equal(t, string(commondao.StatusDismissed), string(p.Status()))\n\tuassert.Equal(t, \"gone\", p.StatusReason())\n}\n\nfunc TestVote(t *testing.T) {\n\tdao := commondao.New(\n\t\tcommondao.WithCouncilMember(memberA),\n\t\tcommondao.WithCouncilMember(memberB),\n\t\tcommondao.WithCouncilMember(memberC),\n\t\tcommondao.WithProposalKind(probeKind{}),\n\t)\n\tp := mustPropose(t, dao, memberA, propDef{period: time.Hour})\n\n\t// Only electorate members can vote\n\terr := dao.Vote(memberD, p.ID(), commondao.ChoiceYes, \"\")\n\tuassert.ErrorIs(t, err, commondao.ErrNotElectorateMember)\n\n\t// Members added after proposal creation are not in the electorate\n\turequire.NoError(t, dao.UpdateCouncil([]address{memberD}, nil))\n\terr = dao.Vote(memberD, p.ID(), commondao.ChoiceYes, \"\")\n\tuassert.ErrorIs(t, err, commondao.ErrNotElectorateMember)\n\n\t// Members removed after proposal creation remain in the electorate\n\turequire.NoError(t, dao.UpdateCouncil(nil, []address{memberC}))\n\turequire.NoError(t, dao.Vote(memberC, p.ID(), commondao.ChoiceAbstain, \"\"))\n\n\t// Invalid choices are rejected\n\terr = dao.Vote(memberA, p.ID(), commondao.VoteChoice(\"FOO\"), \"\")\n\tuassert.ErrorIs(t, err, commondao.ErrInvalidVoteChoice)\n\n\t// Members can vote and change their vote\n\turequire.NoError(t, dao.Vote(memberA, p.ID(), commondao.ChoiceYes, \"\"))\n\turequire.NoError(t, dao.Vote(memberA, p.ID(), commondao.ChoiceNo, \"\"))\n\tuassert.Equal(t, 0, p.VotingRecord().VoteCount(commondao.ChoiceYes))\n\tuassert.Equal(t, 1, p.VotingRecord().VoteCount(commondao.ChoiceNo))\n\n\t// Unknown proposals and deadlines are rejected\n\terr = dao.Vote(memberA, 404, commondao.ChoiceYes, \"\")\n\tuassert.ErrorIs(t, err, commondao.ErrProposalNotFound)\n\n\texpired := mustPropose(t, dao, memberA, propDef{}) // zero voting period\n\terr = dao.Vote(memberA, expired.ID(), commondao.ChoiceYes, \"\")\n\tuassert.ErrorIs(t, err, commondao.ErrVotingDeadlinePassed)\n\n\t// Deleted DAOs reject votes\n\tdao.Dissolve(\"test\")\n\terr = dao.Vote(memberA, p.ID(), commondao.ChoiceYes, \"\")\n\tuassert.ErrorIs(t, err, commondao.ErrDAOIsDeleted)\n}\n\nfunc TestVoteEarlyTermination(t *testing.T) {\n\tnewDAO := func() *commondao.CommonDAO {\n\t\treturn commondao.New(\n\t\t\tcommondao.WithCouncilMember(memberA),\n\t\t\tcommondao.WithCouncilMember(memberB),\n\t\t\tcommondao.WithCouncilMember(memberC),\n\t\t\tcommondao.WithProposalKind(probeKind{}),\n\t\t)\n\t}\n\n\tt.Run(\"supermajority YES passes immediately\", func(t *testing.T) {\n\t\tdao := newDAO()\n\t\tp := mustPropose(t, dao, memberA, defaultPropDef{period: time.Hour})\n\n\t\turequire.NoError(t, dao.Vote(memberA, p.ID(), commondao.ChoiceYes, \"\"))\n\t\tuassert.Equal(t, string(commondao.StatusActive), string(p.Status()))\n\n\t\turequire.NoError(t, dao.Vote(memberB, p.ID(), commondao.ChoiceYes, \"\"))\n\t\tuassert.Equal(t, string(commondao.StatusPassed), string(p.Status()))\n\n\t\t// Passed proposals stay active (pending execution) but reject votes\n\t\tuassert.Equal(t, 1, dao.ActiveProposalsSize())\n\t\terr := dao.Vote(memberC, p.ID(), commondao.ChoiceNo, \"\")\n\t\tuassert.ErrorIs(t, err, commondao.ErrStatusIsNotActive)\n\t})\n\n\tt.Run(\"NO majority dismisses immediately\", func(t *testing.T) {\n\t\tdao := newDAO()\n\t\tp := mustPropose(t, dao, memberA, defaultPropDef{period: time.Hour})\n\n\t\turequire.NoError(t, dao.Vote(memberA, p.ID(), commondao.ChoiceNo, \"\"))\n\t\turequire.NoError(t, dao.Vote(memberB, p.ID(), commondao.ChoiceNo, \"\"))\n\n\t\tuassert.Equal(t, string(commondao.StatusDismissed), string(p.Status()))\n\t\tuassert.Equal(t, 0, dao.ActiveProposalsSize())\n\t\tuassert.Equal(t, 1, dao.FinishedProposalsSize())\n\t})\n\n\tt.Run(\"abstain flip can trigger a pass\", func(t *testing.T) {\n\t\tdao := commondao.New(\n\t\t\tcommondao.WithCouncilMember(memberA),\n\t\t\tcommondao.WithCouncilMember(memberB),\n\t\t\tcommondao.WithCouncilMember(memberC),\n\t\t\tcommondao.WithCouncilMember(memberD),\n\t\t\tcommondao.WithCouncilMember(memberE),\n\t\t\tcommondao.WithProposalKind(probeKind{}),\n\t\t)\n\t\tp := mustPropose(t, dao, memberA, defaultPropDef{period: time.Hour})\n\n\t\turequire.NoError(t, dao.Vote(memberA, p.ID(), commondao.ChoiceYes, \"\"))\n\t\turequire.NoError(t, dao.Vote(memberB, p.ID(), commondao.ChoiceYes, \"\"))\n\t\turequire.NoError(t, dao.Vote(memberC, p.ID(), commondao.ChoiceYes, \"\"))\n\t\turequire.NoError(t, dao.Vote(memberD, p.ID(), commondao.ChoiceNo, \"\"))\n\t\turequire.NoError(t, dao.Vote(memberE, p.ID(), commondao.ChoiceNo, \"\"))\n\t\tuassert.Equal(t, string(commondao.StatusActive), string(p.Status())) // 9 \u003c 10\n\n\t\t// NO -\u003e ABSTAIN shrinks the denominator: D=4, 3*3 \u003e= 2*4\n\t\turequire.NoError(t, dao.Vote(memberE, p.ID(), commondao.ChoiceAbstain, \"\"))\n\t\tuassert.Equal(t, string(commondao.StatusPassed), string(p.Status()))\n\t})\n}\n\nfunc TestExpectedOutcome(t *testing.T) {\n\tdao := commondao.New(\n\t\tcommondao.WithCouncilMember(memberA),\n\t\tcommondao.WithCouncilMember(memberB),\n\t\tcommondao.WithCouncilMember(memberC),\n\t\tcommondao.WithProposalKind(probeKind{}),\n\t)\n\n\t// Default rule proposals report the live tally\n\tp := mustPropose(t, dao, memberA, defaultPropDef{period: time.Hour})\n\tuassert.Equal(t, int(commondao.OutcomePending), int(p.ExpectedOutcome()))\n\turequire.NoError(t, dao.Vote(memberA, p.ID(), commondao.ChoiceYes, \"\"))\n\tuassert.Equal(t, int(commondao.OutcomePending), int(p.ExpectedOutcome()))\n\turequire.NoError(t, dao.Vote(memberB, p.ID(), commondao.ChoiceYes, \"\")) // 3*2 \u003e= 2*3\n\tuassert.Equal(t, int(commondao.OutcomePassed), int(p.ExpectedOutcome()))\n\n}\n\nfunc TestExecute(cur realm, t *testing.T) {\n\tt.Run(\"early passed proposals execute before the deadline\", func(t *testing.T) {\n\t\texecuted := false\n\t\tdao := commondao.New(commondao.WithCouncilMember(memberA), commondao.WithProposalKind(probeKind{}))\n\t\tp := mustPropose(t, dao, memberA, defaultPropDef{period: time.Hour, executed: \u0026executed})\n\n\t\turequire.NoError(t, dao.Vote(memberA, p.ID(), commondao.ChoiceYes, \"\"))\n\t\turequire.Equal(t, string(commondao.StatusPassed), string(p.Status()))\n\n\t\turequire.NoError(t, dao.Execute(p.ID(), cur))\n\t\tuassert.True(t, executed)\n\t\tuassert.Equal(t, string(commondao.StatusExecuted), string(p.Status()))\n\t\tuassert.Equal(t, 0, dao.ActiveProposalsSize())\n\t\tuassert.Equal(t, 1, dao.FinishedProposalsSize())\n\t})\n\n\tt.Run(\"active proposals cannot execute before the deadline\", func(t *testing.T) {\n\t\tdao := commondao.New(commondao.WithCouncilMember(memberA), commondao.WithProposalKind(probeKind{}))\n\t\tp := mustPropose(t, dao, memberA, defaultPropDef{period: time.Hour})\n\n\t\terr := dao.Execute(p.ID(), cur)\n\t\tuassert.ErrorIs(t, err, commondao.ErrVotingDeadlineNotMet)\n\t})\n\n\tt.Run(\"undecided default proposals are dismissed at the deadline\", func(t *testing.T) {\n\t\tdao := commondao.New(commondao.WithCouncilMember(memberA), commondao.WithProposalKind(probeKind{}))\n\t\tp := mustPropose(t, dao, memberA, defaultPropDef{}) // zero voting period\n\n\t\turequire.NoError(t, dao.Execute(p.ID(), cur))\n\t\tuassert.Equal(t, string(commondao.StatusDismissed), string(p.Status()))\n\t\tuassert.Equal(t, 1, dao.FinishedProposalsSize())\n\t})\n\n\tt.Run(\"undecided proposals dismiss before validation\", func(t *testing.T) {\n\t\t// A proposal that never passed archives as Dismissed even when its\n\t\t// definition no longer validates: dismissal is the truthful status\n\t\t// and the executor could never have run.\n\t\tstale := errors.New(\"stale\")\n\t\tdao := commondao.New(commondao.WithCouncilMember(memberA), commondao.WithProposalKind(probeKind{}))\n\t\tp := mustPropose(t, dao, memberA, validatingExecPropDef{\n\t\t\tdefaultPropDef: defaultPropDef{}, // zero voting period\n\t\t\terr:            \u0026stale,\n\t\t})\n\n\t\turequire.NoError(t, dao.Execute(p.ID(), cur))\n\t\tuassert.Equal(t, string(commondao.StatusDismissed), string(p.Status()))\n\t})\n\n\tt.Run(\"executor errors fail the proposal\", func(t *testing.T) {\n\t\tdao := commondao.New(commondao.WithCouncilMember(memberA), commondao.WithProposalKind(probeKind{}))\n\t\tp := mustPropose(t, dao, memberA, defaultPropDef{period: time.Hour, execErr: errors.New(\"exec boom\")})\n\n\t\turequire.NoError(t, dao.Vote(memberA, p.ID(), commondao.ChoiceYes, \"\"))\n\t\turequire.NoError(t, dao.Execute(p.ID(), cur))\n\t\tuassert.Equal(t, string(commondao.StatusFailed), string(p.Status()))\n\t\tuassert.Equal(t, \"exec boom\", p.StatusReason())\n\t\tuassert.Equal(t, 1, dao.FinishedProposalsSize())\n\t})\n\n\tt.Run(\"emptying council updates fail the proposal\", func(t *testing.T) {\n\t\tdao := commondao.New(commondao.WithCouncilMember(memberA), commondao.WithProposalKind(probeKind{}))\n\t\tp := mustPropose(t, dao, memberA, execFnPropDef{\n\t\t\tpropDef: propDef{period: time.Hour},\n\t\t\tfn: func(_ int, sub realm) error {\n\t\t\t\treturn dao.UpdateCouncil(nil, []address{memberA})\n\t\t\t},\n\t\t})\n\n\t\turequire.NoError(t, dao.Vote(memberA, p.ID(), commondao.ChoiceYes, \"\"))\n\t\turequire.NoError(t, dao.Execute(p.ID(), cur))\n\t\tuassert.Equal(t, string(commondao.StatusFailed), string(p.Status()))\n\t\tuassert.Equal(t, 1, dao.Council().Size(), \"expect council unchanged\")\n\t})\n\n\tt.Run(\"early passed proposals still validate\", func(t *testing.T) {\n\t\texecuted := false\n\t\tstale := errors.New(\"stale\")\n\t\tdao := commondao.New(commondao.WithCouncilMember(memberA), commondao.WithProposalKind(probeKind{}))\n\t\tp := mustPropose(t, dao, memberA, validatingExecPropDef{\n\t\t\tdefaultPropDef: defaultPropDef{period: time.Hour, executed: \u0026executed},\n\t\t\terr:            \u0026stale,\n\t\t})\n\n\t\turequire.NoError(t, dao.Vote(memberA, p.ID(), commondao.ChoiceYes, \"\"))\n\t\turequire.Equal(t, string(commondao.StatusPassed), string(p.Status()))\n\n\t\turequire.NoError(t, dao.Execute(p.ID(), cur))\n\t\tuassert.Equal(t, string(commondao.StatusFailed), string(p.Status()))\n\t\tuassert.Equal(t, \"stale\", p.StatusReason())\n\t\tuassert.False(t, executed, \"expect executor to not run when validation fails\")\n\t})\n\n\tt.Run(\"executors cannot re-enter Execute\", func(t *testing.T) {\n\t\t// The per-DAO executing latch panics on a re-entrant Execute of\n\t\t// the same DAO (aborting the tx), even for a different proposal\n\t\t// than the one currently executing. Removing the latch would let\n\t\t// the re-entrant call proceed.\n\t\tvar (\n\t\t\tdao   = commondao.New(commondao.WithCouncilMember(memberA), commondao.WithProposalKind(probeKind{}))\n\t\t\texecs int\n\t\t\tpid2  uint64\n\t\t)\n\t\tp1 := mustPropose(t, dao, memberA, execFnPropDef{\n\t\t\tpropDef: propDef{period: time.Hour},\n\t\t\tfn: func(_ int, sub realm) error {\n\t\t\t\texecs++\n\t\t\t\treturn dao.Execute(pid2, sub) // re-entrant: must panic\n\t\t\t},\n\t\t})\n\t\tp2 := mustPropose(t, dao, memberA, defaultPropDef{period: time.Hour})\n\t\tpid2 = p2.ID()\n\n\t\turequire.NoError(t, dao.Vote(memberA, p1.ID(), commondao.ChoiceYes, \"\"))\n\t\turequire.NoError(t, dao.Vote(memberA, pid2, commondao.ChoiceYes, \"\"))\n\n\t\tuassert.PanicsWithMessage(t, cur, \"commondao: re-entrant Execute is not allowed\", func() {\n\t\t\tdao.Execute(p1.ID(), cur)\n\t\t})\n\t\tuassert.Equal(t, 1, execs, \"expect executor to run exactly once\")\n\t})\n\n\tt.Run(\"kinds cannot re-enter Propose\", func(t *testing.T) {\n\t\t// The per-DAO proposing latch panics on a re-entrant Propose from\n\t\t// inside a kind's New. Removing the latch would let the nested\n\t\t// Propose proceed. (The latch also, via defer, cannot stay stuck\n\t\t// if New panics.)\n\t\tdao := commondao.New(commondao.WithCouncilMember(memberA), commondao.WithProposalKind(probeKind{}))\n\t\turequire.NoError(t, dao.RegisterKind(reProposeKind{dao: dao}))\n\t\tuassert.PanicsWithMessage(t, cur, \"commondao: re-entrant Propose is not allowed\", func() {\n\t\t\tdao.Propose(memberA, \"re-propose\", nil)\n\t\t})\n\t})\n\n\tt.Run(\"concurrent council updates merge in execution order\", func(t *testing.T) {\n\t\tdao := commondao.New(\n\t\t\tcommondao.WithCouncilMember(memberA),\n\t\t\tcommondao.WithCouncilMember(memberB),\n\t\t\tcommondao.WithCouncilMember(memberC),\n\t\t\tcommondao.WithProposalKind(probeKind{}),\n\t\t)\n\t\tp1 := mustPropose(t, dao, memberA, execFnPropDef{\n\t\t\tpropDef: propDef{period: time.Hour},\n\t\t\tfn: func(_ int, sub realm) error {\n\t\t\t\treturn dao.UpdateCouncil([]address{memberD}, []address{memberA})\n\t\t\t},\n\t\t})\n\t\tp2 := mustPropose(t, dao, memberB, execFnPropDef{\n\t\t\tpropDef: propDef{period: time.Hour},\n\t\t\tfn: func(_ int, sub realm) error {\n\t\t\t\t// Removing memberA again is an idempotent no-op\n\t\t\t\treturn dao.UpdateCouncil([]address{memberE}, []address{memberA})\n\t\t\t},\n\t\t})\n\n\t\tfor _, p := range []*commondao.Proposal{p1, p2} {\n\t\t\turequire.NoError(t, dao.Vote(memberA, p.ID(), commondao.ChoiceYes, \"\"))\n\t\t\turequire.NoError(t, dao.Vote(memberB, p.ID(), commondao.ChoiceYes, \"\"))\n\t\t}\n\n\t\turequire.NoError(t, dao.Execute(p1.ID(), cur))\n\t\turequire.NoError(t, dao.Execute(p2.ID(), cur))\n\t\turequire.Equal(t, string(commondao.StatusExecuted), string(p1.Status()))\n\t\turequire.Equal(t, string(commondao.StatusExecuted), string(p2.Status()))\n\n\t\tuassert.Equal(t, 4, dao.Council().Size())\n\t\tuassert.False(t, dao.Council().Has(memberA))\n\t\tuassert.True(t, dao.Council().Has(memberB))\n\t\tuassert.True(t, dao.Council().Has(memberC))\n\t\tuassert.True(t, dao.Council().Has(memberD))\n\t\tuassert.True(t, dao.Council().Has(memberE))\n\t})\n\n\tt.Run(\"deleted DAOs reject execution\", func(t *testing.T) {\n\t\tdao := commondao.New(commondao.WithCouncilMember(memberA), commondao.WithProposalKind(probeKind{}))\n\t\tp := mustPropose(t, dao, memberA, propDef{period: time.Hour})\n\t\tdao.Dissolve(\"test\")\n\n\t\terr := dao.Execute(p.ID(), cur)\n\t\tuassert.ErrorIs(t, err, commondao.ErrDAOIsDeleted)\n\t})\n\n\tt.Run(\"unknown proposals are rejected\", func(t *testing.T) {\n\t\tdao := commondao.New(commondao.WithCouncilMember(memberA), commondao.WithProposalKind(probeKind{}))\n\t\terr := dao.Execute(404, cur)\n\t\tuassert.ErrorIs(t, err, commondao.ErrProposalNotFound)\n\t})\n}\n\nfunc TestWithdraw(t *testing.T) {\n\tdao := commondao.New(\n\t\tcommondao.WithCouncilMember(memberA),\n\t\tcommondao.WithCouncilMember(memberB),\n\t\tcommondao.WithCouncilMember(memberC),\n\t\tcommondao.WithProposalKind(probeKind{}),\n\t)\n\n\t// Proposals without votes can be withdrawn\n\tp := mustPropose(t, dao, memberA, propDef{period: time.Hour})\n\turequire.NoError(t, dao.Withdraw(p.ID()))\n\tuassert.Equal(t, string(commondao.StatusWithdrawn), string(p.Status()))\n\tuassert.Equal(t, 0, dao.ActiveProposalsSize())\n\tuassert.Equal(t, 1, dao.FinishedProposalsSize())\n\n\t// Withdrawn proposals cannot be withdrawn again\n\terr := dao.Withdraw(p.ID())\n\tuassert.ErrorIs(t, err, commondao.ErrProposalNotFound)\n\n\t// Proposals with votes cannot be withdrawn\n\tp = mustPropose(t, dao, memberA, propDef{period: time.Hour})\n\turequire.NoError(t, dao.Vote(memberA, p.ID(), commondao.ChoiceAbstain, \"\"))\n\terr = dao.Withdraw(p.ID())\n\tuassert.ErrorIs(t, err, commondao.ErrWithdrawalNotAllowed)\n\n\t// Early passed proposals cannot be withdrawn\n\tp2 := mustPropose(t, dao, memberA, defaultPropDef{period: time.Hour})\n\turequire.NoError(t, dao.Vote(memberA, p2.ID(), commondao.ChoiceYes, \"\"))\n\turequire.NoError(t, dao.Vote(memberB, p2.ID(), commondao.ChoiceYes, \"\"))\n\turequire.Equal(t, string(commondao.StatusPassed), string(p2.Status()))\n\terr = dao.Withdraw(p2.ID())\n\tuassert.ErrorIs(t, err, commondao.ErrStatusIsNotActive)\n}\n\nfunc TestReadonlyCommonDAO(t *testing.T) {\n\tparent := commondao.New(commondao.WithName(\"root\"))\n\tdao := commondao.New(\n\t\tcommondao.WithID(7),\n\t\tcommondao.WithName(\"child\"),\n\t\tcommondao.WithDescription(\"test\"),\n\t\tcommondao.WithParent(parent),\n\t\tcommondao.WithCouncilMember(memberA),\n\t\tcommondao.WithProposalKind(probeKind{}),\n\t)\n\tp := mustPropose(t, dao, memberA, propDef{title: \"T\", body: \"B\", period: time.Hour})\n\n\tview := dao.Readonly()\n\tuassert.Equal(t, uint64(7), view.ID())\n\tuassert.Equal(t, \"child\", view.Name())\n\tuassert.Equal(t, \"test\", view.Description())\n\tuassert.False(t, view.IsDeleted())\n\tuassert.Equal(t, 1, view.Council().Size())\n\tuassert.Equal(t, 1, view.ActiveProposalsSize())\n\tuassert.Equal(t, 0, view.FinishedProposalsSize())\n\tuassert.Equal(t, 0, view.ChildrenCount())\n\n\tparentView, found := view.Parent()\n\turequire.True(t, found, \"expect parent view\")\n\tuassert.Equal(t, \"root\", parentView.Name())\n\t_, found = parentView.Parent()\n\tuassert.False(t, found)\n\n\tpv, found := view.GetProposal(p.ID())\n\turequire.True(t, found, \"expect proposal view\")\n\tuassert.Equal(t, p.ID(), pv.ID())\n\tuassert.Equal(t, \"T\", pv.Title())\n\tuassert.Equal(t, \"B\", pv.Body())\n\tuassert.Equal(t, string(commondao.StatusActive), string(pv.Status()))\n\tuassert.Equal(t, memberA, pv.Creator())\n\tuassert.Equal(t, 1, pv.Electorate().Size())\n\tuassert.Equal(t, 0, pv.VotingRecord().Size())\n\n\tvisited := 0\n\tview.IterateActiveProposals(0, 10, false, func(commondao.ReadonlyProposal) bool {\n\t\tvisited++\n\t\treturn false\n\t})\n\tuassert.Equal(t, 1, visited)\n\n\t// WithParent registered dao as a child of parent at construction\n\tuassert.Equal(t, 1, parentView.ChildrenCount())\n\tchildID := uint64(0)\n\tparentView.IterateChildren(func(child commondao.ReadonlyCommonDAO) bool {\n\t\tchildID = child.ID()\n\t\treturn false\n\t})\n\tuassert.Equal(t, uint64(7), childID)\n\n\t// A withdrawn proposal is visible through the finished-proposals view\n\tfp := mustPropose(t, dao, memberA, propDef{period: time.Hour})\n\turequire.NoError(t, dao.Withdraw(fp.ID()))\n\tuassert.Equal(t, 1, view.FinishedProposalsSize())\n\tfinished := 0\n\tview.IterateFinishedProposals(0, 10, false, func(commondao.ReadonlyProposal) bool {\n\t\tfinished++\n\t\treturn false\n\t})\n\tuassert.Equal(t, 1, finished)\n\n\t// Recorded votes are visible through the voting-record view\n\turequire.NoError(t, dao.Vote(memberA, p.ID(), commondao.ChoiceYes, \"\"))\n\tpv, _ = view.GetProposal(p.ID())\n\tyes := 0\n\tpv.VotingRecord().IterateVotesCount(func(c commondao.VoteChoice, count int) bool {\n\t\tif c == commondao.ChoiceYes {\n\t\t\tyes = count\n\t\t}\n\t\treturn false\n\t})\n\tuassert.Equal(t, 1, yes)\n\n\t// Views are live handles\n\tdao.Dissolve(\"test\")\n\tuassert.True(t, view.IsDeleted())\n}\n\nfunc TestCharter(t *testing.T) {\n\tdao := commondao.New(\n\t\tcommondao.WithName(\"D\"),\n\t\tcommondao.WithPurpose(\"to do good\"),\n\t\tcommondao.WithDescription(\"a test DAO\"),\n\t)\n\tuassert.Equal(t, \"to do good\", dao.Purpose())\n\tuassert.Equal(t, \"a test DAO\", dao.Description())\n\tuassert.Equal(t, \"to do good\", dao.Readonly().Purpose())\n\n\t// Purpose defaults empty when unset (the realm enforces non-empty).\n\tuassert.Equal(t, \"\", commondao.New().Purpose())\n}\n\nfunc TestAddressAndTreasuryFrozen(t *testing.T) {\n\tdao := commondao.New(commondao.WithAddress(memberA))\n\tuassert.Equal(t, string(memberA), string(dao.Address()))\n\n\tview := dao.Readonly()\n\tuassert.Equal(t, string(memberA), string(view.Address()))\n\n\t// Unset addresses are empty\n\tuassert.Equal(t, \"\", string(commondao.New().Address()))\n\n\tuassert.False(t, dao.IsTreasuryFrozen())\n\tdao.SetTreasuryFrozen(true)\n\tuassert.True(t, dao.IsTreasuryFrozen())\n\tuassert.True(t, view.IsTreasuryFrozen())\n\tdao.SetTreasuryFrozen(false)\n\tuassert.False(t, view.IsTreasuryFrozen())\n}\n\nfunc TestSetMaxActiveProposals(t *testing.T) {\n\tdao := commondao.New(commondao.WithCouncilMember(memberA), commondao.WithProposalKind(probeKind{}))\n\n\tdao.SetMaxActiveProposals(2)\n\t_ = mustPropose(t, dao, memberA, propDef{period: time.Hour})\n\t_ = mustPropose(t, dao, memberA, propDef{period: time.Hour})\n\t_, err := dao.Propose(memberA, \"probe\", propDef{period: time.Hour})\n\tuassert.ErrorIs(t, err, commondao.ErrMaxActiveProposals)\n\n\tuassert.Equal(t, 2, dao.MaxActiveProposals())\n\n\t// Values below the floor are ignored (the floor is 1, not 0/negative)\n\tdao.SetMaxActiveProposals(0)\n\t_, err = dao.Propose(memberA, \"probe\", propDef{period: time.Hour})\n\tuassert.ErrorIs(t, err, commondao.ErrMaxActiveProposals)\n\tdao.SetMaxActiveProposals(-5)\n\t_, err = dao.Propose(memberA, \"probe\", propDef{period: time.Hour})\n\tuassert.ErrorIs(t, err, commondao.ErrMaxActiveProposals)\n}\n\nfunc TestKindRegistry(cur realm, t *testing.T) {\n\tdao := commondao.New(commondao.WithCouncilMember(memberA))\n\n\t// A fresh DAO has no registered kinds\n\tuassert.False(t, dao.HasKind(\"probe\"))\n\tuassert.Equal(t, 0, len(dao.KindNames()))\n\n\t// Proposing through an unregistered kind is rejected\n\t_, err := dao.Propose(memberA, \"probe\", propDef{period: time.Hour})\n\tuassert.ErrorIs(t, err, commondao.ErrProposalKindNotFound)\n\n\t// Registered kinds create proposals\n\turequire.NoError(t, dao.RegisterKind(probeKind{}))\n\tuassert.True(t, dao.HasKind(\"probe\"))\n\tp := mustPropose(t, dao, memberA, propDef{period: time.Hour})\n\n\t// Nil kinds and empty kind names are rejected\n\terr = dao.RegisterKind(nil)\n\tuassert.ErrorIs(t, err, commondao.ErrProposalKindRequired)\n\terr = dao.RegisterKind(namedKind(\"\"))\n\tuassert.ErrorIs(t, err, commondao.ErrProposalKindRequired)\n\n\t// Duplicate kind names are rejected\n\terr = dao.RegisterKind(probeKind{})\n\tuassert.ErrorIs(t, err, commondao.ErrProposalKindExists)\n\n\t// KindNames is sorted by name\n\turequire.NoError(t, dao.RegisterKind(namedKind(\"zeta\")))\n\turequire.NoError(t, dao.RegisterKind(namedKind(\"alpha\")))\n\tnames := dao.KindNames()\n\turequire.Equal(t, 3, len(names))\n\tuassert.Equal(t, \"alpha\", names[0])\n\tuassert.Equal(t, \"probe\", names[1])\n\tuassert.Equal(t, \"zeta\", names[2])\n\n\t// The readonly view mirrors the registry reads\n\tview := dao.Readonly()\n\tuassert.True(t, view.HasKind(\"alpha\"))\n\tuassert.False(t, view.HasKind(\"beta\"))\n\tuassert.Equal(t, 3, len(view.KindNames()))\n\n\t// Deregistering an absent kind is rejected\n\terr = dao.DeregisterKind(\"beta\")\n\tuassert.ErrorIs(t, err, commondao.ErrProposalKindNotFound)\n\n\t// Deregistering blocks new proposals of the kind...\n\turequire.NoError(t, dao.DeregisterKind(\"probe\"))\n\tuassert.False(t, dao.HasKind(\"probe\"))\n\t_, err = dao.Propose(memberA, \"probe\", propDef{period: time.Hour})\n\tuassert.ErrorIs(t, err, commondao.ErrProposalKindNotFound)\n\n\t// ...but never touches in-flight proposals: the frozen definition\n\t// still votes, decides and executes (vote-integrity)\n\turequire.NoError(t, dao.Vote(memberA, p.ID(), commondao.ChoiceYes, \"\"))\n\turequire.Equal(t, string(commondao.StatusPassed), string(p.Status()))\n\turequire.NoError(t, dao.Execute(p.ID(), cur))\n\tuassert.Equal(t, string(commondao.StatusExecuted), string(p.Status()))\n\n\t// Kind factory errors propagate out of Propose\n\tboom := errors.New(\"bad args\")\n\turequire.NoError(t, dao.RegisterKind(failingKind{err: boom}))\n\t_, err = dao.Propose(memberA, \"failing\", nil)\n\tuassert.ErrorIs(t, err, boom)\n\tuassert.Equal(t, 0, dao.ActiveProposalsSize(), \"expect no proposal from a failing factory\")\n\n\t// Propose hands the kind factory a readonly view of the host DAO\n\tvar hostID uint64 = 999 // sentinel: New must overwrite it\n\turequire.NoError(t, dao.RegisterKind(hostKind{hostID: \u0026hostID}))\n\t_, err = dao.Propose(memberA, \"host\", nil)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, dao.ID(), hostID, \"expect the kind factory to receive a readonly view of the host DAO\")\n\n\t// Construction options panic on registration errors\n\tuassert.PanicsWithMessage(t, cur, commondao.ErrProposalKindRequired.Error(), func() {\n\t\tcommondao.New(commondao.WithProposalKind(nil))\n\t})\n\tuassert.PanicsWithMessage(t, cur, commondao.ErrProposalKindExists.Error(), func() {\n\t\tcommondao.New(\n\t\t\tcommondao.WithProposalKind(probeKind{}),\n\t\t\tcommondao.WithProposalKind(probeKind{}),\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":"execution_kind_test.gno","body":"package commondao_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n\n\t\"gno.land/p/nt/commondao/v0\"\n)\n\n// New receives a ReadonlyCommonDAO, which exposes no mutators, so a kind\n// cannot mutate the host (or its tree) at Propose time. This is enforced\n// structurally by the type system, not at runtime: the following method\n// does not compile, because ReadonlyCommonDAO has no UpdateCouncil (nor\n// any other mutator), and it cannot be downcast to *CommonDAO.\n//\n//\tfunc (mutatingKind) New(dao commondao.ReadonlyCommonDAO, _ any) (commondao.ProposalDefinition, error) {\n//\t\tdao.UpdateCouncil(nil, []address{memberA}) // compile error: undefined\n//\t\treturn propDef{}, nil\n//\t}\n\nfunc TestExecutionKind(cur realm, t *testing.T) {\n\tdao := commondao.New(\n\t\tcommondao.WithCouncilMember(memberA),\n\t\tcommondao.WithProposalKind(commondao.ExecutionKind{}),\n\t)\n\n\t// A nil Fn is rejected at Propose.\n\t_, err := dao.Propose(memberA, \"execution\", commondao.ExecutionArgs{Title: \"T\", Body: \"B\"})\n\tuassert.ErrorIs(t, err, commondao.ErrExecutionFuncRequired)\n\n\t// Wrong args type is rejected too.\n\t_, err = dao.Propose(memberA, \"execution\", \"not the args\")\n\tuassert.ErrorIs(t, err, commondao.ErrExecutionFuncRequired)\n\n\t// A valid execution proposal runs the supplied Fn on approval.\n\tran := false\n\tp, err := dao.Propose(memberA, \"execution\", commondao.ExecutionArgs{\n\t\tTitle: \"Do a thing\",\n\t\tBody:  \"details\",\n\t\tFn: func(_ int, _ realm) error {\n\t\t\tran = true\n\t\t\treturn nil\n\t\t},\n\t})\n\turequire.NoError(t, err)\n\tuassert.Equal(t, \"Do a thing\", p.Definition().Title())\n\tuassert.Equal(t, \"details\", p.Definition().Body())\n\n\turequire.NoError(t, dao.Vote(memberA, p.ID(), commondao.ChoiceYes, \"\"))\n\turequire.Equal(t, string(commondao.StatusPassed), string(p.Status()))\n\turequire.NoError(t, dao.Execute(p.ID(), cur))\n\tuassert.True(t, ran, \"expect the supplied Fn to run\")\n\tuassert.Equal(t, string(commondao.StatusExecuted), string(p.Status()))\n}\n\n// TestDeregisterKind pins that DeregisterKind is a plain primitive with no\n// reserved names: any registered kind can be removed (anti-brick is the\n// consuming realm's policy, not a /p/ lock), and an unknown name reports\n// ErrProposalKindNotFound.\nfunc TestDeregisterKind(t *testing.T) {\n\tdao := commondao.New(\n\t\tcommondao.WithCouncilMember(memberA),\n\t\tcommondao.WithProposalKind(commondao.ExecutionKind{}),\n\t\t// A kind whose name sounds reserved is still ordinary: /p/ reserves no\n\t\t// names, so it deregisters like any other.\n\t\tcommondao.WithProposalKind(namedKind(\"register-kind\")),\n\t)\n\n\t// Any registered kind deregisters, including the reserved-sounding name.\n\turequire.NoError(t, dao.DeregisterKind(\"register-kind\"))\n\tuassert.False(t, dao.HasKind(\"register-kind\"))\n\n\turequire.NoError(t, dao.DeregisterKind(\"execution\"))\n\tuassert.False(t, dao.HasKind(\"execution\"))\n\n\t// An unknown name is rejected.\n\terr := dao.DeregisterKind(\"unknown\")\n\tuassert.ErrorIs(t, err, commondao.ErrProposalKindNotFound)\n}\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":"proposal_test.gno","body":"package commondao_test\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\n\t\"gno.land/p/nt/commondao/v0\"\n)\n\n// validablePropDef supports state validation.\ntype validablePropDef struct {\n\tpropDef\n\terr error\n}\n\nfunc (d validablePropDef) Validate() error { return d.err }\n\nfunc TestProposalNew(t *testing.T) {\n\tdao := commondao.New(commondao.WithCouncilMember(memberA), commondao.WithProposalKind(probeKind{}))\n\n\tt.Run(\"creator must be valid\", func(t *testing.T) {\n\t\t_, err := dao.Propose(address(\"\"), \"probe\", propDef{})\n\t\tuassert.ErrorIs(t, err, commondao.ErrInvalidCreatorAddress)\n\t})\n\n\tt.Run(\"defaults\", func(t *testing.T) {\n\t\tp := mustPropose(t, dao, memberA, propDef{title: \"T\", body: \"B\", period: time.Hour})\n\n\t\tuassert.Equal(t, string(commondao.StatusActive), string(p.Status()))\n\t\tuassert.Equal(t, memberA, p.Creator())\n\t\tuassert.Equal(t, \"T\", p.Definition().Title())\n\t\tuassert.Equal(t, \"B\", p.Definition().Body())\n\t\tuassert.Equal(t, 0, p.VotingRecord().Size())\n\t\tuassert.Equal(t, \"\", p.StatusReason())\n\t\tuassert.False(t, p.HasVotingDeadlinePassed())\n\n\t})\n}\n\nfunc TestProposalValidate(t *testing.T) {\n\tdao := commondao.New(commondao.WithCouncilMember(memberA), commondao.WithProposalKind(probeKind{}))\n\n\tt.Run(\"non validable definitions are always valid\", func(t *testing.T) {\n\t\tp := mustPropose(t, dao, memberA, propDef{period: time.Hour})\n\t\tuassert.NoError(t, p.Validate())\n\t})\n\n\tt.Run(\"validable definitions validate while executable\", func(t *testing.T) {\n\t\tboom := errors.New(\"boom\")\n\t\tp := mustPropose(t, dao, memberA, validablePropDef{\n\t\t\tpropDef: propDef{period: time.Hour},\n\t\t\terr:     boom,\n\t\t})\n\t\tuassert.ErrorIs(t, p.Validate(), boom)\n\t})\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"},{"name":"record_test.gno","body":"package commondao_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/addrset/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n\n\t\"gno.land/p/nt/commondao/v0\"\n)\n\n// mustNewVote builds a reason-less vote or fails the test.\nfunc mustNewVote(t *testing.T, addr address, c commondao.VoteChoice) commondao.Vote {\n\tt.Helper()\n\tv, err := commondao.NewVote(addr, c, \"\")\n\turequire.NoError(t, err, \"new vote\")\n\treturn v\n}\n\nfunc TestVotingRecordDefaults(t *testing.T) {\n\tvar record commondao.VotingRecord\n\n\tuassert.Equal(t, 0, record.Size())\n\tuassert.Equal(t, 0, record.VoteCount(commondao.ChoiceYes))\n\tuassert.False(t, record.HasVoted(memberA))\n\n\t_, found := record.GetVote(memberA)\n\tuassert.False(t, found)\n}\n\nfunc TestVotingRecordAddVote(t *testing.T) {\n\tvar record commondao.VotingRecord\n\n\tvote, err := commondao.NewVote(memberA, commondao.ChoiceYes, \"foo\")\n\turequire.NoError(t, err)\n\tupdated := record.AddVote(vote)\n\tuassert.False(t, updated, \"expect first vote to be an insert\")\n\tuassert.Equal(t, 1, record.Size())\n\tuassert.Equal(t, 1, record.VoteCount(commondao.ChoiceYes))\n\tuassert.True(t, record.HasVoted(memberA))\n\n\tv, found := record.GetVote(memberA)\n\tuassert.True(t, found)\n\tuassert.Equal(t, string(commondao.ChoiceYes), string(v.Choice()))\n\tuassert.Equal(t, \"foo\", v.Reason())\n\n\t// Voting again overwrites the previous vote and updates the counters\n\tupdated = record.AddVote(mustNewVote(t, memberA, commondao.ChoiceNo))\n\tuassert.True(t, updated, \"expect second vote to be an update\")\n\tuassert.Equal(t, 1, record.Size())\n\tuassert.Equal(t, 0, record.VoteCount(commondao.ChoiceYes))\n\tuassert.Equal(t, 1, record.VoteCount(commondao.ChoiceNo))\n\n\trecord.AddVote(mustNewVote(t, memberB, commondao.ChoiceNo))\n\tuassert.Equal(t, 2, record.Size())\n\tuassert.Equal(t, 2, record.VoteCount(commondao.ChoiceNo))\n\n\tcount := 0\n\trecord.Iterate(0, record.Size(), false, func(commondao.Vote) bool {\n\t\tcount++\n\t\treturn false\n\t})\n\tuassert.Equal(t, 2, count)\n}\n\nfunc TestTallyDefault(t *testing.T) {\n\tcases := []struct {\n\t\tname       string\n\t\telectorate []address\n\t\tyes        []address\n\t\tno         []address\n\t\tabstain    []address\n\t\tthreshold  commondao.Threshold\n\t\twant       commondao.Outcome\n\t}{\n\t\t{\n\t\t\tname: \"empty electorate stays pending\",\n\t\t\twant: commondao.OutcomePending,\n\t\t},\n\t\t{\n\t\t\tname:       \"no votes stays pending\",\n\t\t\telectorate: []address{memberA, memberB, memberC},\n\t\t\twant:       commondao.OutcomePending,\n\t\t},\n\t\t{\n\t\t\tname:       \"all abstain stays pending\",\n\t\t\telectorate: []address{memberA, memberB, memberC},\n\t\t\tabstain:    []address{memberA, memberB, memberC},\n\t\t\twant:       commondao.OutcomePending,\n\t\t},\n\t\t{\n\t\t\tname:       \"supermajority boundary passes\",\n\t\t\telectorate: []address{memberA, memberB, memberC},\n\t\t\tyes:        []address{memberA, memberB}, // 3*2 \u003e= 2*3\n\t\t\twant:       commondao.OutcomePassed,\n\t\t},\n\t\t{\n\t\t\tname:       \"below supermajority stays pending\",\n\t\t\telectorate: []address{memberA, memberB, memberC},\n\t\t\tyes:        []address{memberA},\n\t\t\tno:         []address{memberB},\n\t\t\twant:       commondao.OutcomePending,\n\t\t},\n\t\t{\n\t\t\tname:       \"abstains shrink the denominator for passing\",\n\t\t\telectorate: []address{memberA, memberB, memberC},\n\t\t\tyes:        []address{memberA},\n\t\t\tabstain:    []address{memberB, memberC}, // D=1, 3*1 \u003e= 2*1\n\t\t\twant:       commondao.OutcomePassed,\n\t\t},\n\t\t{\n\t\t\tname:       \"silence counts against passage\",\n\t\t\telectorate: []address{memberA, memberB, memberC, memberD, memberE, memberF, memberG, memberH, memberI},\n\t\t\tyes:        []address{memberA, memberB, memberC, memberD},\n\t\t\tno:         []address{memberE}, // 4Y/1N/4 silent: 12 \u003c 18\n\t\t\twant:       commondao.OutcomePending,\n\t\t},\n\t\t{\n\t\t\tname:       \"NO majority boundary is strict\",\n\t\t\telectorate: []address{memberA, memberB, memberC, memberD},\n\t\t\tno:         []address{memberA, memberB}, // 2*2 == 4: not dismissed\n\t\t\twant:       commondao.OutcomePending,\n\t\t},\n\t\t{\n\t\t\tname:       \"NO majority dismisses\",\n\t\t\telectorate: []address{memberA, memberB, memberC, memberD},\n\t\t\tno:         []address{memberA, memberB, memberC}, // 2*3 \u003e 4\n\t\t\twant:       commondao.OutcomeDismissed,\n\t\t},\n\t\t{\n\t\t\tname:       \"abstains shrink the denominator for dismissal\",\n\t\t\telectorate: []address{memberA, memberB, memberC, memberD, memberE},\n\t\t\tno:         []address{memberA, memberB},\n\t\t\tabstain:    []address{memberC, memberD}, // D=3, 2*2 \u003e 3\n\t\t\twant:       commondao.OutcomeDismissed,\n\t\t},\n\t\t{\n\t\t\tname:       \"simple majority boundary does not pass\",\n\t\t\telectorate: []address{memberA, memberB, memberC, memberD},\n\t\t\tyes:        []address{memberA, memberB}, // 2*2 == 4\n\t\t\tthreshold:  commondao.ThresholdSimpleMajority,\n\t\t\twant:       commondao.OutcomePending,\n\t\t},\n\t\t{\n\t\t\tname:       \"simple majority passes\",\n\t\t\telectorate: []address{memberA, memberB, memberC, memberD},\n\t\t\tyes:        []address{memberA, memberB, memberC}, // 2*3 \u003e 4\n\t\t\tthreshold:  commondao.ThresholdSimpleMajority,\n\t\t\twant:       commondao.OutcomePassed,\n\t\t},\n\t\t{\n\t\t\tname:       \"simple majority minimal boundary passes\",\n\t\t\telectorate: []address{memberA, memberB, memberC},\n\t\t\tyes:        []address{memberA, memberB}, // 2*2 == D+1\n\t\t\tthreshold:  commondao.ThresholdSimpleMajority,\n\t\t\twant:       commondao.OutcomePassed,\n\t\t},\n\t\t{\n\t\t\tname:       \"votes from outside the electorate are not counted\",\n\t\t\telectorate: []address{memberA, memberB},\n\t\t\tyes:        []address{memberC, memberD}, // strangers\n\t\t\twant:       commondao.OutcomePending,\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tvar (\n\t\t\t\telectorate addrset.Set\n\t\t\t\trecord     commondao.VotingRecord\n\t\t\t)\n\t\t\tfor _, m := range tc.electorate {\n\t\t\t\telectorate.Add(m)\n\t\t\t}\n\t\t\tfor _, m := range tc.yes {\n\t\t\t\trecord.AddVote(mustNewVote(t, m, commondao.ChoiceYes))\n\t\t\t}\n\t\t\tfor _, m := range tc.no {\n\t\t\t\trecord.AddVote(mustNewVote(t, m, commondao.ChoiceNo))\n\t\t\t}\n\t\t\tfor _, m := range tc.abstain {\n\t\t\t\trecord.AddVote(mustNewVote(t, m, commondao.ChoiceAbstain))\n\t\t\t}\n\n\t\t\tgot := commondao.TallyDefault(record.Readonly(), electorate.Readonly(), tc.threshold)\n\n\t\t\tuassert.Equal(t, int(tc.want), int(got))\n\t\t})\n\t}\n}\n\n// refOutcome is an independent restatement of the constitutional tally\n// rule, used to exhaustively cross-check TallyDefault at every boundary.\nfunc refOutcome(electorateSize, yes, no, abstain int, threshold commondao.Threshold) commondao.Outcome {\n\td := electorateSize - abstain\n\tif d \u003c= 0 {\n\t\treturn commondao.OutcomePending\n\t}\n\tpassed := false\n\tif threshold == commondao.ThresholdSimpleMajority {\n\t\tpassed = 2*yes \u003e d // \"more than half\"\n\t} else {\n\t\tpassed = 3*yes \u003e= 2*d // \"two thirds or more\"\n\t}\n\tif passed {\n\t\treturn commondao.OutcomePassed\n\t}\n\tif 2*no \u003e d { // NO simple majority dismisses (both thresholds)\n\t\treturn commondao.OutcomeDismissed\n\t}\n\treturn commondao.OutcomePending\n}\n\n// TestTallyDefaultProperty exhaustively enumerates every electorate size\n// up to 8 and every (yes, no, abstain) split for both thresholds,\n// checking TallyDefault against refOutcome and machine-checking the\n// invariants the ADR argues in prose (mutual exclusivity, the D\u003e0 guard,\n// abstain-shrinks-D monotonicity, and electorate gating).\nfunc TestTallyDefaultProperty(t *testing.T) {\n\t// Eight electorate members plus one non-member \"stranger\".\n\tpool := []address{memberA, memberB, memberC, memberD, memberE, memberF, memberG, memberH}\n\tstranger := memberI\n\tthresholds := []commondao.Threshold{commondao.ThresholdSupermajority, commondao.ThresholdSimpleMajority}\n\n\tfor e := 0; e \u003c= len(pool); e++ {\n\t\tfor yes := 0; yes \u003c= e; yes++ {\n\t\t\tfor no := 0; no+yes \u003c= e; no++ {\n\t\t\t\tfor abstain := 0; abstain+no+yes \u003c= e; abstain++ {\n\t\t\t\t\tfor _, th := range thresholds {\n\t\t\t\t\t\tvar electorate addrset.Set\n\t\t\t\t\t\tfor i := 0; i \u003c e; i++ {\n\t\t\t\t\t\t\telectorate.Add(pool[i])\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvar record commondao.VotingRecord\n\t\t\t\t\t\tidx := 0\n\t\t\t\t\t\tput := func(n int, c commondao.VoteChoice) {\n\t\t\t\t\t\t\tfor i := 0; i \u003c n; i++ {\n\t\t\t\t\t\t\t\tv, err := commondao.NewVote(pool[idx], c, \"\")\n\t\t\t\t\t\t\t\turequire.NoError(t, err)\n\t\t\t\t\t\t\t\trecord.AddVote(v)\n\t\t\t\t\t\t\t\tidx++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tput(yes, commondao.ChoiceYes)\n\t\t\t\t\t\tput(no, commondao.ChoiceNo)\n\t\t\t\t\t\tput(abstain, commondao.ChoiceAbstain)\n\t\t\t\t\t\t// Remaining electorate members stay silent.\n\n\t\t\t\t\t\tgot := commondao.TallyDefault(record.Readonly(), electorate.Readonly(), th)\n\t\t\t\t\t\twant := refOutcome(e, yes, no, abstain, th)\n\t\t\t\t\t\turequire.Equal(t, int(want), int(got),\n\t\t\t\t\t\t\t\"TallyDefault disagreed with the reference formula at some (E, yes, no, abstain, threshold)\")\n\n\t\t\t\t\t\t// Invariant: pass and dismiss are mutually exclusive\n\t\t\t\t\t\t// (yes+no \u003c= D holds since yes+no+abstain \u003c= e).\n\t\t\t\t\t\td := e - abstain\n\t\t\t\t\t\tpassSuper := d \u003e 0 \u0026\u0026 3*yes \u003e= 2*d\n\t\t\t\t\t\tpassSimple := d \u003e 0 \u0026\u0026 2*yes \u003e d\n\t\t\t\t\t\tdismiss := d \u003e 0 \u0026\u0026 2*no \u003e d\n\t\t\t\t\t\tuassert.False(t, passSuper \u0026\u0026 dismiss, \"supermajority pass and dismiss both fired\")\n\t\t\t\t\t\tuassert.False(t, passSimple \u0026\u0026 dismiss, \"simple pass and dismiss both fired\")\n\n\t\t\t\t\t\t// Invariant: votes from outside the electorate never\n\t\t\t\t\t\t// change the outcome.\n\t\t\t\t\t\tsv, err := commondao.NewVote(stranger, commondao.ChoiceYes, \"\")\n\t\t\t\t\t\turequire.NoError(t, err)\n\t\t\t\t\t\trecord.AddVote(sv)\n\t\t\t\t\t\tgotWithStranger := commondao.TallyDefault(record.Readonly(), electorate.Readonly(), th)\n\t\t\t\t\t\tuassert.Equal(t, int(got), int(gotWithStranger), \"out-of-electorate vote changed the outcome\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n// TestTallyDefaultDGuard pins the load-bearing D\u003e0 guard: an all-abstain\n// or empty electorate never passes, even at a zero-YES tally.\nfunc TestTallyDefaultDGuard(t *testing.T) {\n\tvar empty addrset.Set\n\tvar record commondao.VotingRecord\n\tuassert.Equal(t, int(commondao.OutcomePending),\n\t\tint(commondao.TallyDefault(record.Readonly(), empty.Readonly(), commondao.ThresholdSupermajority)))\n\n\tvar electorate addrset.Set\n\telectorate.Add(memberA)\n\telectorate.Add(memberB)\n\tv, err := commondao.NewVote(memberA, commondao.ChoiceAbstain, \"\")\n\turequire.NoError(t, err)\n\trecord.AddVote(v)\n\tv, err = commondao.NewVote(memberB, commondao.ChoiceAbstain, \"\")\n\turequire.NoError(t, err)\n\trecord.AddVote(v)\n\t// D = 2 - 2 = 0: no YES, must stay pending (not a 3*0 \u003e= 2*0 pass).\n\tuassert.Equal(t, int(commondao.OutcomePending),\n\t\tint(commondao.TallyDefault(record.Readonly(), electorate.Readonly(), commondao.ThresholdSupermajority)))\n}\n\n// TestVotingRecordReVoteSameChoice pins that re-voting the identical choice\n// is idempotent: AddVote decrements the previous choice then increments the\n// new one, so a same-choice re-vote nets to zero — the counter must stay 1,\n// not double-count.\nfunc TestVotingRecordReVoteSameChoice(t *testing.T) {\n\tvar record commondao.VotingRecord\n\n\trecord.AddVote(mustNewVote(t, memberA, commondao.ChoiceYes))\n\tupdated := record.AddVote(mustNewVote(t, memberA, commondao.ChoiceYes))\n\n\tuassert.True(t, updated, \"expect a re-vote to be an update\")\n\tuassert.Equal(t, 1, record.Size())\n\tuassert.Equal(t, 1, record.VoteCount(commondao.ChoiceYes))\n}\n"},{"name":"z_commondao_execute_0_filetest.gno","body":"// PKGPATH: gno.land/r/test\npackage test\n\nimport (\n\t\"time\"\n\n\t\"gno.land/p/nt/commondao/v0\"\n)\n\nconst member address = \"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\" // @devx\n\nvar (\n\tdao        *commondao.CommonDAO\n\tproposal   *commondao.Proposal\n\tsubValid   bool\n\tsubAddress address\n)\n\ntype testPropDef struct{}\n\nfunc (testPropDef) Title() string               { return \"\" }\nfunc (testPropDef) Body() string                { return \"\" }\nfunc (testPropDef) VotingPeriod() time.Duration { return time.Hour }\nfunc (testPropDef) Threshold() commondao.Threshold {\n\treturn commondao.ThresholdSupermajority\n}\n\nfunc (testPropDef) Executor() commondao.ExecFunc {\n\t// Executors are non-crossing: they must not rely on\n\t// unsafe.PreviousRealm() for realm identity (there is no crossing frame\n\t// for the executor). The DAO-scoped identity is the sub passed by the\n\t// host, which the executor can read and move value from.\n\treturn func(_ int, sub realm) error {\n\t\tsubValid = sub.Address().IsValid()\n\t\tsubAddress = sub.Address()\n\t\treturn nil\n\t}\n}\n\ntype testPropKind struct{}\n\nfunc (testPropKind) Name() string { return \"test\" }\nfunc (testPropKind) New(_ commondao.ReadonlyCommonDAO, _ any) (commondao.ProposalDefinition, error) {\n\treturn testPropDef{}, nil\n}\n\nfunc init() {\n\tdao = commondao.New(\n\t\tcommondao.WithCouncilMember(member),\n\t\tcommondao.WithProposalKind(testPropKind{}),\n\t)\n\tvar err error\n\tproposal, err = dao.Propose(member, \"test\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// A single YES from the one-member council passes the proposal early\n\tif err := dao.Vote(member, proposal.ID(), commondao.ChoiceYes, \"\"); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc main(cur realm) {\n\t// The host mints the DAO-scoped sub and passes it into Execute; the\n\t// executor runs with that sub as its value-movement authority.\n\tsub := cur.Sub(\"dao/1\")\n\terr := dao.Execute(proposal.ID(), sub)\n\n\tprintln(err == nil)\n\tprintln(string(proposal.Status()))\n\tprintln(subValid)\n\tprintln(subAddress == sub.Address())\n}\n\n// Output:\n// true\n// executed\n// true\n// true\n"},{"name":"z_commondao_execute_1_filetest.gno","body":"// PKGPATH: gno.land/r/test\npackage test\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"gno.land/p/nt/commondao/v0\"\n)\n\nconst member address = \"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\" // @devx\n\nvar (\n\tdao      *commondao.CommonDAO\n\tproposal *commondao.Proposal\n)\n\ntype testPropDef struct{}\n\nfunc (testPropDef) Title() string               { return \"\" }\nfunc (testPropDef) Body() string                { return \"\" }\nfunc (testPropDef) VotingPeriod() time.Duration { return time.Hour }\nfunc (testPropDef) Threshold() commondao.Threshold {\n\treturn commondao.ThresholdSupermajority\n}\n\nfunc (testPropDef) Executor() commondao.ExecFunc {\n\treturn func(_ int, sub realm) error {\n\t\treturn errors.New(\"test error\")\n\t}\n}\n\ntype testPropKind struct{}\n\nfunc (testPropKind) Name() string { return \"test\" }\nfunc (testPropKind) New(_ commondao.ReadonlyCommonDAO, _ any) (commondao.ProposalDefinition, error) {\n\treturn testPropDef{}, nil\n}\n\nfunc init() {\n\tdao = commondao.New(\n\t\tcommondao.WithCouncilMember(member),\n\t\tcommondao.WithProposalKind(testPropKind{}),\n\t)\n\tvar err error\n\tproposal, err = dao.Propose(member, \"test\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// A single YES from the one-member council passes the proposal early\n\tif err := dao.Vote(member, proposal.ID(), commondao.ChoiceYes, \"\"); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc main(cur realm) {\n\terr := dao.Execute(proposal.ID(), cur.Sub(\"dao/1\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tprintln(string(proposal.Status()))\n\tprintln(proposal.StatusReason())\n}\n\n// Output:\n// failed\n// test error\n"},{"name":"z_commondao_execute_2_filetest.gno","body":"// PKGPATH: gno.land/r/test\npackage test\n\nimport (\n\t\"time\"\n\n\t\"gno.land/p/nt/commondao/v0\"\n)\n\nconst member address = \"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\" // @devx\n\nvar (\n\tdao      *commondao.CommonDAO\n\tproposal *commondao.Proposal\n\texecuted bool\n)\n\ntype testPropDef struct{}\n\nfunc (testPropDef) Title() string                  { return \"\" }\nfunc (testPropDef) Body() string                   { return \"\" }\nfunc (testPropDef) VotingPeriod() time.Duration    { return time.Hour } // Voting ends in 1 hour\nfunc (testPropDef) Threshold() commondao.Threshold { return commondao.ThresholdSupermajority }\n\nfunc (testPropDef) Executor() commondao.ExecFunc {\n\treturn func(_ int, sub realm) error {\n\t\texecuted = true\n\t\treturn nil\n\t}\n}\n\ntype testPropKind struct{}\n\nfunc (testPropKind) Name() string { return \"test\" }\nfunc (testPropKind) New(_ commondao.ReadonlyCommonDAO, _ any) (commondao.ProposalDefinition, error) {\n\treturn testPropDef{}, nil\n}\n\nfunc init() {\n\tdao = commondao.New(\n\t\tcommondao.WithCouncilMember(member),\n\t\tcommondao.WithProposalKind(testPropKind{}),\n\t)\n\tvar err error\n\tproposal, err = dao.Propose(member, \"test\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc main(cur realm) {\n\t// A supermajority of YES decides the proposal immediately\n\terr := dao.Vote(member, proposal.ID(), commondao.ChoiceYes, \"\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tprintln(string(proposal.Status()))\n\n\t// Proposals decided early can be executed before the voting deadline.\n\t// The host mints the DAO-scoped sub and passes it into Execute.\n\terr = dao.Execute(proposal.ID(), cur.Sub(\"dao/1\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tprintln(executed)\n\tprintln(string(proposal.Status()))\n}\n\n// Output:\n// passed\n// true\n// executed\n"},{"name":"z_commondao_execute_3_filetest.gno","body":"// PKGPATH: gno.land/r/test\npackage test\n\nimport (\n\t\"time\"\n\n\t\"gno.land/p/nt/commondao/v0\"\n)\n\nconst member address = \"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\" // @devx\n\nvar (\n\tdao                  *commondao.CommonDAO\n\tproposal             *commondao.Proposal\n\tactiveSizeDuringExec int\n\texecCount            int\n)\n\n// probePropDef observes, from inside its own executor, whether its proposal\n// is still in active storage. Execute removes the proposal from active\n// storage BEFORE running Validate/the executor (remove-before-run); that is\n// exactly what makes a re-entrant Execute of the same proposal impossible\n// (it would find nothing in active storage). So during the executor the\n// active-proposal count must already be 0. Deleting that removal would\n// leave the count at 1 — a re-entrancy hole.\ntype probePropDef struct{}\n\nfunc (probePropDef) Title() string               { return \"\" }\nfunc (probePropDef) Body() string                { return \"\" }\nfunc (probePropDef) VotingPeriod() time.Duration { return time.Hour }\nfunc (probePropDef) Threshold() commondao.Threshold {\n\treturn commondao.ThresholdSupermajority\n}\n\nfunc (probePropDef) Executor() commondao.ExecFunc {\n\treturn func(_ int, sub realm) error {\n\t\texecCount++\n\t\tactiveSizeDuringExec = dao.ActiveProposalsSize()\n\t\treturn nil\n\t}\n}\n\ntype probePropKind struct{}\n\nfunc (probePropKind) Name() string { return \"probe\" }\nfunc (probePropKind) New(_ commondao.ReadonlyCommonDAO, _ any) (commondao.ProposalDefinition, error) {\n\treturn probePropDef{}, nil\n}\n\nfunc init() {\n\tdao = commondao.New(\n\t\tcommondao.WithCouncilMember(member),\n\t\tcommondao.WithProposalKind(probePropKind{}),\n\t)\n\tvar err error\n\tproposal, err = dao.Propose(member, \"probe\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// A single YES from the one-member council passes the proposal early.\n\tif err := dao.Vote(member, proposal.ID(), commondao.ChoiceYes, \"\"); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc main(cur realm) {\n\terr := dao.Execute(proposal.ID(), cur.Sub(\"dao/1\"))\n\n\tprintln(\"outer err nil:\", err == nil)\n\tprintln(\"status:\", string(proposal.Status()))\n\tprintln(\"executor ran once:\", execCount == 1)\n\tprintln(\"active count during executor:\", activeSizeDuringExec)\n}\n\n// Output:\n// outer err nil: true\n// status: executed\n// executor ran once: true\n// active count during executor: 0\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"T7cw3ViX/rUf0g/jDn85lPekFm3v6DpYZBpd0oZgZv0OFIq0LRSFn+0RQnPBuwMlbME79Lw7AjKl0hHv16G5Nw=="}],"memo":""}},{"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":"foreign_test.gno","body":"package foreign\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestForeign_BasicWrap(t *testing.T) {\n\tgot := Foreign(\"hello\")\n\twant := \"\\n\\n\u003cgno-foreign\u003e\\nhello\\n\u003c/gno-foreign\u003e\\n\\n\"\n\tif got != want {\n\t\tt.Errorf(\"got %q, want %q\", got, want)\n\t}\n}\n\nfunc TestForeign_LeadingTrailingBlankLines(t *testing.T) {\n\t// Parser requires a blank line before the opener (CM §4.6). Verify\n\t// the helper emits exactly that.\n\tgot := Foreign(\"body\")\n\tif !strings.HasPrefix(got, \"\\n\\n\u003cgno-foreign\u003e\\n\") {\n\t\tt.Errorf(\"missing blank line before opener: %q\", got)\n\t}\n\tif !strings.HasSuffix(got, \"\\n\u003c/gno-foreign\u003e\\n\\n\") {\n\t\tt.Errorf(\"missing blank line after closer: %q\", got)\n\t}\n}\n\nfunc TestForeign_NormalizesCRLF(t *testing.T) {\n\tgot := Foreign(\"line1\\r\\nline2\\r\\nline3\")\n\tif strings.Contains(got, \"\\r\") {\n\t\tt.Errorf(\"CRLF not normalized: %q\", got)\n\t}\n\tif !strings.Contains(got, \"line1\\nline2\\nline3\") {\n\t\tt.Errorf(\"body content lost: %q\", got)\n\t}\n}\n\nfunc TestForeign_NormalizesBareCR(t *testing.T) {\n\tgot := Foreign(\"line1\\rline2\")\n\tif strings.Contains(got, \"\\r\") {\n\t\tt.Errorf(\"bare CR not normalized: %q\", got)\n\t}\n\tif !strings.Contains(got, \"line1\\nline2\") {\n\t\tt.Errorf(\"body content lost: %q\", got)\n\t}\n}\n\nfunc TestForeign_EscapesSentinelClose(t *testing.T) {\n\t// Unbalanced \u003c/gno-foreign\u003e in body would terminate the outer\n\t// block early. Verify it's escaped to literal text — only the\n\t// leading \"\u003c\" is replaced with \"\u0026lt;\"; the trailing \"\u003e\" stays\n\t// literal (rendering as visible \"\u003e\" in HTML).\n\tgot := Foreign(\"foo\\n\u003c/gno-foreign\u003e\\nbar\")\n\tif strings.Contains(got, \"\\n\u003c/gno-foreign\u003e\\nbar\") {\n\t\tt.Errorf(\"unbalanced close not escaped: %q\", got)\n\t}\n\tif !strings.Contains(got, \"\u0026lt;/gno-foreign\u003e\") {\n\t\tt.Errorf(\"expected escaped close: %q\", got)\n\t}\n}\n\nfunc TestForeign_EscapesSentinelOpen(t *testing.T) {\n\t// A bare opener inside body (without matching close in body)\n\t// would be picked up as a nested inner foreign. Escape it.\n\tgot := Foreign(\"foo\\n\u003cgno-foreign\u003e\\nbar\")\n\tif !strings.Contains(got, \"\\n\u0026lt;gno-foreign\u003e\\n\") {\n\t\tt.Errorf(\"expected escaped inner opener: %q\", got)\n\t}\n}\n\nfunc TestForeign_EscapesIndentedSentinel(t *testing.T) {\n\t// Parser strips 0-3 leading spaces before matching; helper\n\t// must mirror that to catch indented sentinels.\n\tgot := Foreign(\"foo\\n   \u003c/gno-foreign\u003e\\nbar\")\n\tif !strings.Contains(got, \"\u0026lt;/gno-foreign\u003e\") {\n\t\tt.Errorf(\"indented sentinel not escaped: %q\", got)\n\t}\n}\n\nfunc TestForeign_EscapesAttributeBearingOpener(t *testing.T) {\n\t// `\u003cgno-foreign label=\"x\"\u003e` IS recognized by the parser as a\n\t// nested opener. If left unmangled, the parser bumps framingDepth\n\t// when it sees this line in body bytes, and then consumes the\n\t// helper's own outer-close as a fake \"inner close\" — capturing\n\t// realm content that follows the helper's output INTO the\n\t// sandbox. Verify the helper escapes the leading \"\u003c\".\n\tgot := Foreign(`\u003cgno-foreign label=\"x\"\u003e`)\n\tif strings.Contains(got, `\u003cgno-foreign label=\"x\"\u003e`) {\n\t\tt.Errorf(\"attribute-bearing opener was NOT mangled — escape vector:\\n%q\", got)\n\t}\n\tif !strings.Contains(got, `\u0026lt;gno-foreign label=\"x\"\u003e`) {\n\t\tt.Errorf(\"expected leading '\u003c' escaped: %q\", got)\n\t}\n}\n\nfunc TestForeign_EscapesAttributeBearingCloser(t *testing.T) {\n\t// golang.org/x/net/html zeroes the Attr slice on end tags, so the\n\t// parser recognizes ANY `\u003c/gno-foreign attr…\u003e` form as a sentinel\n\t// close. Leaving such a line unmangled in body bytes would close\n\t// the outer block early (framingDepth=0 case in the parser's\n\t// Continue), letting body content that follows render OUTSIDE\n\t// the sandbox at top level. Verify the helper escapes it.\n\tgot := Foreign(`\u003c/gno-foreign label=\"x\"\u003e`)\n\tif strings.Contains(got, `\u003e \u003c/gno-foreign label=\"x\"\u003e \u003c/gno-foreign\u003e`) {\n\t\tt.Errorf(\"attribute-bearing closer was NOT mangled — escape vector:\\n%q\", got)\n\t}\n\tif !strings.Contains(got, `\u0026lt;/gno-foreign label=\"x\"\u003e`) {\n\t\tt.Errorf(\"expected leading '\u003c' escaped: %q\", got)\n\t}\n}\n\nfunc TestForeign_EscapesGnoForeignWithExtraContent(t *testing.T) {\n\t// `\u003cgno-foreign\u003e extra` would not be recognized as a sentinel by\n\t// the parser (tokenizer yields 2 tokens). But the helper is\n\t// over-inclusive on purpose: anything that looks like a\n\t// gno-foreign tag opener or closer gets mangled. Predictable\n\t// behavior beats narrow matching that diverges from the parser\n\t// on attribute-bearing forms.\n\tgot := Foreign(\"\u003cgno-foreign\u003e extra text\")\n\tif !strings.Contains(got, \"\u0026lt;gno-foreign\u003e extra text\") {\n\t\tt.Errorf(\"expected over-inclusive mangle of `\u003cgno-foreign\u003e extra`: %q\", got)\n\t}\n}\n\nfunc TestForeign_EscapesCaseVariantClose(t *testing.T) {\n\t// The renderer-side parser recognizes tags case-insensitively\n\t// (goldmark's tokenizer lowercases tag names). A case-variant close\n\t// left unescaped would terminate the outer block early and let\n\t// trailing body render OUTSIDE the sandbox. The helper must escape\n\t// `\u003c/GNO-FOREIGN\u003e` just like `\u003c/gno-foreign\u003e`.\n\tgot := Foreign(\"foo\\n\u003c/GNO-FOREIGN\u003e\\nbar\")\n\tif strings.Contains(got, \"\\n\u003c/GNO-FOREIGN\u003e\\nbar\") {\n\t\tt.Errorf(\"case-variant close not escaped — sandbox-escape vector: %q\", got)\n\t}\n\tif !strings.Contains(got, \"\u0026lt;/GNO-FOREIGN\u003e\") {\n\t\tt.Errorf(\"expected escaped case-variant close: %q\", got)\n\t}\n}\n\nfunc TestForeign_EscapesCaseVariantOpen(t *testing.T) {\n\t// A case-variant opener left unescaped would be picked up by the\n\t// parser as a nested inner foreign (framingDepth++), causing the\n\t// helper's own outer-close to be consumed as a fake inner close and\n\t// capturing trailing realm content into the sandbox.\n\tgot := Foreign(\"foo\\n\u003cGNO-FOREIGN\u003e\\nbar\")\n\tif !strings.Contains(got, \"\\n\u0026lt;GNO-FOREIGN\u003e\\n\") {\n\t\tt.Errorf(\"case-variant opener not escaped — capture vector: %q\", got)\n\t}\n}\n\nfunc TestForeign_EscapesMixedCaseSentinel(t *testing.T) {\n\t// Mixed-case forms (the most likely hand-crafted evasion) must also\n\t// be caught, including the attribute-bearing mixed-case opener.\n\tfor _, in := range []string{\n\t\t\"\u003cGno-Foreign\u003e\",\n\t\t\"\u003c/Gno-Foreign\u003e\",\n\t\t`\u003cGNO-foreign label=\"x\"\u003e`,\n\t\t\"\u003c/gNo-fOrEiGn\u003e\",\n\t} {\n\t\tgot := Foreign(in)\n\t\tif !strings.Contains(got, \"\u0026lt;\") {\n\t\t\tt.Errorf(\"mixed-case sentinel %q not escaped: %q\", in, got)\n\t\t}\n\t}\n}\n\nfunc TestForeignWithLabel_StripsBidiAndZeroWidth(t *testing.T) {\n\t// A bidi-override (U+202E) or zero-width (U+200C) run in the label\n\t// is invisible-spoof payload; it must be stripped before the label\n\t// is spliced into the opener attribute.\n\tgot := ForeignWithLabel(\"a\\u202eb\\u200cc\", \"body\")\n\tif !strings.Contains(got, `label=\"abc\"`) {\n\t\tt.Errorf(\"expected bidi/zero-width-stripped label: %q\", got)\n\t}\n}\n\nfunc TestForeignWithLabel_UnicodeSeparatorsBecomeSpaces(t *testing.T) {\n\t// U+2028 / U+2029 / U+0085 must not survive in the single-line\n\t// opener attribute; they fold to spaces like ASCII line breaks.\n\tgot := ForeignWithLabel(\"a\\u2028b\\u2029c\\u0085d\", \"body\")\n\tif !strings.Contains(got, `label=\"a b c d\"`) {\n\t\tt.Errorf(\"expected space-folded label: %q\", got)\n\t}\n}\n\nfunc TestForeign_EscapesUnrelatedForeignPrefix(t *testing.T) {\n\t// `\u003cgno-foreignx\u003e` is a different tag the parser would NOT treat as\n\t// a sentinel, but the escaper is deliberately over-inclusive (it\n\t// matches the `\u003cgno-foreign` prefix alone), so it is escaped to\n\t// visible literal text. Harmless, and the safe side of the trade.\n\tgot := Foreign(\"\u003cgno-foreignx\u003e\")\n\tif !strings.Contains(got, \"\u0026lt;gno-foreignx\u003e\") {\n\t\tt.Errorf(\"expected over-inclusive escape of \u003cgno-foreignx\u003e: %q\", got)\n\t}\n}\n\nfunc TestForeign_EscapesSlashAndFormFeedClosers(t *testing.T) {\n\t// REGRESSION: goldmark's tokenizer ends a tag name at `/` and at\n\t// form-feed (both HTML tag-name terminators), so `\u003c/gno-foreign/\u003e`\n\t// and `\u003c/gno-foreign\\f\u003e` are recognized as CLOSERS by the parser. A\n\t// body line carrying one of these, if it reached the parser\n\t// unescaped, would close the outer block early — a sandbox escape.\n\t// The over-inclusive escaper must neutralize every such variant.\n\tfor _, in := range []string{\n\t\t\"foo\\n\u003c/gno-foreign/\u003e\\nbar\",\n\t\t\"foo\\n\u003c/gno-foreign/ \u003e\\nbar\",\n\t\t\"foo\\n\u003c/gno-foreign\\f\u003e\\nbar\",\n\t\t\"foo\\n\u003cgno-foreign/\u003e\\nbar\",\n\t} {\n\t\tgot := Foreign(in)\n\t\tif !strings.Contains(got, \"\u0026lt;\") {\n\t\t\tt.Errorf(\"variant not escaped (sandbox-escape vector): %q -\u003e %q\", in, got)\n\t\t}\n\t}\n}\n\nfunc TestForeign_EmptyBody(t *testing.T) {\n\tgot := Foreign(\"\")\n\twant := \"\\n\\n\u003cgno-foreign\u003e\\n\\n\u003c/gno-foreign\u003e\\n\\n\"\n\tif got != want {\n\t\tt.Errorf(\"got %q, want %q\", got, want)\n\t}\n}\n\nfunc TestForeign_PreservesInternalBlankLines(t *testing.T) {\n\tgot := Foreign(\"para1\\n\\npara2\")\n\tif !strings.Contains(got, \"para1\\n\\npara2\") {\n\t\tt.Errorf(\"internal blank line lost: %q\", got)\n\t}\n}\n\nfunc TestForeignWithLabel_BasicWrap(t *testing.T) {\n\tgot := ForeignWithLabel(\"My Label\", \"body\")\n\twant := \"\\n\\n\u003cgno-foreign label=\\\"My Label\\\"\u003e\\nbody\\n\u003c/gno-foreign\u003e\\n\\n\"\n\tif got != want {\n\t\tt.Errorf(\"got %q, want %q\", got, want)\n\t}\n}\n\nfunc TestForeignWithLabel_EmptyLabelFallsBack(t *testing.T) {\n\t// An empty label (or one that becomes empty after sanitization)\n\t// should be identical to Foreign — no attribute on the opener.\n\tgot := ForeignWithLabel(\"\", \"body\")\n\tif strings.Contains(got, \"label=\") {\n\t\tt.Errorf(\"empty label should not emit attribute: %q\", got)\n\t}\n\tif got != Foreign(\"body\") {\n\t\tt.Errorf(\"empty label should match Foreign: got %q vs %q\", got, Foreign(\"body\"))\n\t}\n}\n\nfunc TestForeignWithLabel_WhitespaceOnlyLabelFallsBack(t *testing.T) {\n\tgot := ForeignWithLabel(\"   \", \"body\")\n\tif strings.Contains(got, \"label=\") {\n\t\tt.Errorf(\"whitespace label should not emit attribute: %q\", got)\n\t}\n}\n\nfunc TestForeignWithLabel_EscapesAmpAndQuote(t *testing.T) {\n\tgot := ForeignWithLabel(`Tom \u0026 \"Jerry\"`, \"body\")\n\tif !strings.Contains(got, `label=\"Tom \u0026amp; \u0026quot;Jerry\u0026quot;\"`) {\n\t\tt.Errorf(\"expected \u0026 and \\\" escaped: %q\", got)\n\t}\n}\n\nfunc TestForeignWithLabel_EscapesAngleBrackets(t *testing.T) {\n\t// An unescaped `\u003e` would close the opener tag early. Must be\n\t// escaped.\n\tgot := ForeignWithLabel(`a\u003cb\u003ec`, \"body\")\n\tif !strings.Contains(got, `label=\"a\u0026lt;b\u0026gt;c\"`) {\n\t\tt.Errorf(\"expected \u003c and \u003e escaped: %q\", got)\n\t}\n}\n\nfunc TestForeignWithLabel_StripsNUL(t *testing.T) {\n\tgot := ForeignWithLabel(\"a\\x00b\\x00c\", \"body\")\n\tif strings.Contains(got, \"\\x00\") {\n\t\tt.Errorf(\"NUL not stripped: %q\", got)\n\t}\n\tif !strings.Contains(got, `label=\"abc\"`) {\n\t\tt.Errorf(\"expected NUL-stripped label: %q\", got)\n\t}\n}\n\nfunc TestForeignWithLabel_ControlCharsBecomeSpaces(t *testing.T) {\n\t// Newlines and tabs would break the single-line opener required\n\t// by the parser. They must become spaces.\n\tgot := ForeignWithLabel(\"line1\\nline2\\ttab\", \"body\")\n\tif strings.Contains(got, \"\\nline2\") || strings.Contains(got, \"\\t\") {\n\t\tt.Errorf(\"control chars not converted: %q\", got)\n\t}\n\tif !strings.Contains(got, \"line1 line2 tab\") {\n\t\tt.Errorf(\"expected space-separated label: %q\", got)\n\t}\n}\n\nfunc TestForeignWithLabel_TrimsLeadingTrailingSpace(t *testing.T) {\n\tgot := ForeignWithLabel(\"  hello  \", \"body\")\n\tif !strings.Contains(got, `label=\"hello\"`) {\n\t\tt.Errorf(\"expected trimmed label: %q\", got)\n\t}\n}\n\nfunc TestForeignWithLabel_PreservesBodyNormalization(t *testing.T) {\n\t// Body normalization (CRLF, sentinel escaping) must still apply\n\t// in the labeled variant.\n\tgot := ForeignWithLabel(\"L\", \"a\\r\\n\u003c/gno-foreign\u003e\\r\\nb\")\n\tif strings.Contains(got, \"\\r\") {\n\t\tt.Errorf(\"CRLF not normalized in labeled variant: %q\", got)\n\t}\n\tif !strings.Contains(got, \"\u0026lt;/gno-foreign\u003e\") {\n\t\tt.Errorf(\"sentinel not escaped in labeled variant: %q\", got)\n\t}\n}\n\nfunc TestMaxBlocksPerRender(t *testing.T) {\n\t// Surfaces gnoweb's per-render foreign-block cap to realms via the\n\t// chain/markdown native. Pin the contract value; bump here if the\n\t// renderer cap changes.\n\tif got := MaxBlocksPerRender(); got != 256 {\n\t\tt.Errorf(\"MaxBlocksPerRender() = %d, want 256\", got)\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/nt/markdown/foreign/v0\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"avNcwJGtfU9RtzTjykMiTTnWzlbpt/Iz3UmclJ5MtJktCKmV3AS5cIDEzvYhOlj/O5XHvwO3u1KlJI0ZPqmBKw=="}],"memo":""}},{"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"},{"name":"mdalert_test.gno","body":"package mdalert_test\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/mdalert/v0\"\n)\n\nfunc TestAlertString(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\texpected string\n\t\talert    mdalert.Alert\n\t}{\n\t\t{\n\t\t\tname:     \"alert\",\n\t\t\texpected: \"\u003e [!INFO] Title\\n\u003e Message\\n\",\n\t\t\talert:    mdalert.New(mdalert.TypeInfo, \"Title\", \"Message\", false),\n\t\t},\n\t\t{\n\t\t\tname:     \"alert with empty title\",\n\t\t\texpected: \"\u003e [!INFO]\\n\u003e Message\\n\",\n\t\t\talert:    mdalert.New(mdalert.TypeInfo, \"\", \"Message\", false),\n\t\t},\n\t\t{\n\t\t\tname:     \"alert multiline\",\n\t\t\texpected: \"\u003e [!INFO]\\n\u003e Line1\\n\u003e Line2\\n\",\n\t\t\talert:    mdalert.New(mdalert.TypeInfo, \"\", \"Line1\\nLine2\", false),\n\t\t},\n\t\t{\n\t\t\tname:     \"folded alert\",\n\t\t\texpected: \"\u003e [!INFO]- Title\\n\u003e Message\\n\",\n\t\t\talert:    mdalert.New(mdalert.TypeInfo, \"Title\", \"Message\", true),\n\t\t},\n\t\t{\n\t\t\tname: \"empty alert\",\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.alert.String()\n\t\t\tif got != tt.expected {\n\t\t\t\tt.Errorf(\"Got:  %q\\nWant: %q\", got, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestHelpers(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\texpected string\n\t\tfn       func() string\n\t}{\n\t\t// CAUTION\n\t\t{\"caution\", \"\u003e [!CAUTION] Title\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Caution(\"Title\", \"Message\")\n\t\t}},\n\t\t{\"caution with empty title\", \"\u003e [!CAUTION]\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Caution(\"\", \"Message\")\n\t\t}},\n\t\t{\"caution multiline\", \"\u003e [!CAUTION] Title\\n\u003e Line1\\n\u003e Line2\\n\", func() string {\n\t\t\treturn mdalert.Caution(\"Title\", \"Line1\\nLine2\")\n\t\t}},\n\t\t{\"caution formatted\", \"\u003e [!CAUTION] Title\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Cautionf(\"Title\", \"%s\", \"Message\")\n\t\t}},\n\t\t{\"caution formatted with empty title\", \"\u003e [!CAUTION]\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Cautionf(\"\", \"%s\", \"Message\")\n\t\t}},\n\t\t{\"caution formatted multiline\", \"\u003e [!CAUTION] Title\\n\u003e Line1\\n\u003e Line2\\n\", func() string {\n\t\t\treturn mdalert.Cautionf(\"Title\", \"%s\\n%s\", \"Line1\", \"Line2\")\n\t\t}},\n\n\t\t// INFO\n\t\t{\"info\", \"\u003e [!INFO] Title\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Info(\"Title\", \"Message\")\n\t\t}},\n\t\t{\"info with empty title\", \"\u003e [!INFO]\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Info(\"\", \"Message\")\n\t\t}},\n\t\t{\"info multiline\", \"\u003e [!INFO] Title\\n\u003e Line1\\n\u003e Line2\\n\", func() string {\n\t\t\treturn mdalert.Info(\"Title\", \"Line1\\nLine2\")\n\t\t}},\n\t\t{\"info formatted\", \"\u003e [!INFO] Title\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Infof(\"Title\", \"%s\", \"Message\")\n\t\t}},\n\t\t{\"info formatted with empty title\", \"\u003e [!INFO]\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Infof(\"\", \"%s\", \"Message\")\n\t\t}},\n\t\t{\"info formatted multiline\", \"\u003e [!INFO] Title\\n\u003e Line1\\n\u003e Line2\\n\", func() string {\n\t\t\treturn mdalert.Infof(\"Title\", \"%s\\n%s\", \"Line1\", \"Line2\")\n\t\t}},\n\n\t\t// NOTE\n\t\t{\"note\", \"\u003e [!NOTE] Title\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Note(\"Title\", \"Message\")\n\t\t}},\n\t\t{\"note with empty title\", \"\u003e [!NOTE]\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Note(\"\", \"Message\")\n\t\t}},\n\t\t{\"note multiline\", \"\u003e [!NOTE] Title\\n\u003e Line1\\n\u003e Line2\\n\", func() string {\n\t\t\treturn mdalert.Note(\"Title\", \"Line1\\nLine2\")\n\t\t}},\n\t\t{\"note formatted\", \"\u003e [!NOTE] Title\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Notef(\"Title\", \"%s\", \"Message\")\n\t\t}},\n\t\t{\"note formatted with empty title\", \"\u003e [!NOTE]\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Notef(\"\", \"%s\", \"Message\")\n\t\t}},\n\t\t{\"note formatted multiline\", \"\u003e [!NOTE] Title\\n\u003e Line1\\n\u003e Line2\\n\", func() string {\n\t\t\treturn mdalert.Notef(\"Title\", \"%s\\n%s\", \"Line1\", \"Line2\")\n\t\t}},\n\n\t\t// SUCCESS\n\t\t{\"success\", \"\u003e [!SUCCESS] Title\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Success(\"Title\", \"Message\")\n\t\t}},\n\t\t{\"success with empty title\", \"\u003e [!SUCCESS]\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Success(\"\", \"Message\")\n\t\t}},\n\t\t{\"success multiline\", \"\u003e [!SUCCESS] Title\\n\u003e Line1\\n\u003e Line2\\n\", func() string {\n\t\t\treturn mdalert.Success(\"Title\", \"Line1\\nLine2\")\n\t\t}},\n\t\t{\"success formatted\", \"\u003e [!SUCCESS] Title\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Successf(\"Title\", \"%s\", \"Message\")\n\t\t}},\n\t\t{\"success formatted with empty title\", \"\u003e [!SUCCESS]\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Successf(\"\", \"%s\", \"Message\")\n\t\t}},\n\t\t{\"success formatted multiline\", \"\u003e [!SUCCESS] Title\\n\u003e Line1\\n\u003e Line2\\n\", func() string {\n\t\t\treturn mdalert.Successf(\"Title\", \"%s\\n%s\", \"Line1\", \"Line2\")\n\t\t}},\n\n\t\t// TIP\n\t\t{\"tip\", \"\u003e [!TIP] Title\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Tip(\"Title\", \"Message\")\n\t\t}},\n\t\t{\"tip with empty title\", \"\u003e [!TIP]\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Tip(\"\", \"Message\")\n\t\t}},\n\t\t{\"tip multiline\", \"\u003e [!TIP] Title\\n\u003e Line1\\n\u003e Line2\\n\", func() string {\n\t\t\treturn mdalert.Tip(\"Title\", \"Line1\\nLine2\")\n\t\t}},\n\t\t{\"tip formatted\", \"\u003e [!TIP] Title\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Tipf(\"Title\", \"%s\", \"Message\")\n\t\t}},\n\t\t{\"tip formatted with empty title\", \"\u003e [!TIP]\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Tipf(\"\", \"%s\", \"Message\")\n\t\t}},\n\t\t{\"tip formatted multiline\", \"\u003e [!TIP] Title\\n\u003e Line1\\n\u003e Line2\\n\", func() string {\n\t\t\treturn mdalert.Tipf(\"Title\", \"%s\\n%s\", \"Line1\", \"Line2\")\n\t\t}},\n\n\t\t// WARNING\n\t\t{\"warning\", \"\u003e [!WARNING] Title\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Warning(\"Title\", \"Message\")\n\t\t}},\n\t\t{\"warning with empty title\", \"\u003e [!WARNING]\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Warning(\"\", \"Message\")\n\t\t}},\n\t\t{\"warning multiline\", \"\u003e [!WARNING] Title\\n\u003e Line1\\n\u003e Line2\\n\", func() string {\n\t\t\treturn mdalert.Warning(\"Title\", \"Line1\\nLine2\")\n\t\t}},\n\t\t{\"warning formatted\", \"\u003e [!WARNING] Title\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Warningf(\"Title\", \"%s\", \"Message\")\n\t\t}},\n\t\t{\"warning formatted with empty title\", \"\u003e [!WARNING]\\n\u003e Message\\n\", func() string {\n\t\t\treturn mdalert.Warningf(\"\", \"%s\", \"Message\")\n\t\t}},\n\t\t{\"warning formatted multiline\", \"\u003e [!WARNING] Title\\n\u003e Line1\\n\u003e Line2\\n\", func() string {\n\t\t\treturn mdalert.Warningf(\"Title\", \"%s\\n%s\", \"Line1\", \"Line2\")\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.fn()\n\t\t\tif got != tt.expected {\n\t\t\t\tt.Errorf(\"Got:  %q\\nWant: %q\", got, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"DwNFSfPfT4fACIZ7ltfu57Y106MFCyh91NjieCCe8xoT5PeoQBD7SaYjPLdG7Cupz2NKp4yduizEQvEsE6jtSQ=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"authorizable","path":"gno.land/p/nt/ownable/v0/exts/authorizable","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/v0/exts/authorizable\"\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":"authorizable_test.gno","body":"package authorizable\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/ownable/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\nvar (\n\talice   = testutils.TestAddress(\"alice\")\n\tbob     = testutils.TestAddress(\"bob\")\n\tcharlie = testutils.TestAddress(\"charlie\")\n)\n\nfunc TestNew(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\ta := New(ownable.NewWithAddress(alice))\n\tgot := a.Owner()\n\n\tif alice != got {\n\t\tt.Fatalf(\"Expected %s, got: %s\", alice, got)\n\t}\n}\n\nfunc TestOnAuthList(cur realm, t *testing.T) {\n\ta := New(ownable.NewWithAddress(alice))\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\t// After SetRealm, cur is the test-frame HIV with addr=alice;\n\t// OnAuthList reports on rlm.Address() (i.e. cur.Address()).\n\tif err := a.OnAuthList(0, cur); err == ErrNotInAuthList {\n\t\tt.Fatalf(\"expected alice to be on the list\")\n\t}\n}\n\nfunc TestNotOnAuthList(cur realm, t *testing.T) {\n\ta := New(ownable.NewWithAddress(alice))\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\n\tif err := a.OnAuthList(0, cur); err == nil {\n\t\tt.Fatalf(\"expected bob to not be on the list\")\n\t}\n}\n\nfunc TestAddToAuthList(cur realm, t *testing.T) {\n\ta := New(ownable.NewWithAddress(alice))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tvar err error\n\tfunc(cur realm) { err = a.AddToAuthList(0, cur, bob) }(cross(cur))\n\tif err != nil {\n\t\tt.Fatalf(\"Expected no error, got %v\", err)\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tfunc(cur realm) { err = a.AddToAuthList(0, cur, bob) }(cross(cur))\n\tif err == nil {\n\t\tt.Fatalf(\"Expected AddToAuth to error while bob called it, but it didn't\")\n\t}\n}\n\nfunc TestDeleteFromList(cur realm, t *testing.T) {\n\ta := New(ownable.NewWithAddress(alice))\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tvar err error\n\tfunc(cur realm) { err = a.AddToAuthList(0, cur, bob) }(cross(cur))\n\tif err != nil {\n\t\tt.Fatalf(\"Expected no error, got %v\", err)\n\t}\n\n\tfunc(cur realm) { err = a.AddToAuthList(0, cur, charlie) }(cross(cur))\n\tif err != nil {\n\t\tt.Fatalf(\"Expected no error, got %v\", err)\n\t}\n\n\t// Try an unauthorized deletion (bob is not the superuser).\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tfunc(cur realm) { err = a.DeleteFromAuthList(0, cur, alice) }(cross(cur))\n\tif err == nil {\n\t\tt.Fatalf(\"Expected DelFromAuth to error with %v\", err)\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tfunc(cur realm) { err = a.DeleteFromAuthList(0, cur, charlie) }(cross(cur))\n\tif err != nil {\n\t\tt.Fatalf(\"Expected no error, got %v\", err)\n\t}\n}\n\nfunc TestAssertOnList(cur realm, t *testing.T) {\n\ta := New(ownable.NewWithAddress(alice))\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\n\tuassert.PanicsWithMessage(t, cur, ErrNotInAuthList.Error(), func() {\n\t\ta.AssertOnAuthList(0, cur)\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/v0/exts/authorizable\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"afH9NDMuzf317iKW2GIhZ2j8Y45nt9l6Hb0EyCV02vgUMiJfHXISc4ccKBsrT37xWQX7RVgaQv5Ec+zgMa0VJg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l","package":{"name":"validators","path":"gno.land/p/sys/validators","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/sys/validators\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"V0ni47NarxRCivNPdQ/eVL9H03j5U/k++RwYMch2eSIt2WXsjEy02ibY7vsbthYg+Ggk/A1bnXmJQJ+f89wTiQ=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g15ge0ae9077eh40erwrn2eq0xw6wupwqthpv34l","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`), 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\"\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`.\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\"\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\"\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"},{"name":"poa_test.gno","body":"package poa\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\t\"gno.land/p/sys/validators\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\n// generateTestValidators generates a dummy validator set\nfunc generateTestValidators(count int) []validators.Validator {\n\tvals := make([]validators.Validator, 0, count)\n\n\tfor i := 0; i \u003c count; i++ {\n\t\tval := validators.Validator{\n\t\t\tAddress:     testutils.TestAddress(ufmt.Sprintf(\"%d\", i)),\n\t\t\tPubKey:      \"public-key\",\n\t\t\tVotingPower: 1,\n\t\t}\n\n\t\tvals = append(vals, val)\n\t}\n\n\treturn vals\n}\n\nfunc TestPoA_AddValidator_Invalid(t *testing.T) {\n\tt.Parallel()\n\n\tt.Run(\"validator already in set\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tvar (\n\t\t\tproposalAddress = testutils.TestAddress(\"caller\")\n\t\t\tproposalKey     = \"public-key\"\n\n\t\t\tinitialSet = generateTestValidators(1)\n\t\t)\n\n\t\tinitialSet[0].Address = proposalAddress\n\t\tinitialSet[0].PubKey = proposalKey\n\n\t\t// Create the protocol with an initial set\n\t\tp := NewPoA(WithInitialSet(initialSet))\n\n\t\t// Attempt to add the validator\n\t\t_, err := p.AddValidator(proposalAddress, proposalKey, 1)\n\t\tuassert.ErrorIs(t, err, validators.ErrValidatorExists)\n\t})\n\n\tt.Run(\"invalid voting power\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tvar (\n\t\t\tproposalAddress = testutils.TestAddress(\"caller\")\n\t\t\tproposalKey     = \"public-key\"\n\t\t)\n\n\t\t// Create the protocol with no initial set\n\t\tp := NewPoA()\n\n\t\t// Attempt to add the validator\n\t\t_, err := p.AddValidator(proposalAddress, proposalKey, 0)\n\t\tuassert.ErrorIs(t, err, ErrInvalidVotingPower)\n\t})\n}\n\nfunc TestPoA_AddValidator(t *testing.T) {\n\tt.Parallel()\n\n\tvar (\n\t\tproposalAddress = testutils.TestAddress(\"caller\")\n\t\tproposalKey     = \"public-key\"\n\t)\n\n\t// Create the protocol with no initial set\n\tp := NewPoA()\n\n\t// Attempt to add the validator\n\t_, err := p.AddValidator(proposalAddress, proposalKey, 1)\n\tuassert.NoError(t, err)\n\n\t// Make sure the validator is added\n\tif !p.IsValidator(proposalAddress) || p.validators.Size() != 1 {\n\t\tt.Fatal(\"address is not validator\")\n\t}\n}\n\nfunc TestPoA_RemoveValidator_Invalid(t *testing.T) {\n\tt.Parallel()\n\n\tt.Run(\"proposed removal not in set\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tvar (\n\t\t\tproposalAddress = testutils.TestAddress(\"caller\")\n\t\t\tinitialSet      = generateTestValidators(1)\n\t\t)\n\n\t\tinitialSet[0].Address = proposalAddress\n\n\t\t// Create the protocol with an initial set\n\t\tp := NewPoA(WithInitialSet(initialSet))\n\n\t\t// Attempt to remove the validator\n\t\t_, err := p.RemoveValidator(testutils.TestAddress(\"totally random\"))\n\t\tuassert.ErrorIs(t, err, validators.ErrValidatorMissing)\n\t})\n}\n\nfunc TestPoA_RemoveValidator(t *testing.T) {\n\tt.Parallel()\n\n\tvar (\n\t\tproposalAddress = testutils.TestAddress(\"caller\")\n\t\tinitialSet      = generateTestValidators(1)\n\t)\n\n\tinitialSet[0].Address = proposalAddress\n\n\t// Create the protocol with an initial set\n\tp := NewPoA(WithInitialSet(initialSet))\n\n\t// Attempt to remove the validator\n\t_, err := p.RemoveValidator(proposalAddress)\n\turequire.NoError(t, err)\n\n\t// Make sure the validator is removed\n\tif p.IsValidator(proposalAddress) || p.validators.Size() != 0 {\n\t\tt.Fatal(\"address is validator\")\n\t}\n}\n\nfunc TestPoA_GetValidator(t *testing.T) {\n\tt.Parallel()\n\n\tt.Run(\"validator not in set\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\t// Create the protocol with no initial set\n\t\tp := NewPoA()\n\n\t\t// Attempt to get the voting power\n\t\t_, err := p.GetValidator(testutils.TestAddress(\"caller\"))\n\t\tuassert.ErrorIs(t, err, validators.ErrValidatorMissing)\n\t})\n\n\tt.Run(\"validator fetched\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tvar (\n\t\t\taddress_XXX = testutils.TestAddress(\"caller\")\n\t\t\tpubKey      = \"public-key\"\n\t\t\tvotingPower = uint64(10)\n\n\t\t\tinitialSet = generateTestValidators(1)\n\t\t)\n\n\t\tinitialSet[0].Address = address_XXX\n\t\tinitialSet[0].PubKey = pubKey\n\t\tinitialSet[0].VotingPower = votingPower\n\n\t\t// Create the protocol with an initial set\n\t\tp := NewPoA(WithInitialSet(initialSet))\n\n\t\t// Get the validator\n\t\tval, err := p.GetValidator(address_XXX)\n\t\turequire.NoError(t, err)\n\n\t\t// Validate the address\n\t\tif val.Address != address_XXX {\n\t\t\tt.Fatal(\"invalid address\")\n\t\t}\n\n\t\t// Validate the voting power\n\t\tif val.VotingPower != votingPower {\n\t\t\tt.Fatal(\"invalid voting power\")\n\t\t}\n\n\t\t// Validate the public key\n\t\tif val.PubKey != pubKey {\n\t\t\tt.Fatal(\"invalid public key\")\n\t\t}\n\t})\n}\n\nfunc TestPoA_GetValidators(t *testing.T) {\n\tt.Parallel()\n\n\tt.Run(\"empty set\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\t// Create the protocol with no initial set\n\t\tp := NewPoA()\n\n\t\t// Attempt to get the voting power\n\t\tvals := p.GetValidators()\n\n\t\tif len(vals) != 0 {\n\t\t\tt.Fatal(\"validator set is not empty\")\n\t\t}\n\t})\n\n\tt.Run(\"validator set fetched\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tinitialSet := generateTestValidators(10)\n\n\t\t// Create the protocol with an initial set\n\t\tp := NewPoA(WithInitialSet(initialSet))\n\n\t\t// Get the validator set\n\t\tvals := p.GetValidators()\n\n\t\tif len(vals) != len(initialSet) {\n\t\t\tt.Fatal(\"returned validator set mismatch\")\n\t\t}\n\n\t\tfor _, val := range vals {\n\t\t\tfor _, initialVal := range initialSet {\n\t\t\t\tif val.Address != initialVal.Address {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Validate the voting power\n\t\t\t\tuassert.Equal(t, val.VotingPower, initialVal.VotingPower)\n\n\t\t\t\t// Validate the public key\n\t\t\t\tuassert.Equal(t, val.PubKey, initialVal.PubKey)\n\t\t\t}\n\t\t}\n\t})\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"9yQL6ESoCLDsnSVnF73Rg8mXIzbTIYDcatWbVlBZ+uwuQGHms/umEtr6Qa1DqjyRNS37n9sut2NVECW8vF06lw=="}],"memo":""}},{"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/demo/tokens/grc20\"\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_canonical_filetest.gno","body":"// PKGPATH: gno.land/r/treasury/canonicaltest\n\npackage canonicaltest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\n\t\"gno.land/p/nt/treasury/v0\"\n)\n\n// evilBanker embeds *treasury.CoinsBanker so it inherits ID/Send/Balances/\n// Address via promotion. If treasury used a sealed-interface marker, this\n// type would satisfy the interface and bypass the gate. The canonical-impl\n// allowlist (IsCanonicalBanker / treasury.New's type switch) rejects it\n// because type assertions are nominal: *evilBanker is not *CoinsBanker.\ntype evilBanker struct {\n\t*treasury.CoinsBanker\n}\n\nfunc main(cur realm) {\n\townerAddr := chain.PackageAddress(\"gno.land/r/treasury/canonicaltest\")\n\n\tinner := banker.NewBanker(banker.BankerTypeRealmSend, cur)\n\tlegit, err := treasury.NewCoinsBankerWithOwner(ownerAddr, inner)\n\tif err != nil {\n\t\tpanic(\"failed to construct canonical banker: \" + err.Error())\n\t}\n\n\t// Verify the helper accepts the canonical impl.\n\tif !treasury.IsCanonicalBanker(legit) {\n\t\tpanic(\"canonical *CoinsBanker must pass IsCanonicalBanker\")\n\t}\n\n\t// Verify the helper rejects an embedded-impl bypass attempt.\n\tevil := \u0026evilBanker{CoinsBanker: legit}\n\tif treasury.IsCanonicalBanker(evil) {\n\t\tpanic(\"embedded-impl wrapper must NOT pass IsCanonicalBanker\")\n\t}\n\n\t// Verify treasury.New rejects the same bypass attempt.\n\t_, err = treasury.New([]treasury.Banker{evil}, \"\")\n\tif err != treasury.ErrNonCanonicalBankerImpl {\n\t\tpanic(\"expected ErrNonCanonicalBankerImpl from treasury.New; got: \" + err.Error())\n\t}\n\n\t// And confirms the canonical banker still works.\n\t_, err = treasury.New([]treasury.Banker{legit}, \"\")\n\tif err != nil {\n\t\tpanic(\"canonical banker must be accepted: \" + err.Error())\n\t}\n\n\tprintln(\"canonical allowlist OK\")\n}\n\n// Output:\n// canonical allowlist OK\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\"\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.\nfunc NewCoinsPayment(coins chain.Coins, toAddress address) Payment {\n\treturn coinsPayment{\n\t\tcoins:     coins,\n\t\ttoAddress: toAddress,\n\t}\n}\n"},{"name":"banker_coins_filetest.gno","body":"// PKGPATH: gno.land/r/treasury/main\n\npackage main\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/treasury/v0\"\n)\n\nfunc main(cur realm) {\n\t// Define addresses for the sender (owner) and destination.\n\townerAddr := chain.PackageAddress(\"gno.land/r/treasury/main\")\n\tdestAddr := chain.PackageAddress(\"gno.land/r/dest/main\")\n\n\t// Create a CoinsBanker.\n\tbanker_ := banker.NewBanker(banker.BankerTypeRealmSend, cur)\n\tcbanker, err := treasury.NewCoinsBankerWithOwner(ownerAddr, banker_)\n\tif err != nil {\n\t\tpanic(\"failed to create CoinsBanker: \" + err.Error())\n\t}\n\n\tprintln(\"CoinsBanker ID:\", cbanker.ID())\n\tprintln(\"CoinsBanker Address:\", cbanker.Address())\n\n\t// Check if the CoinsBanker address matches the owner address.\n\tif cbanker.Address() != ownerAddr.String() {\n\t\tpanic(\"CoinsBanker address does not match current realm address\")\n\t}\n\n\tprintln(\"CoinsBanker Balances count:\", len(cbanker.Balances()))\n\n\t// Issue some coins to the owner address.\n\ttesting.IssueCoins(ownerAddr, chain.NewCoins(chain.NewCoin(\"ugnot\", 42)))\n\n\tprintln(\"CoinsBanker Balances count:\", len(cbanker.Balances()))\n\tprintln(\"Ugnot balance:\", cbanker.Balances()[0].Amount)\n\n\t// Send a valid payment.\n\tvalidPayment := treasury.NewCoinsPayment(\n\t\tchain.NewCoins(chain.NewCoin(\"ugnot\", 10)),\n\t\tdestAddr,\n\t)\n\terr = cbanker.Send(0, cur, validPayment)\n\tprintln(\"Valid payment error:\", err)\n\tif err != nil {\n\t\tpanic(\"failed to send valid payment: \" + err.Error())\n\t}\n\n\tprintln(\"Ugnot balance:\", cbanker.Balances()[0].Amount)\n\n\t// Send a payment with an invalid type.\n\tinvalidPaymentType := treasury.NewGRC20Payment(\"\", 0, destAddr)\n\terr = cbanker.Send(0, cur, invalidPaymentType)\n\tprintln(\"Invalid payment type error:\", err)\n\tif err == nil {\n\t\tpanic(\"expected error for invalid payment type, but got none\")\n\t}\n\n\t// Issue another coin to the owner address to test the Balances method.\n\ttesting.IssueCoins(ownerAddr, chain.NewCoins(chain.NewCoin(\"anothercoin\", 1337)))\n\n\tprintln(\"CoinsBanker Balances count:\", len(cbanker.Balances()))\n}\n\n// Output:\n// CoinsBanker ID: Coins\n// CoinsBanker Address: g1ynsdz5zaxhn9gnqtr6t40m5k4fueeutq7xy224\n// CoinsBanker Balances count: 0\n// CoinsBanker Balances count: 1\n// Ugnot balance: 42\n// Valid payment error: undefined\n// Ugnot balance: 32\n// Invalid payment type error: invalid payment type\n// CoinsBanker Balances count: 2\n"},{"name":"banker_grc20.gno","body":"package treasury\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\n\t\"gno.land/p/demo/tokens/grc20\"\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":"banker_grc20_filetest.gno","body":"// PKGPATH: gno.land/r/treasury/main\n\npackage main\n\nimport (\n\t\"chain\"\n\t\"strings\"\n\n\t\"gno.land/p/demo/tokens/grc20\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/treasury/v0\"\n)\n\nconst amount = int64(1000)\n\nvar nextTokenID seqid.ID\n\nfunc createToken(_ int, rlm realm, name string, toMint address) *grc20.Token {\n\t// Create the token.\n\tsymbol := strings.ToUpper(name)\n\ttoken, ledger := grc20.NewToken(name, symbol, 0, nextTokenID.Next(), rlm)\n\n\t// Mint the requested amount.\n\tledger.Mint(toMint, amount)\n\n\treturn token\n}\n\nfunc main(cur realm) {\n\t// Define addresses for the sender (owner) and destination.\n\townerAddr := chain.PackageAddress(\"gno.land/r/treasury/main\")\n\tdestAddr := chain.PackageAddress(\"gno.land/r/dest/main\")\n\n\t// Try to create a GRC20Banker using a nil lister.\n\tgbanker, err := treasury.NewGRC20BankerWithOwner(ownerAddr, nil)\n\tif err == nil {\n\t\tpanic(\"expected error when creating GRC20Banker with nil lister\")\n\t}\n\n\t// Define a list of token and the associated lister.\n\ttokens := []*grc20.Token{\n\t\tcreateToken(0, cur, \"TestToken0\", ownerAddr),\n\t\tcreateToken(0, cur, \"TestToken1\", ownerAddr),\n\t\tcreateToken(0, cur, \"TestToken2\", ownerAddr),\n\t}\n\n\tgrc20Lister := func() map[string]*grc20.Token {\n\t\ttokensMap := make(map[string]*grc20.Token, len(tokens))\n\n\t\tfor _, token := range tokens {\n\t\t\ttokensMap[token.GetSymbol()] = token\n\t\t}\n\n\t\treturn tokensMap\n\t}\n\n\t// Create a GRC20Banker.\n\tgbanker, err = treasury.NewGRC20BankerWithOwner(ownerAddr, grc20Lister)\n\tif err != nil {\n\t\tpanic(\"failed to create GRC20Banker: \" + err.Error())\n\t}\n\n\tprintln(\"GRC20Banker ID:\", gbanker.ID())\n\tprintln(\"GRC20Banker Address:\", gbanker.Address())\n\n\t// Check if the GRC20Banker address matches the owner address.\n\tif gbanker.Address() != ownerAddr.String() {\n\t\tpanic(\"GRC20Banker address does not match current realm address\")\n\t}\n\n\t// Check the balances of the GRC20Banker.\n\tprintln(\"GRC20Banker Balances count:\", len(gbanker.Balances()))\n\tfor _, balance := range gbanker.Balances() {\n\t\tif balance.Amount != amount {\n\t\t\tpanic(\"GRC20Banker balance does not match expected amount\")\n\t\t}\n\t}\n\n\t// Send a valid payment.\n\ttoken := tokens[len(tokens)-1]\n\tvalidPayment := treasury.NewGRC20Payment(\n\t\ttoken.GetSymbol(),\n\t\t100,\n\t\tdestAddr,\n\t)\n\terr = gbanker.Send(0, cur, validPayment)\n\tprintln(\"Valid payment error:\", err)\n\tif err != nil {\n\t\tpanic(\"failed to send valid payment: \" + err.Error())\n\t}\n\n\tprintln(\"Owner balance:\", token.BalanceOf(ownerAddr))\n\tprintln(\"Dest balance:\", token.BalanceOf(destAddr))\n\n\t// Send an unknown token payment.\n\tunknownPayment := treasury.NewGRC20Payment(\n\t\t\"unknown\",\n\t\t100,\n\t\tdestAddr,\n\t)\n\terr = gbanker.Send(0, cur, unknownPayment)\n\tprintln(\"Unknown token payment error:\", err)\n\tif err == nil {\n\t\tpanic(\"expected error for unknown token, but got none\")\n\t}\n\n\t// Send an unsufficient funds payment.\n\tunsufficientPayment := treasury.NewGRC20Payment(\n\t\ttokens[0].GetSymbol(),\n\t\tamount+1,\n\t\tdestAddr,\n\t)\n\terr = gbanker.Send(0, cur, unsufficientPayment)\n\tprintln(\"Unsufficient funds payment error:\", err)\n\tif err == nil {\n\t\tpanic(\"expected error for insufficient funds, but got none\")\n\t}\n\n\t// Send a payment with an invalid type.\n\tinvalidPaymentType := treasury.NewCoinsPayment(chain.Coins{}, destAddr)\n\terr = gbanker.Send(0, cur, invalidPaymentType)\n\tprintln(\"Invalid payment type error:\", err)\n\tif err == nil {\n\t\tpanic(\"expected error for invalid payment type, but got none\")\n\t}\n}\n\n// Output:\n// GRC20Banker ID: GRC20\n// GRC20Banker Address: g1ynsdz5zaxhn9gnqtr6t40m5k4fueeutq7xy224\n// GRC20Banker Balances count: 3\n// Valid payment error: undefined\n// Owner balance: 900\n// Dest balance: 100\n// Unknown token payment error: GRC20 token not found: unknown\n// Unsufficient funds payment error: insufficient balance\n// Invalid payment type error: invalid payment type\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\"\n\t\"gno.land/p/moul/mdtable\"\n\t\"gno.land/p/nt/bptree/v0/pager\"\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/v0\"\n\t\"gno.land/p/nt/bptree/v0/pager\"\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":"treasury_filetest.gno","body":"// PKGPATH: gno.land/r/treasury/main\n\npackage main\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/demo/tokens/grc20\"\n\t\"gno.land/p/nt/treasury/v0\"\n)\n\nfunc checkBalanceAndHistory(t *treasury.Treasury, bankerIDs []string) {\n\tfor _, bankerID := range bankerIDs {\n\t\tbalances, err := t.Balances(bankerID)\n\t\tif err != nil {\n\t\t\tpanic(\"failed to get banker balances: \" + err.Error())\n\t\t}\n\t\tprintln(\"Banker\", bankerID, \"Balance:\", balances[0].Amount)\n\n\t\thistory, err := t.History(bankerID, 1, 10)\n\t\tif err != nil {\n\t\t\tpanic(\"failed to get banker history: \" + err.Error())\n\t\t}\n\t\tprintln(\"Banker\", bankerID, \"History count:\", len(history))\n\t}\n}\n\nfunc main(cur realm) {\n\t// Define addresses for the sender (owner) and destination.\n\townerAddr := chain.PackageAddress(\"gno.land/r/treasury/main\")\n\tdestAddr := chain.PackageAddress(\"gno.land/r/dest/main\")\n\n\t// Try to create a Treasury instance with no bankers.\n\t_, err := treasury.New(nil, \"\")\n\tif err != treasury.ErrNoBankerProvided {\n\t\tpanic(\"expected error when creating Treasury with no bankers\")\n\t}\n\n\t// Define a token and the associated lister.\n\tconst amount = int64(1000)\n\ttoken, ledger := grc20.NewToken(\"TestToken\", \"TEST\", 0, 0, cur)\n\tledger.Mint(ownerAddr, amount)\n\n\tgrc20Lister := func() map[string]*grc20.Token {\n\t\treturn map[string]*grc20.Token{\n\t\t\t\"TEST\": token,\n\t\t}\n\t}\n\n\t// Try to create a Treasury instance with a duplicate banker.\n\tvar (\n\t\tbanker_           = banker.NewBanker(banker.BankerTypeRealmSend, cur)\n\t\tcoinsBanker, _    = treasury.NewCoinsBankerWithOwner(ownerAddr, banker_)\n\t\tgrc20Banker, _    = treasury.NewGRC20BankerWithOwner(ownerAddr, grc20Lister)\n\t\tgrc20BankerDup, _ = treasury.NewGRC20BankerWithOwner(ownerAddr, grc20Lister)\n\t)\n\n\t_, err = treasury.New([]treasury.Banker{coinsBanker, grc20Banker, grc20BankerDup}, \"\")\n\tif !strings.Contains(err.Error(), treasury.ErrDuplicateBanker.Error()) {\n\t\tpanic(\"expected error when creating Treasury with duplicate banker\")\n\t}\n\n\t// Create a Treasury instance with valid bankers.\n\tbankers := []treasury.Banker{coinsBanker, grc20Banker}\n\tt, err := treasury.New(bankers, \"\")\n\tif err != nil {\n\t\tpanic(\"failed to create Treasury: \" + err.Error())\n\t}\n\n\t// Test if the Treasury instance has the expected bankers.\n\tprintln(\"Treasury banker IDs:\", t.ListBankerIDs())\n\n\tconst unknownBankerID = \"unknown-banker-id\"\n\n\tif t.HasBanker(unknownBankerID) {\n\t\tpanic(\"expected banker not to be found\")\n\t}\n\n\t// Check if the addresses of the bankers matches the owner address.\n\tfor _, banker_ := range bankers {\n\t\taddr, err := t.Address(banker_.ID())\n\t\tif err != nil {\n\t\t\tpanic(\"failed to get banker address: \" + err.Error())\n\t\t}\n\t\tprintln(\"Banker\", banker_.ID(), \"Address:\", addr)\n\t}\n\n\t// Check if the balances and history of the bankers match the expected values.\n\ttesting.IssueCoins(ownerAddr, chain.NewCoins(chain.NewCoin(\"ugnot\", amount)))\n\tbankerIDs := []string{coinsBanker.ID(), grc20Banker.ID()}\n\tcheckBalanceAndHistory(t, bankerIDs)\n\n\t// Send 3 valid payments using the CoinsBanker.\n\tvalidCoinsPayment := treasury.NewCoinsPayment(\n\t\tchain.NewCoins(chain.NewCoin(\"ugnot\", 100)),\n\t\tdestAddr,\n\t)\n\tfor i := 0; i \u003c 3; i++ {\n\t\terr = t.Send(0, cur, validCoinsPayment)\n\t\tif err != nil {\n\t\t\tpanic(\"failed to send valid Coins payment: \" + err.Error())\n\t\t}\n\t}\n\n\t// Send 3 valid payments using the GRC20Banker.\n\tvalidGRC20Payment := treasury.NewGRC20Payment(\n\t\ttoken.GetSymbol(),\n\t\t100,\n\t\tdestAddr,\n\t)\n\tfor i := 0; i \u003c 3; i++ {\n\t\terr = t.Send(0, cur, validGRC20Payment)\n\t\tif err != nil {\n\t\t\tpanic(\"failed to send valid GRC20 payment: \" + err.Error())\n\t\t}\n\t}\n\n\t// Check if the balances and history of the bankers match the expected values.\n\tcheckBalanceAndHistory(t, bankerIDs)\n}\n\n// Output:\n// Treasury banker IDs: slice[(\"Coins\" string),(\"GRC20\" string)]\n// Banker Coins Address: g1ynsdz5zaxhn9gnqtr6t40m5k4fueeutq7xy224\n// Banker GRC20 Address: g1ynsdz5zaxhn9gnqtr6t40m5k4fueeutq7xy224\n// Banker Coins Balance: 1000\n// Banker Coins History count: 0\n// Banker GRC20 Balance: 1000\n// Banker GRC20 History count: 0\n// Banker Coins Balance: 700\n// Banker Coins History count: 3\n// Banker GRC20 Balance: 700\n// Banker GRC20 History count: 3\n"},{"name":"types.gno","body":"package treasury\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/bptree/v0/list\"\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// 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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"EtQPWKZWAIKu/npuBN4ji3ZboA3j9K0D1U5oZbgxCvRgVogFmEzdz+uWeVL/dtCyOFKRp5c5HjRvIj/iN2pwCw=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"uint256","path":"gno.land/p/onbloc/uint256","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":"arithmetic_test.gno","body":"package uint256\n\nimport (\n\t\"testing\"\n)\n\ntype binOp2Test struct {\n\tx, y, want string\n}\n\nfunc TestAdd(t *testing.T) {\n\ttests := []binOp2Test{\n\t\t{\"0\", \"1\", \"1\"},\n\t\t{\"1\", \"0\", \"1\"},\n\t\t{\"1\", \"1\", \"2\"},\n\t\t{\"1\", \"3\", \"4\"},\n\t\t{\"10\", \"10\", \"20\"},\n\t\t{\"18446744073709551615\", \"18446744073709551615\", \"36893488147419103230\"}, // uint64 overflow\n\t}\n\n\tfor _, tt := range tests {\n\t\tx := MustFromDecimal(tt.x)\n\t\ty := MustFromDecimal(tt.y)\n\n\t\twant := MustFromDecimal(tt.want)\n\t\tgot := new(Uint).Add(x, y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"Add(%s, %s) = %v, want %v\", tt.x, tt.y, got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestAddOverflow(t *testing.T) {\n\ttests := []struct {\n\t\tx, y     string\n\t\twant     string\n\t\toverflow bool\n\t}{\n\t\t{\"0\", \"1\", \"1\", false},\n\t\t{\"1\", \"0\", \"1\", false},\n\t\t{\"1\", \"1\", \"2\", false},\n\t\t{\"10\", \"10\", \"20\", false},\n\t\t{\"18446744073709551615\", \"18446744073709551615\", \"36893488147419103230\", false},                    // uint64 overflow, but not Uint256 overflow\n\t\t{\"115792089237316195423570985008687907853269984665640564039457584007913129639935\", \"1\", \"0\", true}, // 2^256 - 1 + 1, should overflow\n\t\t{\"57896044618658097711785492504343953926634992332820282019728792003956564819967\", \"57896044618658097711785492504343953926634992332820282019728792003956564819968\", \"115792089237316195423570985008687907853269984665640564039457584007913129639935\", false}, // (2^255 - 1) + 2^255, no overflow\n\t\t{\"57896044618658097711785492504343953926634992332820282019728792003956564819967\", \"57896044618658097711785492504343953926634992332820282019728792003956564819969\", \"0\", true},                                                                               // (2^255 - 1) + (2^255 + 1), should overflow\n\t}\n\n\tfor _, tt := range tests {\n\t\tx := MustFromDecimal(tt.x)\n\t\ty := MustFromDecimal(tt.y)\n\t\twant, _ := FromDecimal(tt.want)\n\n\t\tgot, overflow := new(Uint).AddOverflow(x, y)\n\n\t\tif got.Cmp(want) != 0 || overflow != tt.overflow {\n\t\t\tt.Errorf(\"AddOverflow(%s, %s) = (%s, %v), want (%s, %v)\",\n\t\t\t\ttt.x, tt.y, got.String(), overflow, tt.want, tt.overflow)\n\t\t}\n\t}\n}\n\nfunc TestSub(t *testing.T) {\n\ttests := []binOp2Test{\n\t\t{\"1\", \"0\", \"1\"},\n\t\t{\"1\", \"1\", \"0\"},\n\t\t{\"10\", \"10\", \"0\"},\n\t\t{\"31337\", \"1337\", \"30000\"},\n\t\t{\"2\", \"3\", twoPow256Sub1}, // underflow\n\t}\n\n\tfor _, tc := range tests {\n\t\tx := MustFromDecimal(tc.x)\n\t\ty := MustFromDecimal(tc.y)\n\n\t\twant := MustFromDecimal(tc.want)\n\n\t\tgot := new(Uint).Sub(x, y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\n\t\t\t\t\"Sub(%s, %s) = %v, want %v\",\n\t\t\t\ttc.x, tc.y, got.String(), want.String(),\n\t\t\t)\n\t\t}\n\t}\n}\n\nfunc TestSubOverflow(t *testing.T) {\n\ttests := []struct {\n\t\tx, y     string\n\t\twant     string\n\t\toverflow bool\n\t}{\n\t\t{\"1\", \"0\", \"1\", false},\n\t\t{\"1\", \"1\", \"0\", false},\n\t\t{\"10\", \"10\", \"0\", false},\n\t\t{\"31337\", \"1337\", \"30000\", false},\n\t\t{\"0\", \"1\", \"115792089237316195423570985008687907853269984665640564039457584007913129639935\", true},                                                                                                                                                         // 0 - 1, should underflow\n\t\t{\"57896044618658097711785492504343953926634992332820282019728792003956564819968\", \"1\", \"57896044618658097711785492504343953926634992332820282019728792003956564819967\", false},                                                                             // 2^255 - 1, no underflow\n\t\t{\"57896044618658097711785492504343953926634992332820282019728792003956564819968\", \"57896044618658097711785492504343953926634992332820282019728792003956564819969\", \"115792089237316195423570985008687907853269984665640564039457584007913129639935\", true}, // 2^255 - (2^255 + 1), should underflow\n\t}\n\n\tfor _, tc := range tests {\n\t\tx := MustFromDecimal(tc.x)\n\t\ty := MustFromDecimal(tc.y)\n\t\twant := MustFromDecimal(tc.want)\n\n\t\tgot, overflow := new(Uint).SubOverflow(x, y)\n\n\t\tif got.Cmp(want) != 0 || overflow != tc.overflow {\n\t\t\tt.Errorf(\n\t\t\t\t\"SubOverflow(%s, %s) = (%s, %v), want (%s, %v)\",\n\t\t\t\ttc.x, tc.y, got.String(), overflow, tc.want, tc.overflow,\n\t\t\t)\n\t\t}\n\t}\n}\n\nfunc TestMul(t *testing.T) {\n\ttests := []binOp2Test{\n\t\t{\"1\", \"0\", \"0\"},\n\t\t{\"1\", \"1\", \"1\"},\n\t\t{\"10\", \"10\", \"100\"},\n\t\t{\"18446744073709551615\", \"2\", \"36893488147419103230\"}, // uint64 overflow\n\t}\n\n\tfor _, tt := range tests {\n\t\tx := MustFromDecimal(tt.x)\n\t\ty := MustFromDecimal(tt.y)\n\t\twant := MustFromDecimal(tt.want)\n\t\tgot := new(Uint).Mul(x, y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"Mul(%s, %s) = %v, want %v\", tt.x, tt.y, got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestMulOverflow(t *testing.T) {\n\ttests := []struct {\n\t\tx        string\n\t\ty        string\n\t\twantZ    string\n\t\twantOver bool\n\t}{\n\t\t{\"0x1\", \"0x1\", \"0x1\", false},\n\t\t{\"0x0\", \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"0x0\", false},\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"0x2\", \"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe\", true},\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"0x1\", true},\n\t\t{\"0x8000000000000000000000000000000000000000000000000000000000000000\", \"0x2\", \"0x0\", true},\n\t\t{\"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"0x2\", \"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe\", false},\n\t\t{\"0x100000000000000000\", \"0x100000000000000000\", \"0x10000000000000000000000000000000000\", false},\n\t\t{\"0x10000000000000000000000000000000\", \"0x10000000000000000000000000000000\", \"0x100000000000000000000000000000000000000000000000000000000000000\", false},\n\t}\n\n\tfor _, tt := range tests {\n\t\tx := MustFromHex(tt.x)\n\t\ty := MustFromHex(tt.y)\n\t\twantZ := MustFromHex(tt.wantZ)\n\n\t\tgotZ, gotOver := new(Uint).MulOverflow(x, y)\n\n\t\tif gotZ.Neq(wantZ) {\n\t\t\tt.Errorf(\n\t\t\t\t\"MulOverflow(%s, %s) = %s, want %s\",\n\t\t\t\ttt.x, tt.y, gotZ.String(), wantZ.String(),\n\t\t\t)\n\t\t}\n\t\tif gotOver != tt.wantOver {\n\t\t\tt.Errorf(\"MulOverflow(%s, %s) = %v, want %v\", tt.x, tt.y, gotOver, tt.wantOver)\n\t\t}\n\t}\n}\n\nfunc TestDiv(t *testing.T) {\n\ttests := []binOp2Test{\n\t\t{\"31337\", \"3\", \"10445\"},\n\t\t{\"31337\", \"0\", \"0\"},\n\t\t{\"0\", \"31337\", \"0\"},\n\t\t{\"1\", \"1\", \"1\"},\n\t\t{\"1000000000000000000\", \"3\", \"333333333333333333\"},\n\t\t{twoPow256Sub1, \"2\", \"57896044618658097711785492504343953926634992332820282019728792003956564819967\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tx := MustFromDecimal(tt.x)\n\t\ty := MustFromDecimal(tt.y)\n\t\twant := MustFromDecimal(tt.want)\n\n\t\tgot := new(Uint).Div(x, y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"Div(%s, %s) = %v, want %v\", tt.x, tt.y, got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestMod(t *testing.T) {\n\ttests := []binOp2Test{\n\t\t{\"31337\", \"3\", \"2\"},\n\t\t{\"31337\", \"0\", \"0\"},\n\t\t{\"0\", \"31337\", \"0\"},\n\t\t{\"2\", \"31337\", \"2\"},\n\t\t{\"1\", \"1\", \"0\"},\n\t\t{\"115792089237316195423570985008687907853269984665640564039457584007913129639935\", \"2\", \"1\"}, // 2^256 - 1 mod 2\n\t\t{\"115792089237316195423570985008687907853269984665640564039457584007913129639935\", \"3\", \"0\"}, // 2^256 - 1 mod 3\n\t\t{\"115792089237316195423570985008687907853269984665640564039457584007913129639935\", \"57896044618658097711785492504343953926634992332820282019728792003956564819968\", \"57896044618658097711785492504343953926634992332820282019728792003956564819967\"}, // 2^256 - 1 mod 2^255\n\t}\n\n\tfor _, tt := range tests {\n\t\tx := MustFromDecimal(tt.x)\n\t\ty := MustFromDecimal(tt.y)\n\t\twant := MustFromDecimal(tt.want)\n\n\t\tgot := new(Uint).Mod(x, y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"Mod(%s, %s) = %v, want %v\", tt.x, tt.y, got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestMulMod(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\ty    string\n\t\tm    string\n\t\twant string\n\t}{\n\t\t{\"0x1\", \"0x1\", \"0x2\", \"0x1\"},\n\t\t{\"0x10\", \"0x10\", \"0x7\", \"0x4\"},\n\t\t{\"0x100\", \"0x100\", \"0x17\", \"0x9\"},\n\t\t{\"0x31337\", \"0x31337\", \"0x31338\", \"0x1\"},\n\t\t{\"0x0\", \"0x31337\", \"0x31338\", \"0x0\"},\n\t\t{\"0x31337\", \"0x0\", \"0x31338\", \"0x0\"},\n\t\t{\"0x2\", \"0x3\", \"0x5\", \"0x1\"},\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"0x0\"},\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe\", \"0x1\"},\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"0xffffffffffffffffffffffffffffffff\", \"0x0\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tx := MustFromHex(tt.x)\n\t\ty := MustFromHex(tt.y)\n\t\tm := MustFromHex(tt.m)\n\t\twant := MustFromHex(tt.want)\n\n\t\tgot := new(Uint).MulMod(x, y, m)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\n\t\t\t\t\"MulMod(%s, %s, %s) = %s, want %s\",\n\t\t\t\ttt.x, tt.y, tt.m, got.String(), want.String(),\n\t\t\t)\n\t\t}\n\t}\n}\n\nfunc TestDivMod(t *testing.T) {\n\ttests := []struct {\n\t\tx       string\n\t\ty       string\n\t\twantDiv string\n\t\twantMod string\n\t}{\n\t\t{\"1\", \"1\", \"1\", \"0\"},\n\t\t{\"10\", \"10\", \"1\", \"0\"},\n\t\t{\"100\", \"10\", \"10\", \"0\"},\n\t\t{\"31337\", \"3\", \"10445\", \"2\"},\n\t\t{\"31337\", \"0\", \"0\", \"0\"},\n\t\t{\"0\", \"31337\", \"0\", \"0\"},\n\t\t{\"2\", \"31337\", \"0\", \"2\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tx := MustFromDecimal(tt.x)\n\t\ty := MustFromDecimal(tt.y)\n\t\twantDiv := MustFromDecimal(tt.wantDiv)\n\t\twantMod := MustFromDecimal(tt.wantMod)\n\n\t\tgotDiv := new(Uint)\n\t\tgotMod := new(Uint)\n\t\tgotDiv.DivMod(x, y, gotMod)\n\n\t\tfor i := range gotDiv.arr {\n\t\t\tif gotDiv.arr[i] != wantDiv.arr[i] {\n\t\t\t\tt.Errorf(\"DivMod(%s, %s) got Div %v, want Div %v\", tt.x, tt.y, gotDiv, wantDiv)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tfor i := range gotMod.arr {\n\t\t\tif gotMod.arr[i] != wantMod.arr[i] {\n\t\t\t\tt.Errorf(\"DivMod(%s, %s) got Mod %v, want Mod %v\", tt.x, tt.y, gotMod, wantMod)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestNeg(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\twant string\n\t}{\n\t\t{\"31337\", \"115792089237316195423570985008687907853269984665640564039457584007913129608599\"},\n\t\t{\"115792089237316195423570985008687907853269984665640564039457584007913129608599\", \"31337\"},\n\t\t{\"0\", \"0\"},\n\t\t{\"2\", \"115792089237316195423570985008687907853269984665640564039457584007913129639934\"},\n\t\t{\"1\", twoPow256Sub1},\n\t}\n\n\tfor _, tt := range tests {\n\t\tx := MustFromDecimal(tt.x)\n\t\twant := MustFromDecimal(tt.want)\n\n\t\tgot := new(Uint).Neg(x)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"Neg(%s) = %v, want %v\", tt.x, got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestExp(t *testing.T) {\n\ttests := []binOp2Test{\n\t\t{\"31337\", \"3\", \"30773171189753\"},\n\t\t{\"31337\", \"0\", \"1\"},\n\t\t{\"0\", \"31337\", \"0\"},\n\t\t{\"1\", \"1\", \"1\"},\n\t\t{\"2\", \"3\", \"8\"},\n\t\t{\"2\", \"64\", \"18446744073709551616\"},\n\t\t{\"2\", \"128\", \"340282366920938463463374607431768211456\"},\n\t\t{\"2\", \"255\", \"57896044618658097711785492504343953926634992332820282019728792003956564819968\"},\n\t\t{\"2\", \"256\", \"0\"}, // overflow\n\t}\n\n\tfor _, tt := range tests {\n\t\tx := MustFromDecimal(tt.x)\n\t\ty := MustFromDecimal(tt.y)\n\t\twant := MustFromDecimal(tt.want)\n\n\t\tgot := new(Uint).Exp(x, y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\n\t\t\t\t\"Exp(%s, %s) = %v, want %v\",\n\t\t\t\ttt.x, tt.y, got.String(), want.String(),\n\t\t\t)\n\t\t}\n\t}\n}\n\nfunc TestExp_LargeExponent(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tbase     string\n\t\texponent string\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"2^129\",\n\t\t\tbase:     \"2\",\n\t\t\texponent: \"680564733841876926926749214863536422912\",\n\t\t\texpected: \"0\",\n\t\t},\n\t\t{\n\t\t\tname:     \"2^193\",\n\t\t\tbase:     \"2\",\n\t\t\texponent: \"12379400392853802746563808384000000000000000000\",\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\tbase := MustFromDecimal(tt.base)\n\t\t\texponent := MustFromDecimal(tt.exponent)\n\t\t\texpected := MustFromDecimal(tt.expected)\n\n\t\t\tresult := new(Uint).Exp(base, exponent)\n\n\t\t\tif result.Neq(expected) {\n\t\t\t\tt.Errorf(\n\t\t\t\t\t\"Test %s failed. Expected %s, got %s\",\n\t\t\t\t\ttt.name, expected.String(), result.String(),\n\t\t\t\t)\n\t\t\t}\n\t\t})\n\t}\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":"bitwise_test.gno","body":"package uint256\n\nimport \"testing\"\n\ntype logicOpTest struct {\n\tname string\n\tx    Uint\n\ty    Uint\n\twant Uint\n}\n\nfunc TestOr(t *testing.T) {\n\ttests := []logicOpTest{\n\t\t{\n\t\t\tname: \"all zeros\",\n\t\t\tx:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\ty:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\twant: Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t},\n\t\t{\n\t\t\tname: \"all ones\",\n\t\t\tx:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\ty:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\twant: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t},\n\t\t{\n\t\t\tname: \"mixed\",\n\t\t\tx:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), 0, 0}},\n\t\t\ty:    Uint{arr: [4]uint64{0, 0, ^uint64(0), ^uint64(0)}},\n\t\t\twant: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t},\n\t\t{\n\t\t\tname: \"one operand all ones\",\n\t\t\tx:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\ty:    Uint{arr: [4]uint64{0x5555555555555555, 0xAAAAAAAAAAAAAAAA, 0xFFFFFFFFFFFFFFFF, 0x0000000000000000}},\n\t\t\twant: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(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\tres := new(Uint).Or(\u0026tt.x, \u0026tt.y)\n\t\t\tif *res != tt.want {\n\t\t\t\tt.Errorf(\n\t\t\t\t\t\"Or(%s, %s) = %s, want %s\",\n\t\t\t\t\ttt.x.String(), tt.y.String(), res.String(), (tt.want).String(),\n\t\t\t\t)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestAnd(t *testing.T) {\n\ttests := []logicOpTest{\n\t\t{\n\t\t\tname: \"all zeros\",\n\t\t\tx:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\ty:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\twant: Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t},\n\t\t{\n\t\t\tname: \"all ones\",\n\t\t\tx:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\ty:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\twant: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t},\n\t\t{\n\t\t\tname: \"mixed\",\n\t\t\tx:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\ty:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\twant: Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t},\n\t\t{\n\t\t\tname: \"mixed 2\",\n\t\t\tx:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\ty:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\twant: Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t},\n\t\t{\n\t\t\tname: \"mixed 3\",\n\t\t\tx:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), 0, 0}},\n\t\t\ty:    Uint{arr: [4]uint64{0, 0, ^uint64(0), ^uint64(0)}},\n\t\t\twant: Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t},\n\t\t{\n\t\t\tname: \"one operand zero\",\n\t\t\tx:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\ty:    Uint{arr: [4]uint64{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}},\n\t\t\twant: Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t},\n\t\t{\n\t\t\tname: \"one operand all ones\",\n\t\t\tx:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\ty:    Uint{arr: [4]uint64{0x5555555555555555, 0xAAAAAAAAAAAAAAAA, 0xFFFFFFFFFFFFFFFF, 0x0000000000000000}},\n\t\t\twant: Uint{arr: [4]uint64{0x5555555555555555, 0xAAAAAAAAAAAAAAAA, 0xFFFFFFFFFFFFFFFF, 0x0000000000000000}},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tres := new(Uint).And(\u0026tt.x, \u0026tt.y)\n\t\t\tif *res != tt.want {\n\t\t\t\tt.Errorf(\n\t\t\t\t\t\"And(%s, %s) = %s, want %s\",\n\t\t\t\t\ttt.x.String(), tt.y.String(), res.String(), (tt.want).String(),\n\t\t\t\t)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNot(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tx    Uint\n\t\twant Uint\n\t}{\n\t\t{\n\t\t\tname: \"all zeros\",\n\t\t\tx:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\twant: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t},\n\t\t{\n\t\t\tname: \"all ones\",\n\t\t\tx:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\twant: Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t},\n\t\t{\n\t\t\tname: \"mixed\",\n\t\t\tx:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), 0, 0}},\n\t\t\twant: Uint{arr: [4]uint64{0, 0, ^uint64(0), ^uint64(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\tres := new(Uint).Not(\u0026tt.x)\n\t\t\tif *res != tt.want {\n\t\t\t\tt.Errorf(\n\t\t\t\t\t\"Not(%s) = %s, want %s\",\n\t\t\t\t\ttt.x.String(), res.String(), (tt.want).String(),\n\t\t\t\t)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestAndNot(t *testing.T) {\n\ttests := []logicOpTest{\n\t\t{\n\t\t\tname: \"all zeros\",\n\t\t\tx:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\ty:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\twant: Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t},\n\t\t{\n\t\t\tname: \"all ones\",\n\t\t\tx:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\ty:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\twant: Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t},\n\t\t{\n\t\t\tname: \"mixed\",\n\t\t\tx:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\ty:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\twant: Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t},\n\t\t{\n\t\t\tname: \"mixed 2\",\n\t\t\tx:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\ty:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\twant: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t},\n\t\t{\n\t\t\tname: \"mixed 3\",\n\t\t\tx:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), 0, 0}},\n\t\t\ty:    Uint{arr: [4]uint64{0, 0, ^uint64(0), ^uint64(0)}},\n\t\t\twant: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), 0, 0}},\n\t\t},\n\t\t{\n\t\t\tname: \"one operand zero\",\n\t\t\tx:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\ty:    Uint{arr: [4]uint64{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}},\n\t\t\twant: Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t},\n\t\t{\n\t\t\tname: \"one operand all ones\",\n\t\t\tx:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\ty:    Uint{arr: [4]uint64{0x5555555555555555, 0xAAAAAAAAAAAAAAAA, 0xFFFFFFFFFFFFFFFF, 0x0000000000000000}},\n\t\t\twant: Uint{arr: [4]uint64{0xAAAAAAAAAAAAAAAA, 0x5555555555555555, 0x0000000000000000, ^uint64(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\tres := new(Uint).AndNot(\u0026tt.x, \u0026tt.y)\n\t\t\tif *res != tt.want {\n\t\t\t\tt.Errorf(\n\t\t\t\t\t\"AndNot(%s, %s) = %s, want %s\",\n\t\t\t\t\ttt.x.String(), tt.y.String(), res.String(), (tt.want).String(),\n\t\t\t\t)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestXor(t *testing.T) {\n\ttests := []logicOpTest{\n\t\t{\n\t\t\tname: \"all zeros\",\n\t\t\tx:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\ty:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\twant: Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t},\n\t\t{\n\t\t\tname: \"all ones\",\n\t\t\tx:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\ty:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\twant: Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t},\n\t\t{\n\t\t\tname: \"mixed\",\n\t\t\tx:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\ty:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\twant: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t},\n\t\t{\n\t\t\tname: \"mixed 2\",\n\t\t\tx:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\ty:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\twant: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t},\n\t\t{\n\t\t\tname: \"mixed 3\",\n\t\t\tx:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), 0, 0}},\n\t\t\ty:    Uint{arr: [4]uint64{0, 0, ^uint64(0), ^uint64(0)}},\n\t\t\twant: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t},\n\t\t{\n\t\t\tname: \"one operand zero\",\n\t\t\tx:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\ty:    Uint{arr: [4]uint64{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}},\n\t\t\twant: Uint{arr: [4]uint64{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}},\n\t\t},\n\t\t{\n\t\t\tname: \"one operand all ones\",\n\t\t\tx:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\ty:    Uint{arr: [4]uint64{0x5555555555555555, 0xAAAAAAAAAAAAAAAA, 0xFFFFFFFFFFFFFFFF, 0x0000000000000000}},\n\t\t\twant: Uint{arr: [4]uint64{0xAAAAAAAAAAAAAAAA, 0x5555555555555555, 0x0000000000000000, ^uint64(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\tres := new(Uint).Xor(\u0026tt.x, \u0026tt.y)\n\t\t\tif *res != tt.want {\n\t\t\t\tt.Errorf(\n\t\t\t\t\t\"Xor(%s, %s) = %s, want %s\",\n\t\t\t\t\ttt.x.String(), tt.y.String(), res.String(), (tt.want).String(),\n\t\t\t\t)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestLsh(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\ty    uint\n\t\twant string\n\t}{\n\t\t{\"0\", 0, \"0\"},\n\t\t{\"0\", 1, \"0\"},\n\t\t{\"0\", 64, \"0\"},\n\t\t{\"1\", 0, \"1\"},\n\t\t{\"1\", 1, \"2\"},\n\t\t{\"1\", 64, \"18446744073709551616\"},\n\t\t{\"1\", 128, \"340282366920938463463374607431768211456\"},\n\t\t{\"1\", 192, \"6277101735386680763835789423207666416102355444464034512896\"},\n\t\t{\"1\", 255, \"57896044618658097711785492504343953926634992332820282019728792003956564819968\"},\n\t\t{\"1\", 256, \"0\"},\n\t\t{\"31337\", 0, \"31337\"},\n\t\t{\"31337\", 1, \"62674\"},\n\t\t{\"31337\", 64, \"578065619037836218990592\"},\n\t\t{\"31337\", 128, \"10663428532201448629551770073089320442396672\"},\n\t\t{\"31337\", 192, \"196705537081812415096322133155058642481399512563169449530621952\"},\n\t\t{\"31337\", 193, \"393411074163624830192644266310117284962799025126338899061243904\"},\n\t\t{\"31337\", 255, \"57896044618658097711785492504343953926634992332820282019728792003956564819968\"},\n\t\t{\"31337\", 256, \"0\"},\n\t\t// 64 \u003c n \u003c 128\n\t\t{\"1\", 65, \"36893488147419103232\"},\n\t\t{\"31337\", 100, \"39724366859352024754702188346867712\"},\n\n\t\t// 128 \u003c n \u003c 192\n\t\t{\"1\", 129, \"680564733841876926926749214863536422912\"},\n\t\t{\"31337\", 150, \"44725660946326664792723507424638829088826130956288\"},\n\n\t\t// 192 \u003c n \u003c 256\n\t\t{\"1\", 193, \"12554203470773361527671578846415332832204710888928069025792\"},\n\t\t{\"31337\", 200, \"50356617492943978264658466087695012475238275216171379079839219712\"},\n\n\t\t// n \u003e 256\n\t\t{\"1\", 257, \"0\"},\n\t\t{\"31337\", 300, \"0\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tx := MustFromDecimal(tt.x)\n\t\twant := MustFromDecimal(tt.want)\n\n\t\tgot := new(Uint).Lsh(x, tt.y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"Lsh(%s, %d) = %s, want %s\", tt.x, tt.y, got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestRsh(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\ty    uint\n\t\twant string\n\t}{\n\t\t{\"0\", 0, \"0\"},\n\t\t{\"0\", 1, \"0\"},\n\t\t{\"0\", 64, \"0\"},\n\t\t{\"1\", 0, \"1\"},\n\t\t{\"1\", 1, \"0\"},\n\t\t{\"1\", 64, \"0\"},\n\t\t{\"1\", 128, \"0\"},\n\t\t{\"1\", 192, \"0\"},\n\t\t{\"1\", 255, \"0\"},\n\t\t{\"57896044618658097711785492504343953926634992332820282019728792003956564819968\", 255, \"1\"},\n\t\t{\"6277101735386680763835789423207666416102355444464034512896\", 192, \"1\"},\n\t\t{\"340282366920938463463374607431768211456\", 128, \"1\"},\n\t\t{\"18446744073709551616\", 64, \"1\"},\n\t\t{\"393411074163624830192644266310117284962799025126338899061243904\", 193, \"31337\"},\n\t\t{\"196705537081812415096322133155058642481399512563169449530621952\", 192, \"31337\"},\n\t\t{\"10663428532201448629551770073089320442396672\", 128, \"31337\"},\n\t\t{\"578065619037836218990592\", 64, \"31337\"},\n\t\t{twoPow256Sub1, 256, \"0\"},\n\t\t// outliers\n\t\t{\"340282366920938463463374607431768211455\", 129, \"0\"},\n\t\t{\"18446744073709551615\", 65, \"0\"},\n\t\t{twoPow256Sub1, 1, \"57896044618658097711785492504343953926634992332820282019728792003956564819967\"},\n\n\t\t// n \u003e 256\n\t\t{\"1\", 257, \"0\"},\n\t\t{\"31337\", 300, \"0\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tx := MustFromDecimal(tt.x)\n\n\t\twant := MustFromDecimal(tt.want)\n\t\tgot := new(Uint).Rsh(x, tt.y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"Rsh(%s, %d) = %s, want %s\", tt.x, tt.y, got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestSRsh(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\ty    uint\n\t\twant string\n\t}{\n\t\t// Positive numbers (behaves like Rsh)\n\t\t{\"0x0\", 0, \"0x0\"},\n\t\t{\"0x0\", 1, \"0x0\"},\n\t\t{\"0x1\", 0, \"0x1\"},\n\t\t{\"0x1\", 1, \"0x0\"},\n\t\t{\"0x31337\", 0, \"0x31337\"},\n\t\t{\"0x31337\", 4, \"0x3133\"},\n\t\t{\"0x31337\", 8, \"0x313\"},\n\t\t{\"0x31337\", 16, \"0x3\"},\n\t\t{\"0x10000000000000000\", 64, \"0x1\"}, // 2^64 \u003e\u003e 64\n\n\t\t// // Numbers with MSB set (negative numbers in two's complement)\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 0, \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"},\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 1, \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"},\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 4, \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"},\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 64, \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"},\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 128, \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"},\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 192, \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"},\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 255, \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"},\n\n\t\t// Large positive number close to max value\n\t\t{\"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 1, \"0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"},\n\t\t{\"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 2, \"0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"},\n\t\t{\"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 64, \"0x7fffffffffffffffffffffffffffffffffffffffffffffff\"},\n\t\t{\"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 128, \"0x7fffffffffffffffffffffffffffffff\"},\n\t\t{\"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 192, \"0x7fffffffffffffff\"},\n\t\t{\"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 255, \"0x0\"},\n\n\t\t// Specific cases\n\t\t{\"0x8000000000000000000000000000000000000000000000000000000000000000\", 1, \"0xc000000000000000000000000000000000000000000000000000000000000000\"},\n\t\t{\"0x8000000000000000000000000000000000000000000000000000000000000001\", 1, \"0xc000000000000000000000000000000000000000000000000000000000000000\"},\n\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 65, \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"},\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 127, \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"},\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 129, \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"},\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 193, \"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"},\n\n\t\t// n \u003e 256\n\t\t{\"0x1\", 257, \"0x0\"},\n\t\t{\"0x31337\", 300, \"0x0\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tx := MustFromHex(tt.x)\n\t\twant := MustFromHex(tt.want)\n\n\t\tgot := new(Uint).SRsh(x, tt.y)\n\n\t\tif !got.Eq(want) {\n\t\t\tt.Errorf(\"SRsh(%s, %d) = %s, want %s\", tt.x, tt.y, got.String(), want.String())\n\t\t}\n\t}\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":"cmp_test.gno","body":"package uint256\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestSign(t *testing.T) {\n\ttests := []struct {\n\t\tinput    *Uint\n\t\texpected int\n\t}{\n\t\t{\n\t\t\tinput:    NewUint(0),\n\t\t\texpected: 0,\n\t\t},\n\t\t{\n\t\t\tinput:    NewUint(1),\n\t\t\texpected: 1,\n\t\t},\n\t\t{\n\t\t\tinput:    NewUint(0x7fffffffffffffff),\n\t\t\texpected: 1,\n\t\t},\n\t\t{\n\t\t\tinput:    NewUint(0x8000000000000000),\n\t\t\texpected: 1,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.input.String(), func(t *testing.T) {\n\t\t\tresult := tt.input.Sign()\n\t\t\tif result != tt.expected {\n\t\t\t\tt.Errorf(\"Sign() = %d; want %d\", result, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCmp(t *testing.T) {\n\ttests := []struct {\n\t\tx, y string\n\t\twant int\n\t}{\n\t\t{\"0\", \"0\", 0},\n\t\t{\"0\", \"1\", -1},\n\t\t{\"1\", \"0\", 1},\n\t\t{\"1\", \"1\", 0},\n\t\t{\"10\", \"10\", 0},\n\t\t{\"10\", \"11\", -1},\n\t\t{\"11\", \"10\", 1},\n\t}\n\n\tfor _, tc := range tests {\n\t\tx := MustFromDecimal(tc.x)\n\t\ty := MustFromDecimal(tc.y)\n\n\t\tgot := x.Cmp(y)\n\t\tif got != tc.want {\n\t\t\tt.Errorf(\"Cmp(%s, %s) = %v, want %v\", tc.x, tc.y, got, tc.want)\n\t\t}\n\t}\n}\n\nfunc TestIsZero(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\twant bool\n\t}{\n\t\t{\"0\", true},\n\t\t{\"1\", false},\n\t\t{\"10\", false},\n\t}\n\n\tfor _, tt := range tests {\n\t\tx := MustFromDecimal(tt.x)\n\n\t\tgot := x.IsZero()\n\t\tif got != tt.want {\n\t\t\tt.Errorf(\"IsZero(%s) = %v, want %v\", tt.x, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestLtUint64(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\ty    uint64\n\t\twant bool\n\t}{\n\t\t{\"0\", 1, true},\n\t\t{\"1\", 0, false},\n\t\t{\"10\", 10, false},\n\t\t{\"0xffffffffffffffff\", 0, false},\n\t\t{\"0x10000000000000000\", 10000000000000000, false},\n\t}\n\n\tfor _, tc := range tests {\n\t\tx := parseTestString(t, tc.x)\n\n\t\tgot := x.LtUint64(tc.y)\n\t\tif got != tc.want {\n\t\t\tt.Errorf(\"LtUint64(%s, %d) = %v, want %v\", tc.x, tc.y, got, tc.want)\n\t\t}\n\t}\n}\n\nfunc TestUint_GtUint64(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tz    string\n\t\tn    uint64\n\t\twant bool\n\t}{\n\t\t{\n\t\t\tname: \"z \u003e n\",\n\t\t\tz:    \"1\",\n\t\t\tn:    0,\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"z \u003c n\",\n\t\t\tz:    \"18446744073709551615\",\n\t\t\tn:    0xFFFFFFFFFFFFFFFF,\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"z == n\",\n\t\t\tz:    \"18446744073709551615\",\n\t\t\tn:    0xFFFFFFFFFFFFFFFF,\n\t\t\twant: 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\tz := MustFromDecimal(tt.z)\n\n\t\t\tif got := z.GtUint64(tt.n); got != tt.want {\n\t\t\t\tt.Errorf(\"Uint.GtUint64() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestSGT(t *testing.T) {\n\tx := MustFromHex(\"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe\")\n\ty := MustFromHex(\"0x0\")\n\tactual := x.Sgt(y)\n\tif actual {\n\t\tt.Fatalf(\"Expected %v false\", actual)\n\t}\n\n\tx = MustFromHex(\"0x0\")\n\ty = MustFromHex(\"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe\")\n\tactual = x.Sgt(y)\n\tif !actual {\n\t\tt.Fatalf(\"Expected %v true\", actual)\n\t}\n}\n\nfunc TestEq(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\ty    string\n\t\twant bool\n\t}{\n\t\t{\"0xffffffffffffffff\", \"18446744073709551615\", true},\n\t\t{\"0x10000000000000000\", \"18446744073709551616\", true},\n\t\t{\"0\", \"0\", true},\n\t\t{twoPow256Sub1, twoPow256Sub1, true},\n\t}\n\n\tfor _, tt := range tests {\n\t\tx := parseTestString(t, tt.x)\n\n\t\ty, err := FromDecimal(tt.y)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgot := x.Eq(y)\n\n\t\tif got != tt.want {\n\t\t\tt.Errorf(\"Eq(%s, %s) = %v, want %v\", tt.x, tt.y, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestUint_Lte(t *testing.T) {\n\ttests := []struct {\n\t\tz, x string\n\t\twant bool\n\t}{\n\t\t{\"10\", \"20\", true},\n\t\t{\"20\", \"10\", false},\n\t\t{\"10\", \"10\", true},\n\t\t{\"0\", \"0\", true},\n\t}\n\n\tfor _, tt := range tests {\n\t\tz, err := FromDecimal(tt.z)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\t\tx, err := FromDecimal(tt.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\t\tif got := z.Lte(x); got != tt.want {\n\t\t\tt.Errorf(\"Uint.Lte(%v, %v) = %v, want %v\", tt.z, tt.x, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestUint_Gte(t *testing.T) {\n\ttests := []struct {\n\t\tz, x string\n\t\twant bool\n\t}{\n\t\t{\"20\", \"10\", true},\n\t\t{\"10\", \"20\", false},\n\t\t{\"10\", \"10\", true},\n\t\t{\"0\", \"0\", true},\n\t}\n\n\tfor _, tt := range tests {\n\t\tz := parseTestString(t, tt.z)\n\t\tx := parseTestString(t, tt.x)\n\n\t\tif got := z.Gte(x); got != tt.want {\n\t\t\tt.Errorf(\"Uint.Gte(%v, %v) = %v, want %v\", tt.z, tt.x, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc parseTestString(_ *testing.T, s string) *Uint {\n\tvar x *Uint\n\n\tif strings.HasPrefix(s, \"0x\") {\n\t\tx = MustFromHex(s)\n\t} else {\n\t\tx = MustFromDecimal(s)\n\t}\n\n\treturn x\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":"conversion_test.gno","body":"package uint256\n\nimport \"testing\"\n\nfunc TestIsUint64(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\twant bool\n\t}{\n\t\t{\"0x0\", true},\n\t\t{\"0x1\", true},\n\t\t{\"0x10\", true},\n\t\t{\"0xffffffffffffffff\", true},\n\t\t{\"0x10000000000000000\", false},\n\t}\n\n\tfor _, tt := range tests {\n\t\tx := MustFromHex(tt.x)\n\t\tgot := x.IsUint64()\n\n\t\tif got != tt.want {\n\t\t\tt.Errorf(\"IsUint64(%s) = %v, want %v\", tt.x, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestDec(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tz    Uint\n\t\twant string\n\t}{\n\t\t{\n\t\t\tname: \"zero\",\n\t\t\tz:    Uint{arr: [4]uint64{0, 0, 0, 0}},\n\t\t\twant: \"0\",\n\t\t},\n\t\t{\n\t\t\tname: \"less than 20 digits\",\n\t\t\tz:    Uint{arr: [4]uint64{1234567890, 0, 0, 0}},\n\t\t\twant: \"1234567890\",\n\t\t},\n\t\t{\n\t\t\tname: \"max possible value\",\n\t\t\tz:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},\n\t\t\twant: twoPow256Sub1,\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 := tt.z.Dec()\n\t\t\tif result != tt.want {\n\t\t\t\tt.Errorf(\"Dec(%v) = %s, want %s\", tt.z, result, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestUint_Scan(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tinput   any\n\t\twant    *Uint\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname:  \"nil\",\n\t\t\tinput: nil,\n\t\t\twant:  NewUint(0),\n\t\t},\n\t\t{\n\t\t\tname:  \"valid scientific notation\",\n\t\t\tinput: \"1e4\",\n\t\t\twant:  NewUint(10000),\n\t\t},\n\t\t{\n\t\t\tname:  \"valid decimal string\",\n\t\t\tinput: \"12345\",\n\t\t\twant:  NewUint(12345),\n\t\t},\n\t\t{\n\t\t\tname:  \"valid byte slice\",\n\t\t\tinput: []byte(\"12345\"),\n\t\t\twant:  NewUint(12345),\n\t\t},\n\t\t{\n\t\t\tname:    \"invalid string\",\n\t\t\tinput:   \"invalid\",\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"out of range\",\n\t\t\tinput:   \"115792089237316195423570985008687907853269984665640564039457584007913129639936\", // 2^256\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"unsupported type\",\n\t\t\tinput:   123,\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\tz := new(Uint)\n\t\t\terr := z.Scan(tt.input)\n\n\t\t\tif tt.wantErr {\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Errorf(\"Scan() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"Scan() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t\t}\n\t\t\t\tif !z.Eq(tt.want) {\n\t\t\t\t\tt.Errorf(\"Scan() = %v, want %v\", z, tt.want)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestSetBytes(t *testing.T) {\n\ttests := []struct {\n\t\tinput    []byte\n\t\texpected string\n\t}{\n\t\t{[]byte{}, \"0\"},\n\t\t{[]byte{0x01}, \"1\"},\n\t\t{[]byte{0x12, 0x34}, \"4660\"},\n\t\t{[]byte{0x12, 0x34, 0x56}, \"1193046\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78}, \"305419896\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a}, \"78187493530\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc}, \"20015998343868\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde}, \"5124095576030430\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}, \"1311768467463790320\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12}, \"335812727670730321938\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34}, \"85968058283706962416180\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56}, \"22007822920628982378542166\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78}, \"5634002667681019488906794616\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a}, \"1442304682926340989160139421850\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc}, \"369229998829143293224995691993788\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde}, \"94522879700260683065598897150409950\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}, \"24197857203266734864793317670504947440\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12}, \"6194651444036284125387089323649266544658\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34}, \"1585830769673288736099094866854212235432500\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56}, \"405972677036361916441368285914678332270720086\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78}, \"103929005321308650608990281194157653061304342136\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a}, \"26605825362255014555901511985704359183693911586970\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc}, \"6811091292737283726310787068340315951025641366264508\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde}, \"1743639370940744633935561489495120883462564189763714270\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}, \"446371678960830626287503741310750946166416432579510853360\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12}, \"114271149813972640329600957775552242218602606740354778460178\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34}, \"29253414352376995924377845190541374007962267325530823285805620\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56}, \"7488874074208510956640728368778591746038340435335890761166238806\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78}, \"1917151762997378804900026462407319486985815151445988034858557134456\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a}, \"490790851327328974054406774376273788668368678770172936923790626420890\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc}, \"125642457939796217357928134240326089899102381765164271852490400363748028\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde}, \"32164469232587831643629602365523479014170209731882053594237542493119495390\"},\n\t\t{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}, \"8234104123542484900769178205574010627627573691361805720124810878238590820080\"},\n\t\t// over 32 bytes (last 32 bytes are used)\n\t\t{append([]byte{0xff}, []byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}...), \"8234104123542484900769178205574010627627573691361805720124810878238590820080\"},\n\t}\n\n\tfor _, test := range tests {\n\t\tz := new(Uint)\n\t\tz.SetBytes(test.input)\n\t\texpected := MustFromDecimal(test.expected)\n\t\tif z.Cmp(expected) != 0 {\n\t\t\tt.Errorf(\"SetBytes(%x) = %s, expected %s\", test.input, z.String(), test.expected)\n\t\t}\n\t}\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\"\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":"uint256_test.gno","body":"package uint256\n\nimport (\n\t\"testing\"\n)\n\nfunc TestSetAllOne(t *testing.T) {\n\tz := Zero()\n\tz.SetAllOne()\n\tif z.String() != twoPow256Sub1 {\n\t\tt.Errorf(\"Expected all ones, got %s\", z.String())\n\t}\n}\n\nfunc TestByte(t *testing.T) {\n\ttests := []struct {\n\t\tinput    string\n\t\tposition uint64\n\t\texpected byte\n\t}{\n\t\t{\"0x1000000000000000000000000000000000000000000000000000000000000000\", 0, 16},\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 0, 255},\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 31, 255},\n\t}\n\n\tfor i, tt := range tests {\n\t\tz, _ := FromHex(tt.input)\n\t\tn := NewUint(tt.position)\n\t\tresult := z.Byte(n)\n\n\t\tif result.arr[0] != uint64(tt.expected) {\n\t\t\tt.Errorf(\"Test case %d failed. Input: %s, Position: %d, Expected: %d, Got: %d\",\n\t\t\t\ti, tt.input, tt.position, tt.expected, result.arr[0])\n\t\t}\n\n\t\t// check other array elements are 0\n\t\tif result.arr[1] != 0 || result.arr[2] != 0 || result.arr[3] != 0 {\n\t\t\tt.Errorf(\"Test case %d failed. Non-zero values in upper bytes\", i)\n\t\t}\n\t}\n\n\t// overflow\n\tz, _ := FromHex(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\")\n\tn := NewUint(32)\n\tresult := z.Byte(n)\n\n\tif !result.IsZero() {\n\t\tt.Errorf(\"Expected zero for position \u003e= 32, got %v\", result)\n\t}\n}\n\nfunc TestBitLen(t *testing.T) {\n\ttests := []struct {\n\t\tinput    string\n\t\texpected int\n\t}{\n\t\t{\"0x0\", 0},\n\t\t{\"0x1\", 1},\n\t\t{\"0xff\", 8},\n\t\t{\"0x100\", 9},\n\t\t{\"0xffff\", 16},\n\t\t{\"0x10000\", 17},\n\t\t{\"0xffffffffffffffff\", 64},\n\t\t{\"0x10000000000000000\", 65},\n\t\t{\"0xffffffffffffffffffffffffffffffff\", 128},\n\t\t{\"0x100000000000000000000000000000000\", 129},\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 256},\n\t}\n\n\tfor i, tt := range tests {\n\t\tz, _ := FromHex(tt.input)\n\t\tresult := z.BitLen()\n\n\t\tif result != tt.expected {\n\t\t\tt.Errorf(\"Test case %d failed. Input: %s, Expected: %d, Got: %d\",\n\t\t\t\ti, tt.input, tt.expected, result)\n\t\t}\n\t}\n}\n\nfunc TestByteLen(t *testing.T) {\n\ttests := []struct {\n\t\tinput    string\n\t\texpected int\n\t}{\n\t\t{\"0x0\", 0},\n\t\t{\"0x1\", 1},\n\t\t{\"0xff\", 1},\n\t\t{\"0x100\", 2},\n\t\t{\"0xffff\", 2},\n\t\t{\"0x10000\", 3},\n\t\t{\"0xffffffffffffffff\", 8},\n\t\t{\"0x10000000000000000\", 9},\n\t\t{\"0xffffffffffffffffffffffffffffffff\", 16},\n\t\t{\"0x100000000000000000000000000000000\", 17},\n\t\t{\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 32},\n\t}\n\n\tfor i, tt := range tests {\n\t\tz, _ := FromHex(tt.input)\n\t\tresult := z.ByteLen()\n\n\t\tif result != tt.expected {\n\t\t\tt.Errorf(\"Test case %d failed. Input: %s, Expected: %d, Got: %d\",\n\t\t\t\ti, tt.input, tt.expected, result)\n\t\t}\n\t}\n}\n\nfunc TestClone(t *testing.T) {\n\ttests := []struct {\n\t\tinput    string\n\t\texpected string\n\t}{\n\t\t{\"0x1\", \"1\"},\n\t\t{\"0x100\", \"256\"},\n\t\t{\"0x10000000000000000\", \"18446744073709551616\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tz, _ := FromHex(tt.input)\n\t\tresult := z.Clone()\n\t\tif result.String() != tt.expected {\n\t\t\tt.Errorf(\"Test %s failed. Expected %s, got %s\", tt.input, tt.expected, result.String())\n\t\t}\n\t}\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"bOzV68mPBBvulcykVUexGAwKto51jbdin9cN/62mTkV0dqTUhSitN+MkXz1NnubBJn7wrqxE3wPQ+zFppD9OKw=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"int256","path":"gno.land/p/onbloc/int256","files":[{"name":"arithmetic.gno","body":"package int256\n\nimport (\n\t\"gno.land/p/onbloc/uint256\"\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":"arithmetic_test.gno","body":"package int256\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/onbloc/uint256\"\n)\n\nconst (\n\t// 2^255 - 1\n\tMAX_INT256 = \"57896044618658097711785492504343953926634992332820282019728792003956564819967\"\n\t// -(2^255 - 1)\n\tMINUS_MAX_INT256 = \"-57896044618658097711785492504343953926634992332820282019728792003956564819967\"\n\n\t// 2^255 - 1\n\tMAX_UINT256         = \"115792089237316195423570985008687907853269984665640564039457584007913129639935\"\n\tMAX_UINT256_MINUS_1 = \"115792089237316195423570985008687907853269984665640564039457584007913129639934\"\n\n\tMINUS_MAX_UINT256        = \"-115792089237316195423570985008687907853269984665640564039457584007913129639935\"\n\tMINUS_MAX_UINT256_PLUS_1 = \"-115792089237316195423570985008687907853269984665640564039457584007913129639934\"\n\n\tTWO_POW_128               = \"340282366920938463463374607431768211456\"\n\tMINUS_TWO_POW_128         = \"-340282366920938463463374607431768211456\"\n\tMINUS_TWO_POW_128_MINUS_1 = \"-340282366920938463463374607431768211457\"\n\tTWO_POW_128_MINUS_1       = \"340282366920938463463374607431768211455\"\n\n\tTWO_POW_129_MINUS_1 = \"680564733841876926926749214863536422911\"\n\n\tTWO_POW_254           = \"28948022309329048855892746252171976963317496166410141009864396001978282409984\"\n\tMINUS_TWO_POW_254     = \"-28948022309329048855892746252171976963317496166410141009864396001978282409984\"\n\tHALF_MAX_INT256       = \"28948022309329048855892746252171976963317496166410141009864396001978282409983\"\n\tMINUS_HALF_MAX_INT256 = \"-28948022309329048855892746252171976963317496166410141009864396001978282409983\"\n\n\tTWO_POW_255        = \"57896044618658097711785492504343953926634992332820282019728792003956564819968\"\n\tMIN_INT256         = \"-57896044618658097711785492504343953926634992332820282019728792003956564819968\"\n\tMIN_INT256_MINUS_1 = \"-57896044618658097711785492504343953926634992332820282019728792003956564819969\"\n)\n\nfunc TestAdd(t *testing.T) {\n\ttests := []struct {\n\t\tx, y, want string\n\t}{\n\t\t{\"0\", \"1\", \"1\"},\n\t\t{\"1\", \"0\", \"1\"},\n\t\t{\"1\", \"1\", \"2\"},\n\t\t{\"1\", \"2\", \"3\"},\n\t\t// NEGATIVE\n\t\t{\"-1\", \"1\", \"0\"},\n\t\t{\"1\", \"-1\", \"0\"},\n\t\t{\"3\", \"-3\", \"0\"},\n\t\t{\"-1\", \"-1\", \"-2\"},\n\t\t{\"-1\", \"-2\", \"-3\"},\n\t\t{\"-1\", \"3\", \"2\"},\n\t\t{\"3\", \"-1\", \"2\"},\n\t\t// OVERFLOW\n\t\t{MAX_UINT256, \"1\", \"0\"},\n\t\t{MAX_INT256, \"1\", MIN_INT256},\n\t\t{MIN_INT256, \"-1\", MAX_INT256},\n\t\t{MAX_INT256, MAX_INT256, \"-2\"},\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, err := FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\ty, err := FromDecimal(tc.y)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\twant, err := FromDecimal(tc.want)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgot := New()\n\t\tgot.Add(x, y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"Add(%s, %s) = %v, want %v\", tc.x, tc.y, got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestAddUint256(t *testing.T) {\n\ttests := []struct {\n\t\tx, y, want string\n\t}{\n\t\t{\"0\", \"1\", \"1\"},\n\t\t{\"1\", \"0\", \"1\"},\n\t\t{\"1\", \"1\", \"2\"},\n\t\t{\"1\", \"2\", \"3\"},\n\t\t{\"-1\", \"1\", \"0\"},\n\t\t{\"-1\", \"3\", \"2\"},\n\t\t{MINUS_MAX_UINT256_PLUS_1, MAX_UINT256, \"1\"},\n\t\t{MINUS_MAX_UINT256, MAX_UINT256_MINUS_1, \"-1\"},\n\t\t// OVERFLOW\n\t\t{MINUS_MAX_UINT256, MAX_UINT256, \"0\"},\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, err := FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\ty, err := uint256.FromDecimal(tc.y)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\twant, err := FromDecimal(tc.want)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgot := New()\n\t\tgot.AddUint256(x, y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"AddUint256(%s, %s) = %v, want %v\", tc.x, tc.y, got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestAddDelta(t *testing.T) {\n\ttests := []struct {\n\t\tz, x, y, want string\n\t}{\n\t\t{\"0\", \"0\", \"0\", \"0\"},\n\t\t{\"0\", \"0\", \"1\", \"1\"},\n\t\t{\"0\", \"1\", \"0\", \"1\"},\n\t\t{\"0\", \"1\", \"1\", \"2\"},\n\t\t{\"1\", \"2\", \"3\", \"5\"},\n\t\t{\"5\", \"10\", \"-3\", \"7\"},\n\t\t// underflow\n\t\t{\"1\", \"2\", \"-3\", MAX_UINT256},\n\t}\n\n\tfor _, tc := range tests {\n\t\tz, err := uint256.FromDecimal(tc.z)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tx, err := uint256.FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\ty, err := FromDecimal(tc.y)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\twant, err := uint256.FromDecimal(tc.want)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tAddDelta(z, x, y)\n\n\t\tif z.Neq(want) {\n\t\t\tt.Errorf(\"AddDelta(%s, %s, %s) = %v, want %v\", tc.z, tc.x, tc.y, z.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestAddDeltaOverflow(t *testing.T) {\n\ttests := []struct {\n\t\tz, x, y string\n\t\twant    bool\n\t}{\n\t\t{\"0\", \"0\", \"0\", false},\n\t\t// underflow\n\t\t{\"1\", \"2\", \"-3\", true},\n\t}\n\n\tfor _, tc := range tests {\n\t\tz, err := uint256.FromDecimal(tc.z)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tx, err := uint256.FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\ty, err := FromDecimal(tc.y)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tresult := AddDeltaOverflow(z, x, y)\n\t\tif result != tc.want {\n\t\t\tt.Errorf(\"AddDeltaOverflow(%s, %s, %s) = %v, want %v\", tc.z, tc.x, tc.y, result, tc.want)\n\t\t}\n\t}\n}\n\nfunc TestSub(t *testing.T) {\n\ttests := []struct {\n\t\tx, y, want string\n\t}{\n\t\t{\"1\", \"0\", \"1\"},\n\t\t{\"1\", \"1\", \"0\"},\n\t\t{\"-1\", \"1\", \"-2\"},\n\t\t{\"1\", \"-1\", \"2\"},\n\t\t{\"-1\", \"-1\", \"0\"},\n\t\t{MINUS_MAX_UINT256, MINUS_MAX_UINT256, \"0\"},\n\t\t{MINUS_MAX_UINT256, \"0\", MINUS_MAX_UINT256},\n\t\t{MAX_INT256, MIN_INT256, \"-1\"},\n\t\t{MIN_INT256, MIN_INT256, \"0\"},\n\t\t{MAX_INT256, MAX_INT256, \"0\"},\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, err := FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\ty, err := FromDecimal(tc.y)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\twant, err := FromDecimal(tc.want)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgot := New()\n\t\tgot.Sub(x, y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"Sub(%s, %s) = %v, want %v\", tc.x, tc.y, got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestSubUint256(t *testing.T) {\n\ttests := []struct {\n\t\tx, y, want string\n\t}{\n\t\t{\"0\", \"1\", \"-1\"},\n\t\t{\"1\", \"0\", \"1\"},\n\t\t{\"1\", \"1\", \"0\"},\n\t\t{\"1\", \"2\", \"-1\"},\n\t\t{\"-1\", \"1\", \"-2\"},\n\t\t{\"-1\", \"3\", \"-4\"},\n\t\t// underflow\n\t\t{MINUS_MAX_UINT256, \"1\", \"0\"},\n\t\t{MINUS_MAX_UINT256, \"2\", \"-1\"},\n\t\t{MINUS_MAX_UINT256, \"3\", \"-2\"},\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, err := FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\ty, err := uint256.FromDecimal(tc.y)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\twant, err := FromDecimal(tc.want)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgot := New()\n\t\tgot.SubUint256(x, y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"SubUint256(%s, %s) = %v, want %v\", tc.x, tc.y, got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestMul(t *testing.T) {\n\ttests := []struct {\n\t\tx, y, want string\n\t}{\n\t\t{\"5\", \"3\", \"15\"},\n\t\t{\"-5\", \"3\", \"-15\"},\n\t\t{\"5\", \"-3\", \"-15\"},\n\t\t{\"0\", \"3\", \"0\"},\n\t\t{\"3\", \"0\", \"0\"},\n\t\t{\"-5\", \"-3\", \"15\"},\n\t\t{MAX_UINT256, \"1\", MAX_UINT256},\n\t\t{MAX_INT256, \"2\", \"-2\"},\n\t\t{TWO_POW_254, \"2\", MIN_INT256},\n\t\t{MINUS_TWO_POW_254, \"2\", MIN_INT256},\n\t\t{MAX_INT256, \"1\", MAX_INT256},\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, err := FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\ty, err := FromDecimal(tc.y)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\twant, err := FromDecimal(tc.want)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgot := New()\n\t\tgot.Mul(x, y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"Mul(%s, %s) = %v, want %v\", tc.x, tc.y, got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestDiv(t *testing.T) {\n\ttests := []struct {\n\t\tx, y, expected string\n\t}{\n\t\t{\"1\", \"1\", \"1\"},\n\t\t{\"0\", \"1\", \"0\"},\n\t\t{\"-1\", \"1\", \"-1\"},\n\t\t{\"1\", \"-1\", \"-1\"},\n\t\t{\"-1\", \"-1\", \"1\"},\n\t\t{\"-6\", \"3\", \"-2\"},\n\t\t{\"10\", \"-2\", \"-5\"},\n\t\t{\"-10\", \"3\", \"-3\"},\n\t\t{\"7\", \"3\", \"2\"},\n\t\t{\"-7\", \"3\", \"-2\"},\n\t\t// the maximum value of a positive number in int256 is less than the maximum value of a uint256\n\t\t{MAX_INT256, \"2\", HALF_MAX_INT256},\n\t\t{MINUS_MAX_INT256, \"2\", MINUS_HALF_MAX_INT256},\n\t\t{MAX_INT256, \"-1\", MINUS_MAX_INT256},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.x+\"/\"+tt.y, func(t *testing.T) {\n\t\t\tx := MustFromDecimal(tt.x)\n\t\t\ty := MustFromDecimal(tt.y)\n\t\t\tresult := Zero().Div(x, y)\n\t\t\tif result.String() != tt.expected {\n\t\t\t\tt.Errorf(\"Div(%s, %s) = %s, want %s\", tt.x, tt.y, result.String(), tt.expected)\n\t\t\t}\n\t\t})\n\t}\n\n\tt.Run(\"Division by zero\", func(t *testing.T) {\n\t\tdefer func() {\n\t\t\tif r := recover(); r == nil {\n\t\t\t\tt.Errorf(\"Div(1, 0) did not panic\")\n\t\t\t}\n\t\t}()\n\t\tx := MustFromDecimal(\"1\")\n\t\ty := MustFromDecimal(\"0\")\n\t\tZero().Div(x, y)\n\t})\n}\n\nfunc TestQuo(t *testing.T) {\n\ttests := []struct {\n\t\tx, y, want string\n\t}{\n\t\t{\"0\", \"1\", \"0\"},\n\t\t{\"0\", \"-1\", \"0\"},\n\t\t{\"10\", \"1\", \"10\"},\n\t\t{\"10\", \"-1\", \"-10\"},\n\t\t{\"-10\", \"1\", \"-10\"},\n\t\t{\"-10\", \"-1\", \"10\"},\n\t\t{\"10\", \"-3\", \"-3\"},\n\t\t{\"-10\", \"3\", \"-3\"},\n\t\t{\"10\", \"3\", \"3\"},\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, err := FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\ty, err := FromDecimal(tc.y)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\twant, err := FromDecimal(tc.want)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgot := New()\n\t\tgot.Quo(x, y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"Quo(%s, %s) = %v, want %v\", tc.x, tc.y, got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestRem(t *testing.T) {\n\ttests := []struct {\n\t\tx, y, want string\n\t}{\n\t\t{\"0\", \"1\", \"0\"},\n\t\t{\"0\", \"-1\", \"0\"},\n\t\t{\"10\", \"1\", \"0\"},\n\t\t{\"10\", \"-1\", \"0\"},\n\t\t{\"-10\", \"1\", \"0\"},\n\t\t{\"-10\", \"-1\", \"0\"},\n\t\t{\"10\", \"3\", \"1\"},\n\t\t{\"10\", \"-3\", \"1\"},\n\t\t{\"-10\", \"3\", \"-1\"},\n\t\t{\"-10\", \"-3\", \"-1\"},\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, err := FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\ty, err := FromDecimal(tc.y)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\twant, err := FromDecimal(tc.want)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgot := New()\n\t\tgot.Rem(x, y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"Rem(%s, %s) = %v, want %v\", tc.x, tc.y, got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestMod(t *testing.T) {\n\ttests := []struct {\n\t\tx, y, want string\n\t}{\n\t\t{\"0\", \"1\", \"0\"},\n\t\t{\"0\", \"-1\", \"0\"},\n\t\t{\"10\", \"1\", \"0\"},\n\t\t{\"10\", \"-1\", \"0\"},\n\t\t{\"-10\", \"1\", \"0\"},\n\t\t{\"-10\", \"-1\", \"0\"},\n\t\t{\"10\", \"3\", \"1\"},\n\t\t{\"10\", \"-3\", \"1\"},\n\t\t{\"-10\", \"3\", \"2\"},\n\t\t{\"-10\", \"-3\", \"2\"},\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, err := FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\ty, err := FromDecimal(tc.y)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\twant, err := FromDecimal(tc.want)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgot := New()\n\t\tgot.Mod(x, y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"Mod(%s, %s) = %v, want %v\", tc.x, tc.y, got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestModeOverflow(t *testing.T) {\n\ttests := []struct {\n\t\tx, y, want string\n\t}{\n\t\t{MIN_INT256, \"2\", \"0\"},  // MIN_INT256 % 2 = 0\n\t\t{MAX_INT256, \"2\", \"1\"},  // MAX_INT256 % 2 = 1\n\t\t{MIN_INT256, \"-1\", \"0\"}, // MIN_INT256 % -1 = 0\n\t\t{MAX_INT256, \"-1\", \"0\"}, // MAX_INT256 % -1 = 0\n\t}\n\n\tfor _, tt := range tests {\n\t\tx := MustFromDecimal(tt.x)\n\t\ty := MustFromDecimal(tt.y)\n\t\twant := MustFromDecimal(tt.want)\n\t\tgot := New().Mod(x, y)\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"Mod(%s, %s) = %v, want %v\", tt.x, tt.y, got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestModPanic(t *testing.T) {\n\ttests := []struct {\n\t\tx, y string\n\t}{\n\t\t{\"10\", \"0\"},\n\t\t{\"10\", \"-0\"},\n\t\t{\"-10\", \"0\"},\n\t\t{\"-10\", \"-0\"},\n\t}\n\n\tfor _, tc := range tests {\n\t\tdefer func() {\n\t\t\tif r := recover(); r == nil {\n\t\t\t\tt.Errorf(\"Mod(%s, %s) did not panic\", tc.x, tc.y)\n\t\t\t}\n\t\t}()\n\t\tx, err := FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\ty, err := FromDecimal(tc.y)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tresult := New().Mod(x, y)\n\t\tt.Errorf(\"Mod(%s, %s) = %v, want %v\", tc.x, tc.y, result.String(), \"0\")\n\t}\n}\n\nfunc TestDivE(t *testing.T) {\n\ttestCases := []struct {\n\t\tx, y int64\n\t\twant int64\n\t}{\n\t\t{8, 3, 2},\n\t\t{8, -3, -2},\n\t\t{-8, 3, -3},\n\t\t{-8, -3, 3},\n\t\t{1, 2, 0},\n\t\t{1, -2, 0},\n\t\t{-1, 2, -1},\n\t\t{-1, -2, 1},\n\t\t{0, 1, 0},\n\t\t{0, -1, 0},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tx := NewInt(tc.x)\n\t\ty := NewInt(tc.y)\n\t\twant := NewInt(tc.want)\n\t\tgot := new(Int).DivE(x, y)\n\t\tif got.Cmp(want) != 0 {\n\t\t\tt.Errorf(\"DivE(%v, %v) = %v, want %v\", tc.x, tc.y, got, want)\n\t\t}\n\t}\n}\n\nfunc TestDivEByZero(t *testing.T) {\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Errorf(\"DivE did not panic on division by zero\")\n\t\t}\n\t}()\n\n\tx := NewInt(1)\n\ty := NewInt(0)\n\tnew(Int).DivE(x, y)\n}\n\nfunc TestModEByZero(t *testing.T) {\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Errorf(\"ModE did not panic on division by zero\")\n\t\t}\n\t}()\n\n\tx := NewInt(1)\n\ty := NewInt(0)\n\tnew(Int).ModE(x, y)\n}\n\nfunc TestLargeNumbers(t *testing.T) {\n\tx, _ := new(Int).SetString(\"123456789012345678901234567890\")\n\ty, _ := new(Int).SetString(\"987654321098765432109876543210\")\n\n\t// Expected results (calculated separately)\n\texpectedQ, _ := new(Int).SetString(\"0\")\n\texpectedR, _ := new(Int).SetString(\"123456789012345678901234567890\")\n\n\tgotQ := new(Int).DivE(x, y)\n\tgotR := new(Int).ModE(x, y)\n\n\tif gotQ.Cmp(expectedQ) != 0 {\n\t\tt.Errorf(\"DivE with large numbers: got %v, want %v\", gotQ, expectedQ)\n\t}\n\n\tif gotR.Cmp(expectedR) != 0 {\n\t\tt.Errorf(\"ModE with large numbers: got %v, want %v\", gotR, expectedR)\n\t}\n}\n\nfunc TestAbs(t *testing.T) {\n\ttests := []struct {\n\t\tx, want string\n\t}{\n\t\t{\"0\", \"0\"},\n\t\t{\"1\", \"1\"},\n\t\t{\"-1\", \"1\"},\n\t\t{\"-2\", \"2\"},\n\t\t{\"-100000000000\", \"100000000000\"},\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, err := FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgot := x.Abs()\n\n\t\tif got.String() != tc.want {\n\t\t\tt.Errorf(\"Abs(%s) = %v, want %v\", tc.x, got.String(), tc.want)\n\t\t}\n\t}\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":"bitwise_test.gno","body":"package int256\n\nimport (\n\t\"testing\"\n)\n\nfunc TestBitwise_And(t *testing.T) {\n\ttests := []struct {\n\t\tx, y, want string\n\t}{\n\t\t{\"5\", \"1\", \"1\"},  // 0101 \u0026 0001 = 0001\n\t\t{\"-1\", \"1\", \"1\"}, // 1111 \u0026 0001 = 0001\n\t\t{\"-5\", \"3\", \"3\"}, // 1111...1011 \u0026 0000...0011 = 0000...0011\n\t\t{MAX_UINT256, MAX_UINT256, MAX_UINT256},\n\t\t{TWO_POW_128, TWO_POW_128_MINUS_1, \"0\"}, // 2^128 \u0026 (2^128 - 1) = 0\n\t\t{TWO_POW_128, MAX_UINT256, TWO_POW_128}, // 2^128 \u0026 MAX_INT256\n\t\t{MAX_UINT256, TWO_POW_128, TWO_POW_128}, // MAX_INT256 \u0026 2^128\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, _ := FromDecimal(tc.x)\n\t\ty, _ := FromDecimal(tc.y)\n\t\twant, _ := FromDecimal(tc.want)\n\n\t\tgot := new(Int).And(x, y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"And(%s, %s) = %s, want %s\", x.String(), y.String(), got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestBitwise_Or(t *testing.T) {\n\ttests := []struct {\n\t\tx, y, want string\n\t}{\n\t\t{\"5\", \"1\", \"5\"},   // 0101 | 0001 = 0101\n\t\t{\"-1\", \"1\", \"-1\"}, // 1111 | 0001 = 1111\n\t\t{\"-5\", \"3\", \"-5\"}, // 1111...1011 | 0000...0011 = 1111...1011\n\t\t{TWO_POW_128, TWO_POW_128_MINUS_1, TWO_POW_129_MINUS_1},\n\t\t{TWO_POW_128, MAX_UINT256, MAX_UINT256},\n\t\t{\"0\", TWO_POW_128, TWO_POW_128},         // 0 | 2^128 = 2^128\n\t\t{MAX_UINT256, TWO_POW_128, MAX_UINT256}, // MAX_INT256 | 2^128 = MAX_INT256\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, _ := FromDecimal(tc.x)\n\t\ty, _ := FromDecimal(tc.y)\n\t\twant, _ := FromDecimal(tc.want)\n\n\t\tgot := new(Int).Or(x, y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\n\t\t\t\t\"Or(%s, %s) = %s, want %s\",\n\t\t\t\tx.String(), y.String(), got.String(), want.String(),\n\t\t\t)\n\t\t}\n\t}\n}\n\nfunc TestBitwise_Not(t *testing.T) {\n\ttests := []struct {\n\t\tx, want string\n\t}{\n\t\t{\"5\", \"-6\"},                              // 0101 -\u003e 1111...1010\n\t\t{\"-1\", \"0\"},                              // 1111...1111 -\u003e 0000...0000\n\t\t{TWO_POW_128, MINUS_TWO_POW_128_MINUS_1}, // NOT 2^128\n\t\t{TWO_POW_255, MIN_INT256_MINUS_1},        // NOT 2^255\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, _ := FromDecimal(tc.x)\n\t\twant, _ := FromDecimal(tc.want)\n\n\t\tgot := new(Int).Not(x)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"Not(%s) = %s, want %s\", x.String(), got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestBitwise_Xor(t *testing.T) {\n\ttests := []struct {\n\t\tx, y, want string\n\t}{\n\t\t{\"5\", \"1\", \"4\"},                 // 0101 ^ 0001 = 0100\n\t\t{\"-1\", \"1\", \"-2\"},               // 1111...1111 ^ 0000...0001 = 1111...1110\n\t\t{\"-5\", \"3\", \"-8\"},               // 1111...1011 ^ 0000...0011 = 1111...1000\n\t\t{TWO_POW_128, TWO_POW_128, \"0\"}, // 2^128 ^ 2^128 = 0\n\t\t{MAX_UINT256, TWO_POW_128, MINUS_TWO_POW_128_MINUS_1}, // MAX_INT256 ^ 2^128\n\t\t{TWO_POW_255, MAX_UINT256, MIN_INT256_MINUS_1},        // 2^255 ^ MAX_INT256\n\t}\n\n\tfor _, tt := range tests {\n\t\tx, _ := FromDecimal(tt.x)\n\t\ty, _ := FromDecimal(tt.y)\n\t\twant, _ := FromDecimal(tt.want)\n\n\t\tgot := new(Int).Xor(x, y)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"Xor(%s, %s) = %s, want %s\", x.String(), y.String(), got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestBitwise_Rsh(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\tn    uint\n\t\twant string\n\t}{\n\t\t{\"5\", 1, \"2\"},  // 0101 \u003e\u003e 1 = 0010\n\t\t{\"42\", 3, \"5\"}, // 00101010 \u003e\u003e 3 = 00000101\n\t\t{TWO_POW_128, 128, \"1\"},\n\t\t{MAX_UINT256, 255, \"1\"},\n\t\t{TWO_POW_255, 254, \"2\"},\n\t\t{MINUS_TWO_POW_128, 128, TWO_POW_128_MINUS_1},\n\t}\n\n\tfor _, tt := range tests {\n\t\tx, _ := FromDecimal(tt.x)\n\t\twant, _ := FromDecimal(tt.want)\n\n\t\tgot := new(Int).Rsh(x, tt.n)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"Rsh(%s, %d) = %s, want %s\", x.String(), tt.n, got.String(), want.String())\n\t\t}\n\t}\n}\n\nfunc TestBitwise_Lsh(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\tn    uint\n\t\twant string\n\t}{\n\t\t{\"5\", 2, \"20\"},          // 0101 \u003c\u003c 2 = 10100\n\t\t{\"42\", 5, \"1344\"},       // 00101010 \u003c\u003c 5 = 10101000000\n\t\t{\"1\", 128, TWO_POW_128}, // 1 \u003c\u003c 128 = 2^128\n\t\t{\"2\", 254, TWO_POW_255},\n\t\t{\"1\", 255, MIN_INT256}, // 1 \u003c\u003c 255 = MIN_INT256 (overflow)\n\t}\n\n\tfor _, tt := range tests {\n\t\tx, _ := FromDecimal(tt.x)\n\t\twant, _ := FromDecimal(tt.want)\n\n\t\tgot := new(Int).Lsh(x, tt.n)\n\n\t\tif got.Neq(want) {\n\t\t\tt.Errorf(\"Lsh(%s, %d) = %s, want %s\", x.String(), tt.n, got.String(), want.String())\n\t\t}\n\t}\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":"cmp_test.gno","body":"package int256\n\nimport \"testing\"\n\nfunc TestEq(t *testing.T) {\n\ttests := []struct {\n\t\tx, y string\n\t\twant bool\n\t}{\n\t\t{\"0\", \"0\", true},\n\t\t{\"0\", \"1\", false},\n\t\t{\"1\", \"0\", false},\n\t\t{\"-1\", \"0\", false},\n\t\t{\"0\", \"-1\", false},\n\t\t{\"1\", \"1\", true},\n\t\t{\"-1\", \"-1\", true},\n\t\t{\"115792089237316195423570985008687907853269984665640564039457584007913129639935\", \"-115792089237316195423570985008687907853269984665640564039457584007913129639935\", false},\n\t\t{\"-115792089237316195423570985008687907853269984665640564039457584007913129639935\", \"-115792089237316195423570985008687907853269984665640564039457584007913129639935\", true},\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, err := FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\ty, err := FromDecimal(tc.y)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgot := x.Eq(y)\n\t\tif got != tc.want {\n\t\t\tt.Errorf(\"Eq(%s, %s) = %v, want %v\", tc.x, tc.y, got, tc.want)\n\t\t}\n\t}\n}\n\nfunc TestNeq(t *testing.T) {\n\ttests := []struct {\n\t\tx, y string\n\t\twant bool\n\t}{\n\t\t{\"0\", \"0\", false},\n\t\t{\"0\", \"1\", true},\n\t\t{\"1\", \"0\", true},\n\t\t{\"-1\", \"0\", true},\n\t\t{\"0\", \"-1\", true},\n\t\t{\"1\", \"1\", false},\n\t\t{\"-1\", \"-1\", false},\n\t\t{\"115792089237316195423570985008687907853269984665640564039457584007913129639935\", \"-115792089237316195423570985008687907853269984665640564039457584007913129639935\", true},\n\t\t{\"-115792089237316195423570985008687907853269984665640564039457584007913129639935\", \"-115792089237316195423570985008687907853269984665640564039457584007913129639935\", false},\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, err := FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\ty, err := FromDecimal(tc.y)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgot := x.Neq(y)\n\t\tif got != tc.want {\n\t\t\tt.Errorf(\"Neq(%s, %s) = %v, want %v\", tc.x, tc.y, got, tc.want)\n\t\t}\n\t}\n}\n\nfunc TestCmp(t *testing.T) {\n\ttests := []struct {\n\t\tx, y string\n\t\twant int\n\t}{\n\t\t{\"0\", \"0\", 0},\n\t\t{\"0\", \"1\", -1},\n\t\t{\"1\", \"0\", 1},\n\t\t{\"-1\", \"0\", -1},\n\t\t{\"0\", \"-1\", 1},\n\t\t{\"1\", \"1\", 0},\n\t\t{\"115792089237316195423570985008687907853269984665640564039457584007913129639935\", \"-115792089237316195423570985008687907853269984665640564039457584007913129639935\", -1},\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, err := FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\ty, err := FromDecimal(tc.y)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgot := x.Cmp(y)\n\t\tif got != tc.want {\n\t\t\tt.Errorf(\"Cmp(%s, %s) = %v, want %v\", tc.x, tc.y, got, tc.want)\n\t\t}\n\t}\n}\n\nfunc TestIsZero(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\twant bool\n\t}{\n\t\t{\"0\", true},\n\t\t{\"-0\", true},\n\t\t{\"1\", false},\n\t\t{\"-1\", false},\n\t\t{\"10\", false},\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, err := FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgot := x.IsZero()\n\t\tif got != tc.want {\n\t\t\tt.Errorf(\"IsZero(%s) = %v, want %v\", tc.x, got, tc.want)\n\t\t}\n\t}\n}\n\nfunc TestIsNeg(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\twant bool\n\t}{\n\t\t{\"0\", false},\n\t\t{\"-0\", false},\n\t\t{\"1\", false},\n\t\t{\"-1\", true},\n\t\t{\"10\", false},\n\t\t{\"-10\", true},\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, err := FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgot := x.IsNeg()\n\t\tif got != tc.want {\n\t\t\tt.Errorf(\"IsNeg(%s) = %v, want %v\", tc.x, got, tc.want)\n\t\t}\n\t}\n}\n\nfunc TestLt(t *testing.T) {\n\ttests := []struct {\n\t\tx, y string\n\t\twant bool\n\t}{\n\t\t{\"0\", \"0\", false},\n\t\t{\"0\", \"1\", true},\n\t\t{\"1\", \"0\", false},\n\t\t{\"-1\", \"0\", true},\n\t\t{\"0\", \"-1\", false},\n\t\t{\"1\", \"1\", false},\n\t\t{\"-1\", \"-1\", false},\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, err := FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\ty, err := FromDecimal(tc.y)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgot := x.Lt(y)\n\t\tif got != tc.want {\n\t\t\tt.Errorf(\"Lt(%s, %s) = %v, want %v\", tc.x, tc.y, got, tc.want)\n\t\t}\n\t}\n}\n\nfunc TestGt(t *testing.T) {\n\ttests := []struct {\n\t\tx, y string\n\t\twant bool\n\t}{\n\t\t{\"0\", \"0\", false},\n\t\t{\"0\", \"1\", false},\n\t\t{\"1\", \"0\", true},\n\t\t{\"-1\", \"0\", false},\n\t\t{\"0\", \"-1\", true},\n\t\t{\"1\", \"1\", false},\n\t\t{\"-1\", \"-1\", false},\n\t}\n\n\tfor _, tc := range tests {\n\t\tx, err := FromDecimal(tc.x)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\ty, err := FromDecimal(tc.y)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgot := x.Gt(y)\n\t\tif got != tc.want {\n\t\t\tt.Errorf(\"Gt(%s, %s) = %v, want %v\", tc.x, tc.y, got, tc.want)\n\t\t}\n\t}\n}\n\nfunc TestClone(t *testing.T) {\n\ttests := []string{\n\t\t\"0\",\n\t\t\"-0\",\n\t\t\"1\",\n\t\t\"-1\",\n\t\t\"10\",\n\t\t\"-10\",\n\t\t\"115792089237316195423570985008687907853269984665640564039457584007913129639935\",\n\t\t\"-115792089237316195423570985008687907853269984665640564039457584007913129639935\",\n\t}\n\n\tfor _, xStr := range tests {\n\t\tx, err := FromDecimal(xStr)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\ty := x.Clone()\n\n\t\tif x.Neq(y) {\n\t\t\tt.Errorf(\"cloned value is not equal to original value\")\n\t\t}\n\t}\n}\n"},{"name":"conversion.gno","body":"package int256\n\nimport (\n\t\"math\"\n\n\t\"gno.land/p/onbloc/uint256\"\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":"conversion_test.gno","body":"package int256\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/onbloc/uint256\"\n)\n\nfunc TestSetInt64(t *testing.T) {\n\ttests := []struct {\n\t\tv      int64\n\t\texpect int\n\t}{\n\t\t{0, 0},\n\t\t{1, 1},\n\t\t{-1, -1},\n\t\t{9223372036854775807, 1},   // overflow (max int64)\n\t\t{-9223372036854775808, -1}, // underflow (min int64)\n\t}\n\n\tfor _, tt := range tests {\n\t\tz := New().SetInt64(tt.v)\n\t\tif z.Sign() != tt.expect {\n\t\t\tt.Errorf(\"SetInt64(%d) = %d, want %d\", tt.v, z.Sign(), tt.expect)\n\t\t}\n\t}\n}\n\nfunc TestUint64(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\twant uint64\n\t}{\n\t\t{\"0\", 0},\n\t\t{\"1\", 1},\n\t\t{\"9223372036854775807\", 9223372036854775807},\n\t\t{\"9223372036854775808\", 9223372036854775808},\n\t\t{\"18446744073709551615\", 18446744073709551615},\n\t}\n\n\tfor _, tt := range tests {\n\t\tz := MustFromDecimal(tt.x)\n\n\t\tgot := z.Uint64()\n\t\tif got != tt.want {\n\t\t\tt.Errorf(\"Uint64(%s) = %d, want %d\", tt.x, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestUint64_Panic(t *testing.T) {\n\ttests := []struct {\n\t\tx string\n\t}{\n\t\t{\"-1\"},\n\t\t{\"18446744073709551616\"},\n\t\t{\"18446744073709551617\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tdefer func() {\n\t\t\tif r := recover(); r == nil {\n\t\t\t\tt.Errorf(\"Uint64(%s) did not panic\", tt.x)\n\t\t\t}\n\t\t}()\n\n\t\tz := MustFromDecimal(tt.x)\n\t\tz.Uint64()\n\t}\n}\n\nfunc TestInt64(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\twant int64\n\t}{\n\t\t{\"0\", 0},\n\t\t{\"1\", 1},\n\t\t{\"9223372036854775807\", 9223372036854775807},\n\t\t{\"-1\", -1},\n\t\t{\"-9223372036854775808\", -9223372036854775808},\n\t}\n\n\tfor _, tt := range tests {\n\t\tz := MustFromDecimal(tt.x)\n\n\t\tgot := z.Int64()\n\t\tif got != tt.want {\n\t\t\tt.Errorf(\"Uint64(%s) = %d, want %d\", tt.x, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestInt64_Panic(t *testing.T) {\n\ttests := []struct {\n\t\tx string\n\t}{\n\t\t{\"18446744073709551616\"},\n\t\t{\"18446744073709551617\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tdefer func() {\n\t\t\tif r := recover(); r == nil {\n\t\t\t\tt.Errorf(\"Int64(%s) did not panic\", tt.x)\n\t\t\t}\n\t\t}()\n\n\t\tz := MustFromDecimal(tt.x)\n\t\tz.Int64()\n\t}\n}\n\nfunc TestNeg(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\twant string\n\t}{\n\t\t{\"0\", \"0\"},\n\t\t{\"1\", \"-1\"},\n\t\t{\"-1\", \"1\"},\n\t\t{\"9223372036854775807\", \"-9223372036854775807\"},\n\t\t{\"-18446744073709551615\", \"18446744073709551615\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tz := MustFromDecimal(tt.x)\n\t\tz.Neg(z)\n\n\t\tgot := z.String()\n\t\tif got != tt.want {\n\t\t\tt.Errorf(\"Neg(%s) = %s, want %s\", tt.x, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestSet(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\twant string\n\t}{\n\t\t{\"0\", \"0\"},\n\t\t{\"1\", \"1\"},\n\t\t{\"-1\", \"-1\"},\n\t\t{\"9223372036854775807\", \"9223372036854775807\"},\n\t\t{\"-18446744073709551615\", \"-18446744073709551615\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tz := MustFromDecimal(tt.x)\n\t\tz.Set(z)\n\n\t\tgot := z.String()\n\t\tif got != tt.want {\n\t\t\tt.Errorf(\"Set(%s) = %s, want %s\", tt.x, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc TestSetUint256(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\twant string\n\t}{\n\t\t{\"0\", \"0\"},\n\t\t{\"1\", \"1\"},\n\t\t{\"9223372036854775807\", \"9223372036854775807\"},\n\t\t{\"18446744073709551615\", \"18446744073709551615\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tgot := New()\n\n\t\tz := uint256.MustFromDecimal(tt.x)\n\t\tgot.SetUint256(z)\n\n\t\tif got.String() != tt.want {\n\t\t\tt.Errorf(\"SetUint256(%s) = %s, want %s\", tt.x, got.String(), tt.want)\n\t\t}\n\t}\n}\n\nfunc TestString(t *testing.T) {\n\ttests := []struct {\n\t\tinput    string\n\t\texpected string\n\t}{\n\t\t{\"0\", \"0\"},\n\t\t{\"1\", \"1\"},\n\t\t{\"-1\", \"-1\"},\n\t\t{\"123456789\", \"123456789\"},\n\t\t{\"-123456789\", \"-123456789\"},\n\t\t{\"18446744073709551615\", \"18446744073709551615\"}, // max uint64\n\t\t{\"-18446744073709551615\", \"-18446744073709551615\"},\n\t\t{TWO_POW_128_MINUS_1, TWO_POW_128_MINUS_1},\n\t\t{MINUS_TWO_POW_128, MINUS_TWO_POW_128},\n\t\t{MIN_INT256, MIN_INT256},\n\t\t{MAX_INT256, MAX_INT256},\n\t}\n\n\tfor _, tt := range tests {\n\t\tx, err := FromDecimal(tt.input)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to parse input (%s): %v\", tt.input, err)\n\t\t\tcontinue\n\t\t}\n\n\t\toutput := x.String()\n\n\t\tif output != tt.expected {\n\t\t\tt.Errorf(\"String(%s) = %s, want %s\", tt.input, output, tt.expected)\n\t\t}\n\t}\n}\n\nfunc TestNilToZero(t *testing.T) {\n\tz := New().NilToZero()\n\tif z.Sign() != 0 {\n\t\tt.Errorf(\"NilToZero() = %d, want %d\", z.Sign(), 0)\n\t}\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\"\ngno = \"0.9\"\n"},{"name":"int256.gno","body":"package int256\n\nimport (\n\t\"errors\"\n\n\t\"gno.land/p/onbloc/uint256\"\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"},{"name":"int256_test.gno","body":"package int256\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/onbloc/uint256\"\n)\n\nfunc TestInitializers(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tfn       func() *Int\n\t\twantSign int\n\t\twantStr  string\n\t}{\n\t\t{\"Zero\", Zero, 0, \"0\"},\n\t\t{\"New\", New, 0, \"0\"},\n\t\t{\"One\", One, 1, \"1\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tz := tt.fn()\n\t\t\tif z.Sign() != tt.wantSign {\n\t\t\t\tt.Errorf(\"%s() = %d, want %d\", tt.name, z.Sign(), tt.wantSign)\n\t\t\t}\n\t\t\tif z.String() != tt.wantStr {\n\t\t\t\tt.Errorf(\"%s() = %s, want %s\", tt.name, z.String(), tt.wantStr)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNewInt(t *testing.T) {\n\ttests := []struct {\n\t\tinput    int64\n\t\texpected int\n\t}{\n\t\t{0, 0},\n\t\t{1, 1},\n\t\t{-1, -1},\n\t\t{9223372036854775807, 1},   // max int64\n\t\t{-9223372036854775808, -1}, // min int64\n\t}\n\n\tfor _, tt := range tests {\n\t\tz := NewInt(tt.input)\n\t\tif z.Sign() != tt.expected {\n\t\t\tt.Errorf(\"NewInt(%d) = %d, want %d\", tt.input, z.Sign(), tt.expected)\n\t\t}\n\t}\n}\n\nfunc TestFromDecimal(t *testing.T) {\n\ttests := []struct {\n\t\tinput    string\n\t\texpected int\n\t\tisError  bool\n\t}{\n\t\t{\"0\", 0, false},\n\t\t{\"1\", 1, false},\n\t\t{\"-1\", -1, false},\n\t\t{\"123456789\", 1, false},\n\t\t{\"-123456789\", -1, false},\n\t\t{\"invalid\", 0, true},\n\t}\n\n\tfor _, tt := range tests {\n\t\tz, err := FromDecimal(tt.input)\n\t\tif tt.isError {\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"FromDecimal(%s) expected error, but got nil\", tt.input)\n\t\t\t}\n\t\t} else {\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"FromDecimal(%s) unexpected error: %v\", tt.input, err)\n\t\t\t} else if z.Sign() != tt.expected {\n\t\t\t\tt.Errorf(\"FromDecimal(%s) sign is incorrect. Expected: %d, Actual: %d\", tt.input, tt.expected, z.Sign())\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestMustFromDecimal(t *testing.T) {\n\ttests := []struct {\n\t\tinput       string\n\t\texpected    int\n\t\tshouldPanic bool\n\t}{\n\t\t{\"0\", 0, false},\n\t\t{\"1\", 1, false},\n\t\t{\"-1\", -1, false},\n\t\t{\"123\", 1, false},\n\t\t{\"invalid\", 0, true},\n\t}\n\n\tfor _, tt := range tests {\n\t\tif tt.shouldPanic {\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r == nil {\n\t\t\t\t\tt.Errorf(\"MustFromDecimal(%q) expected panic, but got nil\", tt.input)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\n\t\tz := MustFromDecimal(tt.input)\n\t\tif !tt.shouldPanic \u0026\u0026 z.Sign() != tt.expected {\n\t\t\tt.Errorf(\"MustFromDecimal(%q) sign is incorrect. Expected: %d, Actual: %d\", tt.input, tt.expected, z.Sign())\n\t\t}\n\t}\n}\n\nfunc TestSetUint64(t *testing.T) {\n\ttests := []uint64{\n\t\t0,\n\t\t1,\n\t\t18446744073709551615, // max uint64\n\t}\n\n\tfor _, tt := range tests {\n\t\tz := New().SetUint64(tt)\n\t\tif z.Sign() \u003c 0 {\n\t\t\tt.Errorf(\"SetUint64(%d) result is negative\", tt)\n\t\t}\n\t\tif tt == 0 \u0026\u0026 z.Sign() != 0 {\n\t\t\tt.Errorf(\"SetUint64(0) result is not zero\")\n\t\t}\n\t\tif tt \u003e 0 \u0026\u0026 z.Sign() != 1 {\n\t\t\tt.Errorf(\"SetUint64(%d) result is not positive\", tt)\n\t\t}\n\t}\n}\n\nfunc TestFromUint256(t *testing.T) {\n\ttests := []struct {\n\t\tinput    *uint256.Uint\n\t\texpected int\n\t}{\n\t\t{uint256.NewUint(0), 0},\n\t\t{uint256.NewUint(1), 1},\n\t\t{uint256.NewUint(18446744073709551615), 1},\n\t}\n\n\tfor _, tt := range tests {\n\t\tz := New().FromUint256(tt.input)\n\t\tif z.Sign() != tt.expected {\n\t\t\tt.Errorf(\"FromUint256(%v) = %d, want %d\", tt.input, z.Sign(), tt.expected)\n\t\t}\n\t}\n}\n\nfunc TestSign(t *testing.T) {\n\ttests := []struct {\n\t\tx    string\n\t\twant int\n\t}{\n\t\t{\"0\", 0},\n\t\t{\"-0\", 0},\n\t\t{\"+0\", 0},\n\t\t{\"1\", 1},\n\t\t{\"-1\", -1},\n\t\t{\"9223372036854775807\", 1},\n\t\t{\"-9223372036854775808\", -1},\n\t}\n\n\tfor _, tt := range tests {\n\t\tz := MustFromDecimal(tt.x)\n\t\tgot := z.Sign()\n\t\tif got != tt.want {\n\t\t\tt.Errorf(\"Sign(%s) = %d, want %d\", tt.x, got, tt.want)\n\t\t}\n\t}\n}\n\nfunc BenchmarkSign(b *testing.B) {\n\tz := New()\n\tfor i := 0; i \u003c b.N; i++ {\n\t\tz.SetUint64(uint64(i))\n\t\tz.Sign()\n\t}\n}\n\nfunc TestSetAndToString(t *testing.T) {\n\ttests := []struct {\n\t\tinput    string\n\t\texpected int\n\t\tisError  bool\n\t}{\n\t\t{\"0\", 0, false},\n\t\t{\"1\", 1, false},\n\t\t{\"-1\", -1, false},\n\t\t{\"123456789\", 1, false},\n\t\t{\"-123456789\", -1, false},\n\t\t{\"invalid\", 0, true},\n\t}\n\n\tfor _, tt := range tests {\n\t\tz, err := New().SetString(tt.input)\n\t\tif tt.isError {\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"SetString(%s) expected error, but got nil\", tt.input)\n\t\t\t}\n\t\t} else {\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"SetString(%s) unexpected error: %v\", tt.input, err)\n\t\t\t} else if z.Sign() != tt.expected {\n\t\t\t\tt.Errorf(\"SetString(%s) sign is incorrect. Expected: %d, Actual: %d\", tt.input, tt.expected, z.Sign())\n\t\t\t} else if z.String() != tt.input {\n\t\t\t\tt.Errorf(\"SetString(%s) string representation is incorrect. Expected: %s, Actual: %s\", tt.input, tt.input, z.String())\n\t\t\t}\n\t\t}\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"gvJN1YrNIeZBhCsT/SCqsXYQ1LGrJkdIq8HsWHJq2oJ1J6luLWmdTt640njlBC6PE6JLMNLRUrLquA/fpUpp+w=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"json","path":"gno.land/p/onbloc/json","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":"buffer_test.gno","body":"package json\n\nimport (\n\t\"testing\"\n)\n\nfunc TestBufferCurrent(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tbuffer   *buffer\n\t\texpected byte\n\t\twantErr  bool\n\t}{\n\t\t{\n\t\t\tname: \"Valid current byte\",\n\t\t\tbuffer: \u0026buffer{\n\t\t\t\tdata:   []byte(\"test\"),\n\t\t\t\tlength: 4,\n\t\t\t\tindex:  1,\n\t\t\t},\n\t\t\texpected: 'e',\n\t\t\twantErr:  false,\n\t\t},\n\t\t{\n\t\t\tname: \"EOF\",\n\t\t\tbuffer: \u0026buffer{\n\t\t\t\tdata:   []byte(\"test\"),\n\t\t\t\tlength: 4,\n\t\t\t\tindex:  4,\n\t\t\t},\n\t\t\texpected: 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\tgot, err := tt.buffer.current()\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"buffer.current() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif got != tt.expected {\n\t\t\t\tt.Errorf(\"buffer.current() = %v, want %v\", got, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestBufferStep(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tbuffer  *buffer\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname:    \"Valid step\",\n\t\t\tbuffer:  \u0026buffer{data: []byte(\"test\"), length: 4, index: 0},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname:    \"EOF error\",\n\t\t\tbuffer:  \u0026buffer{data: []byte(\"test\"), length: 4, index: 3},\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\terr := tt.buffer.step()\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"buffer.step() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestBufferNext(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tbuffer  *buffer\n\t\twant    byte\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname:    \"Valid next byte\",\n\t\t\tbuffer:  \u0026buffer{data: []byte(\"test\"), length: 4, index: 0},\n\t\t\twant:    'e',\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname:    \"EOF error\",\n\t\t\tbuffer:  \u0026buffer{data: []byte(\"test\"), length: 4, index: 3},\n\t\t\twant:    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\tgot, err := tt.buffer.next()\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"buffer.next() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif got != tt.want {\n\t\t\t\tt.Errorf(\"buffer.next() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestBufferSlice(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tbuffer  *buffer\n\t\tpos     int\n\t\twant    []byte\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname:    \"Valid slice -- 0 characters\",\n\t\t\tbuffer:  \u0026buffer{data: []byte(\"test\"), length: 4, index: 0},\n\t\t\tpos:     0,\n\t\t\twant:    nil,\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname:    \"Valid slice -- 1 character\",\n\t\t\tbuffer:  \u0026buffer{data: []byte(\"test\"), length: 4, index: 0},\n\t\t\tpos:     1,\n\t\t\twant:    []byte(\"t\"),\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname:    \"Valid slice -- 2 characters\",\n\t\t\tbuffer:  \u0026buffer{data: []byte(\"test\"), length: 4, index: 1},\n\t\t\tpos:     2,\n\t\t\twant:    []byte(\"es\"),\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname:    \"Valid slice -- 3 characters\",\n\t\t\tbuffer:  \u0026buffer{data: []byte(\"test\"), length: 4, index: 0},\n\t\t\tpos:     3,\n\t\t\twant:    []byte(\"tes\"),\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname:    \"Valid slice -- 4 characters\",\n\t\t\tbuffer:  \u0026buffer{data: []byte(\"test\"), length: 4, index: 0},\n\t\t\tpos:     4,\n\t\t\twant:    []byte(\"test\"),\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname:    \"EOF error\",\n\t\t\tbuffer:  \u0026buffer{data: []byte(\"test\"), length: 4, index: 3},\n\t\t\tpos:     2,\n\t\t\twant:    nil,\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\tgot, err := tt.buffer.slice(tt.pos)\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"buffer.slice() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif string(got) != string(tt.want) {\n\t\t\t\tt.Errorf(\"buffer.slice() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestBufferMove(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tbuffer  *buffer\n\t\tpos     int\n\t\twantErr bool\n\t\twantIdx int\n\t}{\n\t\t{\n\t\t\tname:    \"Valid move\",\n\t\t\tbuffer:  \u0026buffer{data: []byte(\"test\"), length: 4, index: 1},\n\t\t\tpos:     2,\n\t\t\twantErr: false,\n\t\t\twantIdx: 3,\n\t\t},\n\t\t{\n\t\t\tname:    \"Move beyond length\",\n\t\t\tbuffer:  \u0026buffer{data: []byte(\"test\"), length: 4, index: 1},\n\t\t\tpos:     4,\n\t\t\twantErr: true,\n\t\t\twantIdx: 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\terr := tt.buffer.move(tt.pos)\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"buffer.move() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t}\n\t\t\tif tt.buffer.index != tt.wantIdx {\n\t\t\t\tt.Errorf(\"buffer.move() index = %v, want %v\", tt.buffer.index, tt.wantIdx)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestBufferSkip(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tbuffer  *buffer\n\t\tb       byte\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname:    \"Skip byte\",\n\t\t\tbuffer:  \u0026buffer{data: []byte(\"test\"), length: 4, index: 0},\n\t\t\tb:       'e',\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname:    \"Skip to EOF\",\n\t\t\tbuffer:  \u0026buffer{data: []byte(\"test\"), length: 4, index: 0},\n\t\t\tb:       'x',\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\terr := tt.buffer.skip(tt.b)\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"buffer.skip() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestSkipToNextSignificantToken(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    []byte\n\t\texpected int\n\t}{\n\t\t{\"No significant chars\", []byte(\"abc\"), 3},\n\t\t{\"One significant char at start\", []byte(\".abc\"), 0},\n\t\t{\"Significant char in middle\", []byte(\"ab.c\"), 2},\n\t\t{\"Multiple significant chars\", []byte(\"a$.c\"), 1},\n\t\t{\"Significant char at end\", []byte(\"abc$\"), 3},\n\t\t{\"Only significant chars\", []byte(\"$.\"), 0},\n\t\t{\"Empty string\", []byte(\"\"), 0},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tb := newBuffer(tt.input)\n\t\t\tb.skipToNextSignificantToken()\n\t\t\tif b.index != tt.expected {\n\t\t\t\tt.Errorf(\"after skipToNextSignificantToken(), got index = %v, want %v\", b.index, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc mockBuffer(s string) *buffer {\n\treturn newBuffer([]byte(s))\n}\n\nfunc TestSkipAndReturnIndex(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    string\n\t\texpected int\n\t}{\n\t\t{\"StartOfString\", \"\", 0},\n\t\t{\"MiddleOfString\", \"abcdef\", 1},\n\t\t{\"EndOfString\", \"abc\", 1},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tbuf := mockBuffer(tt.input)\n\t\t\tgot, err := buf.skipAndReturnIndex()\n\t\t\tif err != nil \u0026\u0026 tt.input != \"\" { // Expect no error unless input is empty\n\t\t\t\tt.Errorf(\"skipAndReturnIndex() error = %v\", err)\n\t\t\t}\n\t\t\tif got != tt.expected {\n\t\t\t\tt.Errorf(\"skipAndReturnIndex() = %v, want %v\", got, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestSkipUntil(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    string\n\t\ttokens   map[byte]bool\n\t\texpected int\n\t}{\n\t\t{\"SkipToToken\", \"abcdefg\", map[byte]bool{'c': true}, 2},\n\t\t{\"SkipToEnd\", \"abcdefg\", map[byte]bool{'h': true}, 7},\n\t\t{\"SkipNone\", \"abcdefg\", map[byte]bool{'a': true}, 0},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tbuf := mockBuffer(tt.input)\n\t\t\tgot, err := buf.skipUntil(tt.tokens)\n\t\t\tif err != nil \u0026\u0026 got != len(tt.input) { // Expect error only if reached end without finding token\n\t\t\t\tt.Errorf(\"skipUntil() error = %v\", err)\n\t\t\t}\n\t\t\tif got != tt.expected {\n\t\t\t\tt.Errorf(\"skipUntil() = %v, want %v\", got, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestSliceFromIndices(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    string\n\t\tstart    int\n\t\tend      int\n\t\texpected string\n\t}{\n\t\t{\"FullString\", \"abcdefg\", 0, 7, \"abcdefg\"},\n\t\t{\"Substring\", \"abcdefg\", 2, 5, \"cde\"},\n\t\t{\"OutOfBounds\", \"abcdefg\", 5, 10, \"fg\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tbuf := mockBuffer(tt.input)\n\t\t\tgot := buf.sliceFromIndices(tt.start, tt.end)\n\t\t\tif string(got) != tt.expected {\n\t\t\t\tt.Errorf(\"sliceFromIndices() = %v, want %v\", string(got), tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestBufferToken(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tpath  string\n\t\tindex int\n\t\tisErr bool\n\t}{\n\t\t{\n\t\t\tname:  \"Simple valid path\",\n\t\t\tpath:  \"@.length\",\n\t\t\tindex: 8,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"Path with array expr\",\n\t\t\tpath:  \"@['foo'].0.bar\",\n\t\t\tindex: 14,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"Path with array expr and simple fomula\",\n\t\t\tpath:  \"@['foo'].[(@.length - 1)].*\",\n\t\t\tindex: 27,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"Path with filter expr\",\n\t\t\tpath:  \"@['foo'].[?(@.bar == 1 \u0026 @.baz \u003c @.length)].*\",\n\t\t\tindex: 45,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"addition of foo and bar\",\n\t\t\tpath:  \"@.foo+@.bar\",\n\t\t\tindex: 11,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"logical AND of foo and bar\",\n\t\t\tpath:  \"@.foo \u0026\u0026 @.bar\",\n\t\t\tindex: 14,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"logical OR of foo and bar\",\n\t\t\tpath:  \"@.foo || @.bar\",\n\t\t\tindex: 14,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"accessing third element of foo\",\n\t\t\tpath:  \"@.foo,3\",\n\t\t\tindex: 7,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"accessing last element of array\",\n\t\t\tpath:  \"@.length-1\",\n\t\t\tindex: 10,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"number 1\",\n\t\t\tpath:  \"1\",\n\t\t\tindex: 1,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"float\",\n\t\t\tpath:  \"3.1e4\",\n\t\t\tindex: 5,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"float with minus\",\n\t\t\tpath:  \"3.1e-4\",\n\t\t\tindex: 6,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"float with plus\",\n\t\t\tpath:  \"3.1e+4\",\n\t\t\tindex: 6,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"negative number\",\n\t\t\tpath:  \"-12345\",\n\t\t\tindex: 6,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"negative float\",\n\t\t\tpath:  \"-3.1e4\",\n\t\t\tindex: 6,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"negative float with minus\",\n\t\t\tpath:  \"-3.1e-4\",\n\t\t\tindex: 7,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"negative float with plus\",\n\t\t\tpath:  \"-3.1e+4\",\n\t\t\tindex: 7,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"string number\",\n\t\t\tpath:  \"'12345'\",\n\t\t\tindex: 7,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"string with backslash\",\n\t\t\tpath:  \"'foo \\\\'bar '\",\n\t\t\tindex: 12,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"string with inner double quotes\",\n\t\t\tpath:  \"'foo \\\"bar \\\"'\",\n\t\t\tindex: 12,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"parenthesis 1\",\n\t\t\tpath:  \"(@abc)\",\n\t\t\tindex: 6,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"parenthesis 2\",\n\t\t\tpath:  \"[()]\",\n\t\t\tindex: 4,\n\t\t\tisErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"parenthesis mismatch\",\n\t\t\tpath:  \"[(])\",\n\t\t\tindex: 2,\n\t\t\tisErr: true,\n\t\t},\n\t\t{\n\t\t\tname:  \"parenthesis mismatch 2\",\n\t\t\tpath:  \"(\",\n\t\t\tindex: 1,\n\t\t\tisErr: true,\n\t\t},\n\t\t{\n\t\t\tname:  \"parenthesis mismatch 3\",\n\t\t\tpath:  \"())]\",\n\t\t\tindex: 2,\n\t\t\tisErr: true,\n\t\t},\n\t\t{\n\t\t\tname:  \"bracket mismatch\",\n\t\t\tpath:  \"[()\",\n\t\t\tindex: 3,\n\t\t\tisErr: true,\n\t\t},\n\t\t{\n\t\t\tname:  \"bracket mismatch 2\",\n\t\t\tpath:  \"()]\",\n\t\t\tindex: 2,\n\t\t\tisErr: true,\n\t\t},\n\t\t{\n\t\t\tname:  \"path does not close bracket\",\n\t\t\tpath:  \"@.foo[)\",\n\t\t\tindex: 6,\n\t\t\tisErr: 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\tbuf := newBuffer([]byte(tt.path))\n\n\t\t\terr := buf.pathToken()\n\t\t\tif tt.isErr {\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Errorf(\"Expected an error for path `%s`, but got none\", tt.path)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif err == nil \u0026\u0026 tt.isErr {\n\t\t\t\tt.Errorf(\"Expected an error for path `%s`, but got none\", tt.path)\n\t\t\t}\n\n\t\t\tif buf.index != tt.index {\n\t\t\t\tt.Errorf(\"Expected final index %d, got %d (token: `%s`) for path `%s`\", tt.index, buf.index, string(buf.data[buf.index]), tt.path)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestBufferFirst(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tdata     []byte\n\t\texpected byte\n\t}{\n\t\t{\n\t\t\tname:     \"Valid first byte\",\n\t\t\tdata:     []byte(\"test\"),\n\t\t\texpected: 't',\n\t\t},\n\t\t{\n\t\t\tname:     \"Empty buffer\",\n\t\t\tdata:     []byte(\"\"),\n\t\t\texpected: 0,\n\t\t},\n\t\t{\n\t\t\tname:     \"Whitespace buffer\",\n\t\t\tdata:     []byte(\"   \"),\n\t\t\texpected: 0,\n\t\t},\n\t\t{\n\t\t\tname:     \"whitespace in middle\",\n\t\t\tdata:     []byte(\"hello world\"),\n\t\t\texpected: 'h',\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tb := newBuffer(tt.data)\n\n\t\t\tgot, err := b.first()\n\t\t\tif err != nil \u0026\u0026 tt.expected != 0 {\n\t\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t\t}\n\n\t\t\tif got != tt.expected {\n\t\t\t\tt.Errorf(\"Expected first byte to be %q, got %q\", tt.expected, got)\n\t\t\t}\n\t\t})\n\t}\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":"builder_test.gno","body":"package json\n\nimport (\n\t\"testing\"\n)\n\nfunc TestNodeBuilder(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tbuild    func() *Node\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname: \"plain object\",\n\t\t\tbuild: func() *Node {\n\t\t\t\treturn Builder().\n\t\t\t\t\tWriteString(\"name\", \"Alice\").\n\t\t\t\t\tWriteNumber(\"age\", 30).\n\t\t\t\t\tWriteBool(\"is_student\", false).\n\t\t\t\t\tNode()\n\t\t\t},\n\t\t\texpected: `{\"name\":\"Alice\",\"age\":30,\"is_student\":false}`,\n\t\t},\n\t\t{\n\t\t\tname: \"nested object\",\n\t\t\tbuild: func() *Node {\n\t\t\t\treturn Builder().\n\t\t\t\t\tWriteString(\"name\", \"Alice\").\n\t\t\t\t\tWriteObject(\"address\", func(b *NodeBuilder) {\n\t\t\t\t\t\tb.WriteString(\"city\", \"New York\").\n\t\t\t\t\t\t\tWriteNumber(\"zipcode\", 10001)\n\t\t\t\t\t}).\n\t\t\t\t\tNode()\n\t\t\t},\n\t\t\texpected: `{\"name\":\"Alice\",\"address\":{\"city\":\"New York\",\"zipcode\":10001}}`,\n\t\t},\n\t\t{\n\t\t\tname: \"null node\",\n\t\t\tbuild: func() *Node {\n\t\t\t\treturn Builder().WriteNull(\"foo\").Node()\n\t\t\t},\n\t\t\texpected: `{\"foo\":null}`,\n\t\t},\n\t\t{\n\t\t\tname: \"array node\",\n\t\t\tbuild: func() *Node {\n\t\t\t\treturn Builder().\n\t\t\t\t\tWriteArray(\"items\", func(ab *ArrayBuilder) {\n\t\t\t\t\t\tab.WriteString(\"item1\").\n\t\t\t\t\t\t\tWriteString(\"item2\").\n\t\t\t\t\t\t\tWriteString(\"item3\")\n\t\t\t\t\t}).\n\t\t\t\t\tNode()\n\t\t\t},\n\t\t\texpected: `{\"items\":[\"item1\",\"item2\",\"item3\"]}`,\n\t\t},\n\t\t{\n\t\t\tname: \"array with objects\",\n\t\t\tbuild: func() *Node {\n\t\t\t\treturn Builder().\n\t\t\t\t\tWriteArray(\"users\", func(ab *ArrayBuilder) {\n\t\t\t\t\t\tab.WriteObject(func(b *NodeBuilder) {\n\t\t\t\t\t\t\tb.WriteString(\"name\", \"Bob\").\n\t\t\t\t\t\t\t\tWriteNumber(\"age\", 25)\n\t\t\t\t\t\t}).\n\t\t\t\t\t\t\tWriteObject(func(b *NodeBuilder) {\n\t\t\t\t\t\t\t\tb.WriteString(\"name\", \"Carol\").\n\t\t\t\t\t\t\t\t\tWriteNumber(\"age\", 27)\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}).\n\t\t\t\t\tNode()\n\t\t\t},\n\t\t\texpected: `{\"users\":[{\"name\":\"Bob\",\"age\":25},{\"name\":\"Carol\",\"age\":27}]}`,\n\t\t},\n\t\t{\n\t\t\tname: \"array with various types\",\n\t\t\tbuild: func() *Node {\n\t\t\t\treturn Builder().\n\t\t\t\t\tWriteArray(\"values\", func(ab *ArrayBuilder) {\n\t\t\t\t\t\tab.WriteString(\"item1\").\n\t\t\t\t\t\t\tWriteNumber(123).\n\t\t\t\t\t\t\tWriteBool(true).\n\t\t\t\t\t\t\tWriteNull()\n\t\t\t\t\t}).\n\t\t\t\t\tNode()\n\t\t\t},\n\t\t\texpected: `{\"values\":[\"item1\",123,true,null]}`,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tnode := tt.build()\n\t\t\tvalue, err := Marshal(node)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"unexpected error: %s\", err)\n\t\t\t}\n\t\t\tif string(value) != tt.expected {\n\t\t\t\tt.Errorf(\"expected %s, got %s\", tt.expected, string(value))\n\t\t\t}\n\t\t})\n\t}\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":"decode_test.gno","body":"package json\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\ntype testNode struct {\n\tname  string\n\tinput []byte\n\tvalue []byte\n\t_type ValueType\n}\n\nfunc simpleValid(test *testNode, t *testing.T) {\n\troot, err := Unmarshal(test.input)\n\tif err != nil {\n\t\tt.Errorf(\"Error on Unmarshal(%s): %s\", test.input, err.Error())\n\t} else if root == nil {\n\t\tt.Errorf(\"Error on Unmarshal(%s): root is nil\", test.name)\n\t} else if root.nodeType != test._type {\n\t\tt.Errorf(\"Error on Unmarshal(%s): wrong type\", test.name)\n\t} else if !bytes.Equal(root.source(), test.value) {\n\t\tt.Errorf(\"Error on Unmarshal(%s): %s != %s\", test.name, root.source(), test.value)\n\t}\n}\n\nfunc simpleInvalid(test *testNode, t *testing.T) {\n\troot, err := Unmarshal(test.input)\n\tif err == nil {\n\t\tt.Errorf(\"Error on Unmarshal(%s): error expected, got '%s'\", test.name, root.source())\n\t} else if root != nil {\n\t\tt.Errorf(\"Error on Unmarshal(%s): root is not nil\", test.name)\n\t}\n}\n\nfunc simpleCorrupted(name string) *testNode {\n\treturn \u0026testNode{name: name, input: []byte(name)}\n}\n\nfunc TestUnmarshal_StringSimpleSuccess(t *testing.T) {\n\ttests := []*testNode{\n\t\t{name: \"blank\", input: []byte(\"\\\"\\\"\"), _type: String, value: []byte(\"\\\"\\\"\")},\n\t\t{name: \"char\", input: []byte(\"\\\"c\\\"\"), _type: String, value: []byte(\"\\\"c\\\"\")},\n\t\t{name: \"word\", input: []byte(\"\\\"cat\\\"\"), _type: String, value: []byte(\"\\\"cat\\\"\")},\n\t\t{name: \"spaces\", input: []byte(\"  \\\"good cat or dog\\\"\\r\\n \"), _type: String, value: []byte(\"\\\"good cat or dog\\\"\")},\n\t\t{name: \"backslash\", input: []byte(\"\\\"good \\\\\\\"cat\\\\\\\"\\\"\"), _type: String, value: []byte(\"\\\"good \\\\\\\"cat\\\\\\\"\\\"\")},\n\t\t{name: \"backslash 2\", input: []byte(\"\\\"good \\\\\\\\\\\\\\\"cat\\\\\\\"\\\"\"), _type: String, value: []byte(\"\\\"good \\\\\\\\\\\\\\\"cat\\\\\\\"\\\"\")},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tsimpleValid(test, t)\n\t\t})\n\t}\n}\n\nfunc TestUnmarshal_NumericSimpleSuccess(t *testing.T) {\n\ttests := []*testNode{\n\t\t{name: \"1\", input: []byte(\"1\"), _type: Number, value: []byte(\"1\")},\n\t\t{name: \"-1\", input: []byte(\"-1\"), _type: Number, value: []byte(\"-1\")},\n\n\t\t{name: \"1234567890\", input: []byte(\"1234567890\"), _type: Number, value: []byte(\"1234567890\")},\n\t\t{name: \"-123\", input: []byte(\"-123\"), _type: Number, value: []byte(\"-123\")},\n\n\t\t{name: \"123.456\", input: []byte(\"123.456\"), _type: Number, value: []byte(\"123.456\")},\n\t\t{name: \"-123.456\", input: []byte(\"-123.456\"), _type: Number, value: []byte(\"-123.456\")},\n\n\t\t{name: \"1e3\", input: []byte(\"1e3\"), _type: Number, value: []byte(\"1e3\")},\n\t\t{name: \"1e+3\", input: []byte(\"1e+3\"), _type: Number, value: []byte(\"1e+3\")},\n\t\t{name: \"1e-3\", input: []byte(\"1e-3\"), _type: Number, value: []byte(\"1e-3\")},\n\t\t{name: \"-1e3\", input: []byte(\"-1e3\"), _type: Number, value: []byte(\"-1e3\")},\n\t\t{name: \"-1e-3\", input: []byte(\"-1e-3\"), _type: Number, value: []byte(\"-1e-3\")},\n\n\t\t{name: \"1.123e3456\", input: []byte(\"1.123e3456\"), _type: Number, value: []byte(\"1.123e3456\")},\n\t\t{name: \"1.123e-3456\", input: []byte(\"1.123e-3456\"), _type: Number, value: []byte(\"1.123e-3456\")},\n\t\t{name: \"-1.123e3456\", input: []byte(\"-1.123e3456\"), _type: Number, value: []byte(\"-1.123e3456\")},\n\t\t{name: \"-1.123e-3456\", input: []byte(\"-1.123e-3456\"), _type: Number, value: []byte(\"-1.123e-3456\")},\n\n\t\t{name: \"1E3\", input: []byte(\"1E3\"), _type: Number, value: []byte(\"1E3\")},\n\t\t{name: \"1E-3\", input: []byte(\"1E-3\"), _type: Number, value: []byte(\"1E-3\")},\n\t\t{name: \"-1E3\", input: []byte(\"-1E3\"), _type: Number, value: []byte(\"-1E3\")},\n\t\t{name: \"-1E-3\", input: []byte(\"-1E-3\"), _type: Number, value: []byte(\"-1E-3\")},\n\n\t\t{name: \"1.123E3456\", input: []byte(\"1.123E3456\"), _type: Number, value: []byte(\"1.123E3456\")},\n\t\t{name: \"1.123E-3456\", input: []byte(\"1.123E-3456\"), _type: Number, value: []byte(\"1.123E-3456\")},\n\t\t{name: \"-1.123E3456\", input: []byte(\"-1.123E3456\"), _type: Number, value: []byte(\"-1.123E3456\")},\n\t\t{name: \"-1.123E-3456\", input: []byte(\"-1.123E-3456\"), _type: Number, value: []byte(\"-1.123E-3456\")},\n\n\t\t{name: \"-1.123E-3456 with spaces\", input: []byte(\" \\r -1.123E-3456 \\t\\n\"), _type: Number, value: []byte(\"-1.123E-3456\")},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\troot, err := Unmarshal(test.input)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Error on Unmarshal(%s): %s\", test.name, err.Error())\n\t\t\t} else if root == nil {\n\t\t\t\tt.Errorf(\"Error on Unmarshal(%s): root is nil\", test.name)\n\t\t\t} else if root.nodeType != test._type {\n\t\t\t\tt.Errorf(\"Error on Unmarshal(%s): wrong type\", test.name)\n\t\t\t} else if !bytes.Equal(root.source(), test.value) {\n\t\t\t\tt.Errorf(\"Error on Unmarshal(%s): %s != %s\", test.name, root.source(), test.value)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestUnmarshal_StringSimpleCorrupted(t *testing.T) {\n\ttests := []*testNode{\n\t\t{name: \"white NL\", input: []byte(\"\\\"foo\\nbar\\\"\")},\n\t\t{name: \"white R\", input: []byte(\"\\\"foo\\rbar\\\"\")},\n\t\t{name: \"white Tab\", input: []byte(\"\\\"foo\\tbar\\\"\")},\n\t\t{name: \"wrong quotes\", input: []byte(\"'cat'\")},\n\t\t{name: \"double string\", input: []byte(\"\\\"Hello\\\" \\\"World\\\"\")},\n\t\t{name: \"quotes in quotes\", input: []byte(\"\\\"good \\\"cat\\\"\\\"\")},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tsimpleInvalid(test, t)\n\t\t})\n\t}\n}\n\nfunc TestUnmarshal_ObjectSimpleSuccess(t *testing.T) {\n\ttests := []*testNode{\n\t\t{name: \"{}\", input: []byte(\"{}\"), _type: Object, value: []byte(\"{}\")},\n\t\t{name: `{ \\r\\n }`, input: []byte(\"{ \\r\\n }\"), _type: Object, value: []byte(\"{ \\r\\n }\")},\n\t\t{name: `{\"key\":1}`, input: []byte(`{\"key\":1}`), _type: Object, value: []byte(`{\"key\":1}`)},\n\t\t{name: `{\"key\":true}`, input: []byte(`{\"key\":true}`), _type: Object, value: []byte(`{\"key\":true}`)},\n\t\t{name: `{\"key\":\"value\"}`, input: []byte(`{\"key\":\"value\"}`), _type: Object, value: []byte(`{\"key\":\"value\"}`)},\n\t\t{name: `{\"foo\":\"bar\",\"baz\":\"foo\"}`, input: []byte(`{\"foo\":\"bar\", \"baz\":\"foo\"}`), _type: Object, value: []byte(`{\"foo\":\"bar\", \"baz\":\"foo\"}`)},\n\t\t{name: \"spaces\", input: []byte(`  {  \"foo\"  :  \"bar\"  , \"baz\"   :   \"foo\"   }    `), _type: Object, value: []byte(`{  \"foo\"  :  \"bar\"  , \"baz\"   :   \"foo\"   }`)},\n\t\t{name: \"nested\", input: []byte(`{\"foo\":{\"bar\":{\"baz\":{}}}}`), _type: Object, value: []byte(`{\"foo\":{\"bar\":{\"baz\":{}}}}`)},\n\t\t{name: \"array\", input: []byte(`{\"array\":[{},{},{\"foo\":[{\"bar\":[\"baz\"]}]}]}`), _type: Object, value: []byte(`{\"array\":[{},{},{\"foo\":[{\"bar\":[\"baz\"]}]}]}`)},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tsimpleValid(test, t)\n\t\t})\n\t}\n}\n\nfunc TestUnmarshal_ObjectSimpleCorrupted(t *testing.T) {\n\ttests := []*testNode{\n\t\tsimpleCorrupted(\"{{{\\\"key\\\": \\\"foo\\\"{{{{\"),\n\t\tsimpleCorrupted(\"}\"),\n\t\tsimpleCorrupted(\"{ }}}}}}}\"),\n\t\tsimpleCorrupted(\" }\"),\n\t\tsimpleCorrupted(\"{,}\"),\n\t\tsimpleCorrupted(\"{:}\"),\n\t\tsimpleCorrupted(\"{100000}\"),\n\t\tsimpleCorrupted(\"{1:1}\"),\n\t\tsimpleCorrupted(\"{'1:2,3:4'}\"),\n\t\tsimpleCorrupted(`{\"d\"}`),\n\t\tsimpleCorrupted(`{\"foo\"}`),\n\t\tsimpleCorrupted(`{\"foo\":}`),\n\t\tsimpleCorrupted(`{:\"foo\"}`),\n\t\tsimpleCorrupted(`{\"foo\":bar}`),\n\t\tsimpleCorrupted(`{\"foo\":\"bar\",}`),\n\t\tsimpleCorrupted(`{}{}`),\n\t\tsimpleCorrupted(`{},{}`),\n\t\tsimpleCorrupted(`{[},{]}`),\n\t\tsimpleCorrupted(`{[,]}`),\n\t\tsimpleCorrupted(`{[]}`),\n\t\tsimpleCorrupted(`{}1`),\n\t\tsimpleCorrupted(`1{}`),\n\t\tsimpleCorrupted(`{\"x\"::1}`),\n\t\tsimpleCorrupted(`{null:null}`),\n\t\tsimpleCorrupted(`{\"foo:\"bar\"}`),\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tsimpleInvalid(test, t)\n\t\t})\n\t}\n}\n\nfunc TestUnmarshal_NullSimpleCorrupted(t *testing.T) {\n\ttests := []*testNode{\n\t\t{name: \"nul\", input: []byte(\"nul\")},\n\t\t{name: \"nil\", input: []byte(\"nil\")},\n\t\t{name: \"nill\", input: []byte(\"nill\")},\n\t\t{name: \"NILL\", input: []byte(\"NILL\")},\n\t\t{name: \"Null\", input: []byte(\"Null\")},\n\t\t{name: \"NULL\", input: []byte(\"NULL\")},\n\t\t{name: \"spaces\", input: []byte(\"Nu ll\")},\n\t\t{name: \"null1\", input: []byte(\"null1\")},\n\t\t{name: \"double\", input: []byte(\"null null\")},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tsimpleInvalid(test, t)\n\t\t})\n\t}\n}\n\nfunc TestUnmarshal_BoolSimpleSuccess(t *testing.T) {\n\ttests := []*testNode{\n\t\t{name: \"lower true\", input: []byte(\"true\"), _type: Boolean, value: []byte(\"true\")},\n\t\t{name: \"lower false\", input: []byte(\"false\"), _type: Boolean, value: []byte(\"false\")},\n\t\t{name: \"spaces true\", input: []byte(\"  true\\r\\n \"), _type: Boolean, value: []byte(\"true\")},\n\t\t{name: \"spaces false\", input: []byte(\"  false\\r\\n \"), _type: Boolean, value: []byte(\"false\")},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tsimpleValid(test, t)\n\t\t})\n\t}\n}\n\nfunc TestUnmarshal_BoolSimpleCorrupted(t *testing.T) {\n\ttests := []*testNode{\n\t\tsimpleCorrupted(\"tru\"),\n\t\tsimpleCorrupted(\"fals\"),\n\t\tsimpleCorrupted(\"tre\"),\n\t\tsimpleCorrupted(\"fal se\"),\n\t\tsimpleCorrupted(\"true false\"),\n\t\tsimpleCorrupted(\"True\"),\n\t\tsimpleCorrupted(\"TRUE\"),\n\t\tsimpleCorrupted(\"False\"),\n\t\tsimpleCorrupted(\"FALSE\"),\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tsimpleInvalid(test, t)\n\t\t})\n\t}\n}\n\nfunc TestUnmarshal_ArraySimpleSuccess(t *testing.T) {\n\ttests := []*testNode{\n\t\t{name: \"[]\", input: []byte(\"[]\"), _type: Array, value: []byte(\"[]\")},\n\t\t{name: \"[1]\", input: []byte(\"[1]\"), _type: Array, value: []byte(\"[1]\")},\n\t\t{name: \"[1,2,3]\", input: []byte(\"[1,2,3]\"), _type: Array, value: []byte(\"[1,2,3]\")},\n\t\t{name: \"[1, 2, 3]\", input: []byte(\"[1, 2, 3]\"), _type: Array, value: []byte(\"[1, 2, 3]\")},\n\t\t{name: \"[1,[2],3]\", input: []byte(\"[1,[2],3]\"), _type: Array, value: []byte(\"[1,[2],3]\")},\n\t\t{name: \"[[],[],[]]\", input: []byte(\"[[],[],[]]\"), _type: Array, value: []byte(\"[[],[],[]]\")},\n\t\t{name: \"[[[[[]]]]]\", input: []byte(\"[[[[[]]]]]\"), _type: Array, value: []byte(\"[[[[[]]]]]\")},\n\t\t{name: \"[true,null,1,\\\"foo\\\",[]]\", input: []byte(\"[true,null,1,\\\"foo\\\",[]]\"), _type: Array, value: []byte(\"[true,null,1,\\\"foo\\\",[]]\")},\n\t\t{name: \"spaces\", input: []byte(\"\\n\\r [\\n1\\n ]\\r\\n\"), _type: Array, value: []byte(\"[\\n1\\n ]\")},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tsimpleValid(test, t)\n\t\t})\n\t}\n}\n\nfunc TestUnmarshal_ArraySimpleCorrupted(t *testing.T) {\n\ttests := []*testNode{\n\t\tsimpleCorrupted(\"[,]\"),\n\t\tsimpleCorrupted(\"[]\\\\\"),\n\t\tsimpleCorrupted(\"[1,]\"),\n\t\tsimpleCorrupted(\"[[]\"),\n\t\tsimpleCorrupted(\"[]]\"),\n\t\tsimpleCorrupted(\"1[]\"),\n\t\tsimpleCorrupted(\"[]1\"),\n\t\tsimpleCorrupted(\"[[]1]\"),\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tsimpleInvalid(test, t)\n\t\t})\n\t}\n}\n\n// Examples from https://json.org/example.html\nfunc TestUnmarshal(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tvalue string\n\t}{\n\t\t{\n\t\t\tname: \"glossary\",\n\t\t\tvalue: `{\n\t\t\t\t\"glossary\": {\n\t\t\t\t\t\"title\": \"example glossary\",\n\t\t\t\t\t\"GlossDiv\": {\n\t\t\t\t\t\t\"title\": \"S\",\n\t\t\t\t\t\t\"GlossList\": {\n\t\t\t\t\t\t\t\"GlossEntry\": {\n\t\t\t\t\t\t\t\t\"ID\": \"SGML\",\n\t\t\t\t\t\t\t\t\"SortAs\": \"SGML\",\n\t\t\t\t\t\t\t\t\"GlossTerm\": \"Standard Generalized Markup Language\",\n\t\t\t\t\t\t\t\t\"Acronym\": \"SGML\",\n\t\t\t\t\t\t\t\t\"Abbrev\": \"ISO 8879:1986\",\n\t\t\t\t\t\t\t\t\"GlossDef\": {\n\t\t\t\t\t\t\t\t\t\"para\": \"A meta-markup language, used to create markup languages such as DocBook.\",\n\t\t\t\t\t\t\t\t\t\"GlossSeeAlso\": [\"GML\", \"XML\"]\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\"GlossSee\": \"markup\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}`,\n\t\t},\n\t\t{\n\t\t\tname: \"menu\",\n\t\t\tvalue: `{\"menu\": {\n\t\t\t\t\"id\": \"file\",\n\t\t\t\t\"value\": \"File\",\n\t\t\t\t\"popup\": {\n\t\t\t\t  \"menuitem\": [\n\t\t\t\t\t{\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},\n\t\t\t\t\t{\"value\": \"Open\", \"onclick\": \"OpenDoc()\"},\n\t\t\t\t\t{\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}\n\t\t\t\t  ]\n\t\t\t\t}\n\t\t\t}}`,\n\t\t},\n\t\t{\n\t\t\tname: \"widget\",\n\t\t\tvalue: `{\"widget\": {\n\t\t\t\t\"debug\": \"on\",\n\t\t\t\t\"window\": {\n\t\t\t\t\t\"title\": \"Sample Konfabulator Widget\",\n\t\t\t\t\t\"name\": \"main_window\",\n\t\t\t\t\t\"width\": 500,\n\t\t\t\t\t\"height\": 500\n\t\t\t\t},\n\t\t\t\t\"image\": { \n\t\t\t\t\t\"src\": \"Images/Sun.png\",\n\t\t\t\t\t\"name\": \"sun1\",\n\t\t\t\t\t\"hOffset\": 250,\n\t\t\t\t\t\"vOffset\": 250,\n\t\t\t\t\t\"alignment\": \"center\"\n\t\t\t\t},\n\t\t\t\t\"text\": {\n\t\t\t\t\t\"data\": \"Click Here\",\n\t\t\t\t\t\"size\": 36,\n\t\t\t\t\t\"style\": \"bold\",\n\t\t\t\t\t\"name\": \"text1\",\n\t\t\t\t\t\"hOffset\": 250,\n\t\t\t\t\t\"vOffset\": 100,\n\t\t\t\t\t\"alignment\": \"center\",\n\t\t\t\t\t\"onMouseUp\": \"sun1.opacity = (sun1.opacity / 100) * 90;\"\n\t\t\t\t}\n\t\t\t}}    `,\n\t\t},\n\t\t{\n\t\t\tname: \"web-app\",\n\t\t\tvalue: `{\"web-app\": {\n\t\t\t\t\"servlet\": [   \n\t\t\t\t  {\n\t\t\t\t\t\"servlet-name\": \"cofaxCDS\",\n\t\t\t\t\t\"servlet-class\": \"org.cofax.cds.CDSServlet\",\n\t\t\t\t\t\"init-param\": {\n\t\t\t\t\t  \"configGlossary:installationAt\": \"Philadelphia, PA\",\n\t\t\t\t\t  \"configGlossary:adminEmail\": \"ksm@pobox.com\",\n\t\t\t\t\t  \"configGlossary:poweredBy\": \"Cofax\",\n\t\t\t\t\t  \"configGlossary:poweredByIcon\": \"/images/cofax.gif\",\n\t\t\t\t\t  \"configGlossary:staticPath\": \"/content/static\",\n\t\t\t\t\t  \"templateProcessorClass\": \"org.cofax.WysiwygTemplate\",\n\t\t\t\t\t  \"templateLoaderClass\": \"org.cofax.FilesTemplateLoader\",\n\t\t\t\t\t  \"templatePath\": \"templates\",\n\t\t\t\t\t  \"templateOverridePath\": \"\",\n\t\t\t\t\t  \"defaultListTemplate\": \"listTemplate.htm\",\n\t\t\t\t\t  \"defaultFileTemplate\": \"articleTemplate.htm\",\n\t\t\t\t\t  \"useJSP\": false,\n\t\t\t\t\t  \"jspListTemplate\": \"listTemplate.jsp\",\n\t\t\t\t\t  \"jspFileTemplate\": \"articleTemplate.jsp\",\n\t\t\t\t\t  \"cachePackageTagsTrack\": 200,\n\t\t\t\t\t  \"cachePackageTagsStore\": 200,\n\t\t\t\t\t  \"cachePackageTagsRefresh\": 60,\n\t\t\t\t\t  \"cacheTemplatesTrack\": 100,\n\t\t\t\t\t  \"cacheTemplatesStore\": 50,\n\t\t\t\t\t  \"cacheTemplatesRefresh\": 15,\n\t\t\t\t\t  \"cachePagesTrack\": 200,\n\t\t\t\t\t  \"cachePagesStore\": 100,\n\t\t\t\t\t  \"cachePagesRefresh\": 10,\n\t\t\t\t\t  \"cachePagesDirtyRead\": 10,\n\t\t\t\t\t  \"searchEngineListTemplate\": \"forSearchEnginesList.htm\",\n\t\t\t\t\t  \"searchEngineFileTemplate\": \"forSearchEngines.htm\",\n\t\t\t\t\t  \"searchEngineRobotsDb\": \"WEB-INF/robots.db\",\n\t\t\t\t\t  \"useDataStore\": true,\n\t\t\t\t\t  \"dataStoreClass\": \"org.cofax.SqlDataStore\",\n\t\t\t\t\t  \"redirectionClass\": \"org.cofax.SqlRedirection\",\n\t\t\t\t\t  \"dataStoreName\": \"cofax\",\n\t\t\t\t\t  \"dataStoreDriver\": \"com.microsoft.jdbc.sqlserver.SQLServerDriver\",\n\t\t\t\t\t  \"dataStoreUrl\": \"jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon\",\n\t\t\t\t\t  \"dataStoreUser\": \"sa\",\n\t\t\t\t\t  \"dataStorePassword\": \"dataStoreTestQuery\",\n\t\t\t\t\t  \"dataStoreTestQuery\": \"SET NOCOUNT ON;select test='test';\",\n\t\t\t\t\t  \"dataStoreLogFile\": \"/usr/local/tomcat/logs/datastore.log\",\n\t\t\t\t\t  \"dataStoreInitConns\": 10,\n\t\t\t\t\t  \"dataStoreMaxConns\": 100,\n\t\t\t\t\t  \"dataStoreConnUsageLimit\": 100,\n\t\t\t\t\t  \"dataStoreLogLevel\": \"debug\",\n\t\t\t\t\t  \"maxUrlLength\": 500}},\n\t\t\t\t  {\n\t\t\t\t\t\"servlet-name\": \"cofaxEmail\",\n\t\t\t\t\t\"servlet-class\": \"org.cofax.cds.EmailServlet\",\n\t\t\t\t\t\"init-param\": {\n\t\t\t\t\t\"mailHost\": \"mail1\",\n\t\t\t\t\t\"mailHostOverride\": \"mail2\"}},\n\t\t\t\t  {\n\t\t\t\t\t\"servlet-name\": \"cofaxAdmin\",\n\t\t\t\t\t\"servlet-class\": \"org.cofax.cds.AdminServlet\"},\n\t\t\t   \n\t\t\t\t  {\n\t\t\t\t\t\"servlet-name\": \"fileServlet\",\n\t\t\t\t\t\"servlet-class\": \"org.cofax.cds.FileServlet\"},\n\t\t\t\t  {\n\t\t\t\t\t\"servlet-name\": \"cofaxTools\",\n\t\t\t\t\t\"servlet-class\": \"org.cofax.cms.CofaxToolsServlet\",\n\t\t\t\t\t\"init-param\": {\n\t\t\t\t\t  \"templatePath\": \"toolstemplates/\",\n\t\t\t\t\t  \"log\": 1,\n\t\t\t\t\t  \"logLocation\": \"/usr/local/tomcat/logs/CofaxTools.log\",\n\t\t\t\t\t  \"logMaxSize\": \"\",\n\t\t\t\t\t  \"dataLog\": 1,\n\t\t\t\t\t  \"dataLogLocation\": \"/usr/local/tomcat/logs/dataLog.log\",\n\t\t\t\t\t  \"dataLogMaxSize\": \"\",\n\t\t\t\t\t  \"removePageCache\": \"/content/admin/remove?cache=pages\u0026id=\",\n\t\t\t\t\t  \"removeTemplateCache\": \"/content/admin/remove?cache=templates\u0026id=\",\n\t\t\t\t\t  \"fileTransferFolder\": \"/usr/local/tomcat/webapps/content/fileTransferFolder\",\n\t\t\t\t\t  \"lookInContext\": 1,\n\t\t\t\t\t  \"adminGroupID\": 4,\n\t\t\t\t\t  \"betaServer\": true}}],\n\t\t\t\t\"servlet-mapping\": {\n\t\t\t\t  \"cofaxCDS\": \"/\",\n\t\t\t\t  \"cofaxEmail\": \"/cofaxutil/aemail/*\",\n\t\t\t\t  \"cofaxAdmin\": \"/admin/*\",\n\t\t\t\t  \"fileServlet\": \"/static/*\",\n\t\t\t\t  \"cofaxTools\": \"/tools/*\"},\n\t\t\t   \n\t\t\t\t\"taglib\": {\n\t\t\t\t  \"taglib-uri\": \"cofax.tld\",\n\t\t\t\t  \"taglib-location\": \"/WEB-INF/tlds/cofax.tld\"}}}`,\n\t\t},\n\t\t{\n\t\t\tname: \"SVG Viewer\",\n\t\t\tvalue: `{\"menu\": {\n\t\t\t\t\"header\": \"SVG Viewer\",\n\t\t\t\t\"items\": [\n\t\t\t\t\t{\"id\": \"Open\"},\n\t\t\t\t\t{\"id\": \"OpenNew\", \"label\": \"Open New\"},\n\t\t\t\t\tnull,\n\t\t\t\t\t{\"id\": \"ZoomIn\", \"label\": \"Zoom In\"},\n\t\t\t\t\t{\"id\": \"ZoomOut\", \"label\": \"Zoom Out\"},\n\t\t\t\t\t{\"id\": \"OriginalView\", \"label\": \"Original View\"},\n\t\t\t\t\tnull,\n\t\t\t\t\t{\"id\": \"Quality\"},\n\t\t\t\t\t{\"id\": \"Pause\"},\n\t\t\t\t\t{\"id\": \"Mute\"},\n\t\t\t\t\tnull,\n\t\t\t\t\t{\"id\": \"Find\", \"label\": \"Find...\"},\n\t\t\t\t\t{\"id\": \"FindAgain\", \"label\": \"Find Again\"},\n\t\t\t\t\t{\"id\": \"Copy\"},\n\t\t\t\t\t{\"id\": \"CopyAgain\", \"label\": \"Copy Again\"},\n\t\t\t\t\t{\"id\": \"CopySVG\", \"label\": \"Copy SVG\"},\n\t\t\t\t\t{\"id\": \"ViewSVG\", \"label\": \"View SVG\"},\n\t\t\t\t\t{\"id\": \"ViewSource\", \"label\": \"View Source\"},\n\t\t\t\t\t{\"id\": \"SaveAs\", \"label\": \"Save As\"},\n\t\t\t\t\tnull,\n\t\t\t\t\t{\"id\": \"Help\"},\n\t\t\t\t\t{\"id\": \"About\", \"label\": \"About Adobe CVG Viewer...\"}\n\t\t\t\t]\n\t\t\t}}`,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t_, err := Unmarshal([]byte(test.value))\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Error on Unmarshal: %s\", err.Error())\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestUnmarshalSafe(t *testing.T) {\n\tjson := []byte(`{ \"store\": {\n\t\t\"book\": [ \n\t\t  { \"category\": \"reference\",\n\t\t\t\"author\": \"Nigel Rees\",\n\t\t\t\"title\": \"Sayings of the Century\",\n\t\t\t\"price\": 8.95\n\t\t  },\n\t\t  { \"category\": \"fiction\",\n\t\t\t\"author\": \"Evelyn Waugh\",\n\t\t\t\"title\": \"Sword of Honour\",\n\t\t\t\"price\": 12.99\n\t\t  },\n\t\t  { \"category\": \"fiction\",\n\t\t\t\"author\": \"Herman Melville\",\n\t\t\t\"title\": \"Moby Dick\",\n\t\t\t\"isbn\": \"0-553-21311-3\",\n\t\t\t\"price\": 8.99\n\t\t  },\n\t\t  { \"category\": \"fiction\",\n\t\t\t\"author\": \"J. R. R. Tolkien\",\n\t\t\t\"title\": \"The Lord of the Rings\",\n\t\t\t\"isbn\": \"0-395-19395-8\",\n\t\t\t\"price\": 22.99\n\t\t  }\n\t\t],\n\t\t\"bicycle\": {\n\t\t  \"color\": \"red\",\n\t\t  \"price\": 19.95\n\t\t}\n\t  }\n\t}`)\n\tsafe, err := UnmarshalSafe(json)\n\tif err != nil {\n\t\tt.Errorf(\"Error on Unmarshal: %s\", err.Error())\n\t} else if safe == nil {\n\t\tt.Errorf(\"Error on Unmarshal: safe is nil\")\n\t} else {\n\t\troot, err := Unmarshal(json)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Error on Unmarshal: %s\", err.Error())\n\t\t} else if root == nil {\n\t\t\tt.Errorf(\"Error on Unmarshal: root is nil\")\n\t\t} else if !bytes.Equal(root.source(), safe.source()) {\n\t\t\tt.Errorf(\"Error on UnmarshalSafe: values not same\")\n\t\t}\n\t}\n}\n\n// BenchmarkGoStdUnmarshal-8   \t   61698\t     19350 ns/op\t     288 B/op\t       6 allocs/op\n// BenchmarkUnmarshal-8        \t   45620\t     26165 ns/op\t   21889 B/op\t     367 allocs/op\n//\n// type bench struct {\n// \tName  string `json:\"name\"`\n// \tValue int    `json:\"value\"`\n// }\n\n// func BenchmarkGoStdUnmarshal(b *testing.B) {\n// \tdata := []byte(webApp)\n// \tfor i := 0; i \u003c b.N; i++ {\n// \t\terr := json.Unmarshal(data, \u0026bench{})\n// \t\tif err != nil {\n// \t\t\tb.Fatal(err)\n// \t\t}\n// \t}\n// }\n\n// func BenchmarkUnmarshal(b *testing.B) {\n// \tdata := []byte(webApp)\n// \tfor i := 0; i \u003c b.N; i++ {\n// \t\t_, err := Unmarshal(data)\n// \t\tif err != nil {\n// \t\t\tb.Fatal(err)\n// \t\t}\n// \t}\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":"encode_test.gno","body":"package json\n\nimport \"testing\"\n\nfunc TestMarshal_Primitive(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tnode *Node\n\t}{\n\t\t{\n\t\t\tname: \"null\",\n\t\t\tnode: NullNode(\"\"),\n\t\t},\n\t\t{\n\t\t\tname: \"true\",\n\t\t\tnode: BoolNode(\"\", true),\n\t\t},\n\t\t{\n\t\t\tname: \"false\",\n\t\t\tnode: BoolNode(\"\", false),\n\t\t},\n\t\t{\n\t\t\tname: `\"string\"`,\n\t\t\tnode: StringNode(\"\", \"string\"),\n\t\t},\n\t\t{\n\t\t\tname: `\"one \\\"encoded\\\" string\"`,\n\t\t\tnode: StringNode(\"\", `one \"encoded\" string`),\n\t\t},\n\t\t{\n\t\t\tname: `{\"foo\":\"bar\"}`,\n\t\t\tnode: ObjectNode(\"\", map[string]*Node{\n\t\t\t\t\"foo\": StringNode(\"foo\", \"bar\"),\n\t\t\t}),\n\t\t},\n\t\t{\n\t\t\tname: \"42\",\n\t\t\tnode: NumberNode(\"\", 42),\n\t\t},\n\t\t{\n\t\t\tname: \"3.14\",\n\t\t\tnode: NumberNode(\"\", 3.14),\n\t\t},\n\t\t{\n\t\t\tname: `[1,2,3]`,\n\t\t\tnode: ArrayNode(\"\", []*Node{\n\t\t\t\tNumberNode(\"0\", 1),\n\t\t\t\tNumberNode(\"2\", 2),\n\t\t\t\tNumberNode(\"3\", 3),\n\t\t\t}),\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tvalue, err := Marshal(test.node)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"unexpected error: %s\", err)\n\t\t\t} else if string(value) != test.name {\n\t\t\t\tt.Errorf(\"wrong result: '%s', expected '%s'\", value, test.name)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMarshal_Object(t *testing.T) {\n\tnode := ObjectNode(\"\", map[string]*Node{\n\t\t\"foo\": StringNode(\"foo\", \"bar\"),\n\t\t\"baz\": NumberNode(\"baz\", 100500),\n\t\t\"qux\": NullNode(\"qux\"),\n\t})\n\n\tmustKey := []string{\"foo\", \"baz\", \"qux\"}\n\n\tvalue, err := Marshal(node)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error: %s\", err)\n\t}\n\n\t// the order of keys in the map is not guaranteed\n\t// so we need to unmarshal the result and check the keys\n\tdecoded, err := Unmarshal(value)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error: %s\", err)\n\t}\n\n\tfor _, key := range mustKey {\n\t\tif node, err := decoded.GetKey(key); err != nil {\n\t\t\tt.Errorf(\"unexpected error: %s\", err)\n\t\t} else {\n\t\t\tif node == nil {\n\t\t\t\tt.Errorf(\"node is nil\")\n\t\t\t} else if node.key == nil {\n\t\t\t\tt.Errorf(\"key is nil\")\n\t\t\t} else if *node.key != key {\n\t\t\t\tt.Errorf(\"wrong key: '%s', expected '%s'\", *node.key, key)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc valueNode(prev *Node, key string, typ ValueType, val any) *Node {\n\tcurr := \u0026Node{\n\t\tprev:     prev,\n\t\tdata:     nil,\n\t\tkey:      \u0026key,\n\t\tborders:  [2]int{0, 0},\n\t\tvalue:    val,\n\t\tmodified: true,\n\t}\n\n\tif val != nil {\n\t\tcurr.nodeType = typ\n\t}\n\n\treturn curr\n}\n\nfunc TestMarshal_Errors(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tnode func() (node *Node)\n\t}{\n\t\t{\n\t\t\tname: \"nil\",\n\t\t\tnode: func() (node *Node) {\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"broken\",\n\t\t\tnode: func() (node *Node) {\n\t\t\t\tnode = Must(Unmarshal([]byte(`{}`)))\n\t\t\t\tnode.borders[1] = 0\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Numeric\",\n\t\t\tnode: func() (node *Node) {\n\t\t\t\treturn valueNode(nil, \"\", Number, false)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"String\",\n\t\t\tnode: func() (node *Node) {\n\t\t\t\treturn valueNode(nil, \"\", String, false)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Bool\",\n\t\t\tnode: func() (node *Node) {\n\t\t\t\treturn valueNode(nil, \"\", Boolean, 1)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Array_1\",\n\t\t\tnode: func() (node *Node) {\n\t\t\t\tnode = ArrayNode(\"\", nil)\n\t\t\t\tnode.next[\"1\"] = NullNode(\"1\")\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Array_2\",\n\t\t\tnode: func() (node *Node) {\n\t\t\t\treturn ArrayNode(\"\", []*Node{valueNode(nil, \"\", Boolean, 1)})\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Object\",\n\t\t\tnode: func() (node *Node) {\n\t\t\t\treturn ObjectNode(\"\", map[string]*Node{\"key\": valueNode(nil, \"key\", Boolean, 1)})\n\t\t\t},\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tvalue, err := Marshal(test.node())\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"expected error\")\n\t\t\t} else if len(value) != 0 {\n\t\t\t\tt.Errorf(\"wrong result\")\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMarshal_Nil(t *testing.T) {\n\t_, err := Marshal(nil)\n\tif err == nil {\n\t\tt.Error(\"Expected error for nil node, but got nil\")\n\t}\n}\n\nfunc TestMarshal_NotModified(t *testing.T) {\n\tnode := \u0026Node{}\n\t_, err := Marshal(node)\n\tif err == nil {\n\t\tt.Error(\"Expected error for not modified node, but got nil\")\n\t}\n}\n\nfunc TestMarshalCycleReference(t *testing.T) {\n\tnode1 := \u0026Node{\n\t\tkey:      stringPtr(\"node1\"),\n\t\tnodeType: String,\n\t\tnext: map[string]*Node{\n\t\t\t\"next\": nil,\n\t\t},\n\t}\n\n\tnode2 := \u0026Node{\n\t\tkey:      stringPtr(\"node2\"),\n\t\tnodeType: String,\n\t\tprev:     node1,\n\t}\n\n\tnode1.next[\"next\"] = node2\n\n\t_, err := Marshal(node1)\n\tif err == nil {\n\t\tt.Error(\"Expected error for cycle reference, but got nil\")\n\t}\n}\n\nfunc TestMarshalNoCycleReference(t *testing.T) {\n\tnode1 := \u0026Node{\n\t\tkey:      stringPtr(\"node1\"),\n\t\tnodeType: String,\n\t\tvalue:    \"value1\",\n\t\tmodified: true,\n\t}\n\n\tnode2 := \u0026Node{\n\t\tkey:      stringPtr(\"node2\"),\n\t\tnodeType: String,\n\t\tvalue:    \"value2\",\n\t\tmodified: true,\n\t}\n\n\t_, err := Marshal(node1)\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\t_, err = Marshal(node2)\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n}\n\nfunc stringPtr(s string) *string {\n\treturn \u0026s\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":"escape_test.gno","body":"package json\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\t\"unicode/utf8\"\n)\n\nfunc TestHexToInt(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tc    byte\n\t\twant int\n\t}{\n\t\t{\"Digit 0\", '0', 0},\n\t\t{\"Digit 9\", '9', 9},\n\t\t{\"Uppercase A\", 'A', 10},\n\t\t{\"Uppercase F\", 'F', 15},\n\t\t{\"Lowercase a\", 'a', 10},\n\t\t{\"Lowercase f\", 'f', 15},\n\t\t{\"Invalid character1\", 'g', badHex},\n\t\t{\"Invalid character2\", 'G', badHex},\n\t\t{\"Invalid character3\", 'z', badHex},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := h2i(tt.c); got != tt.want {\n\t\t\t\tt.Errorf(\"h2i() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestIsSurrogatePair(t *testing.T) {\n\ttestCases := []struct {\n\t\tname     string\n\t\tr        rune\n\t\texpected bool\n\t}{\n\t\t{\"high surrogate start\", 0xD800, true},\n\t\t{\"high surrogate end\", 0xDBFF, true},\n\t\t{\"low surrogate start\", 0xDC00, true},\n\t\t{\"low surrogate end\", 0xDFFF, true},\n\t\t{\"Non-surrogate\", 0x0000, false},\n\t\t{\"Non-surrogate 2\", 0xE000, false},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tif got := isSurrogatePair(tc.r); got != tc.expected {\n\t\t\t\tt.Errorf(\"isSurrogate() = %v, want %v\", got, tc.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCombineSurrogates(t *testing.T) {\n\ttestCases := []struct {\n\t\thigh, low rune\n\t\texpected  rune\n\t}{\n\t\t{0xD83D, 0xDC36, 0x1F436}, // 🐶 U+1F436 DOG FACE\n\t\t{0xD83D, 0xDE00, 0x1F600}, // 😀 U+1F600 GRINNING FACE\n\t\t{0xD83C, 0xDF03, 0x1F303}, // 🌃 U+1F303 NIGHT WITH STARS\n\t}\n\n\tfor _, tc := range testCases {\n\t\tresult := combineSurrogates(tc.high, tc.low)\n\t\tif result != tc.expected {\n\t\t\tt.Errorf(\"combineSurrogates(%U, %U) = %U; want %U\", tc.high, tc.low, result, tc.expected)\n\t\t}\n\t}\n}\n\nfunc TestDecodeSingleUnicodeEscape(t *testing.T) {\n\ttestCases := []struct {\n\t\tinput    []byte\n\t\texpected rune\n\t\tisValid  bool\n\t}{\n\t\t// valid unicode escape sequences\n\t\t{[]byte(`\\u0041`), 'A', true},\n\t\t{[]byte(`\\u03B1`), 'α', true},\n\t\t{[]byte(`\\u00E9`), 'é', true}, // valid non-English character\n\t\t{[]byte(`\\u0021`), '!', true}, // valid special character\n\t\t{[]byte(`\\uFF11`), '１', true},\n\t\t{[]byte(`\\uD83D`), 0xD83D, true},\n\t\t{[]byte(`\\uDE03`), 0xDE03, true},\n\n\t\t// invalid unicode escape sequences\n\t\t{[]byte(`\\u004`), utf8.RuneError, false},  // too short\n\t\t{[]byte(`\\uXYZW`), utf8.RuneError, false}, // invalid hex\n\t\t{[]byte(`\\u00G1`), utf8.RuneError, false}, // non-hex character\n\t}\n\n\tfor _, tc := range testCases {\n\t\tresult, isValid := decodeSingleUnicodeEscape(tc.input)\n\t\tif result != tc.expected || isValid != tc.isValid {\n\t\t\tt.Errorf(\"decodeSingleUnicodeEscape(%s) = (%U, %v); want (%U, %v)\", tc.input, result, isValid, tc.expected, tc.isValid)\n\t\t}\n\t}\n}\n\nfunc TestDecodeUnicodeEscape(t *testing.T) {\n\ttests := []struct {\n\t\tinput    []byte\n\t\texpected rune\n\t\tsize     int\n\t}{\n\t\t{[]byte(`\\u0041`), 'A', 6},\n\t\t{[]byte(`\\uD83D\\uDE00`), 0x1F600, 12}, // 😀\n\t\t{[]byte(`\\uD834\\uDD1E`), 0x1D11E, 12}, // 𝄞\n\t\t{[]byte(`\\uFFFF`), '\\uFFFF', 6},\n\t\t{[]byte(`\\uXYZW`), utf8.RuneError, -1},\n\t\t{[]byte(`\\uD800`), utf8.RuneError, -1},       // single high surrogate\n\t\t{[]byte(`\\uDC00`), utf8.RuneError, -1},       // single low surrogate\n\t\t{[]byte(`\\uD800\\uDC00`), 0x10000, 12},        // First code point above U+FFFF\n\t\t{[]byte(`\\uDBFF\\uDFFF`), 0x10FFFF, 12},       // Maximum code point\n\t\t{[]byte(`\\uD83D\\u0041`), utf8.RuneError, -1}, // invalid surrogate pair\n\t}\n\n\tfor _, tc := range tests {\n\t\tr, size := decodeUnicodeEscape(tc.input)\n\t\tif r != tc.expected || size != tc.size {\n\t\t\tt.Errorf(\"decodeUnicodeEscape(%q) = (%U, %d); want (%U, %d)\", tc.input, r, size, tc.expected, tc.size)\n\t\t}\n\t}\n}\n\nfunc TestUnescapeToUTF8(t *testing.T) {\n\ttests := []struct {\n\t\tinput       []byte\n\t\texpectedIn  int\n\t\texpectedOut int\n\t\tisError     bool\n\t}{\n\t\t// valid escape sequences\n\t\t{[]byte(`\\n`), 2, 1, false},\n\t\t{[]byte(`\\t`), 2, 1, false},\n\t\t{[]byte(`\\u0041`), 6, 1, false},\n\t\t{[]byte(`\\u03B1`), 6, 2, false},\n\t\t{[]byte(`\\uD830\\uDE03`), 12, 4, false},\n\n\t\t// invalid escape sequences\n\t\t{[]byte(`\\`), -1, -1, true},            // incomplete escape sequence\n\t\t{[]byte(`\\x`), -1, -1, true},           // invalid escape character\n\t\t{[]byte(`\\u`), -1, -1, true},           // incomplete unicode escape sequence\n\t\t{[]byte(`\\u004`), -1, -1, true},        // invalid unicode escape sequence\n\t\t{[]byte(`\\uXYZW`), -1, -1, true},       // invalid unicode escape sequence\n\t\t{[]byte(`\\uD83D\\u0041`), -1, -1, true}, // invalid unicode escape sequence\n\t}\n\n\tfor _, tc := range tests {\n\t\tinput := make([]byte, len(tc.input))\n\t\tcopy(input, tc.input)\n\t\toutput := make([]byte, utf8.UTFMax)\n\t\tinLen, outLen, err := processEscapedUTF8(input, output)\n\t\tif (err != nil) != tc.isError {\n\t\t\tt.Errorf(\"processEscapedUTF8(%q) = %v; want %v\", tc.input, err, tc.isError)\n\t\t}\n\n\t\tif inLen != tc.expectedIn || outLen != tc.expectedOut {\n\t\t\tt.Errorf(\"processEscapedUTF8(%q) = (%d, %d); want (%d, %d)\", tc.input, inLen, outLen, tc.expectedIn, tc.expectedOut)\n\t\t}\n\t}\n}\n\nfunc TestUnescape(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    []byte\n\t\texpected []byte\n\t\tisError  bool\n\t}{\n\t\t{\"NoEscape\", []byte(\"hello world\"), []byte(\"hello world\"), false},\n\t\t{\"SingleEscape\", []byte(\"hello\\\\nworld\"), []byte(\"hello\\nworld\"), false},\n\t\t{\"MultipleEscapes\", []byte(\"line1\\\\nline2\\\\r\\\\nline3\"), []byte(\"line1\\nline2\\r\\nline3\"), false},\n\t\t{\"UnicodeEscape\", []byte(\"snowman:\\\\u2603\"), []byte(\"snowman:\\u2603\"), false},\n\t\t{\"SurrogatePair\", []byte(\"emoji:\\\\uD83D\\\\uDE00\"), []byte(\"emoji:😀\"), false},\n\t\t{\"InvalidEscape\", []byte(\"hello\\\\xworld\"), nil, true},\n\t\t{\"IncompleteUnicode\", []byte(\"incomplete:\\\\u123\"), nil, true},\n\t\t{\"InvalidSurrogatePair\", []byte(\"invalid:\\\\uD83D\\\\u0041\"), nil, true},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\toutput := make([]byte, len(tc.input)*2) // Allocate extra space for possible expansion\n\t\t\tresult, err := Unescape(tc.input, output)\n\t\t\tif (err != nil) != tc.isError {\n\t\t\t\tt.Errorf(\"Unescape(%q) error = %v; want error = %v\", tc.input, err, tc.isError)\n\t\t\t}\n\n\t\t\tif !tc.isError \u0026\u0026 !bytes.Equal(result, tc.expected) {\n\t\t\t\tt.Errorf(\"Unescape(%q) = %q; want %q\", tc.input, result, tc.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestUnquoteBytes(t *testing.T) {\n\ttests := []struct {\n\t\tinput    []byte\n\t\tborder   byte\n\t\texpected []byte\n\t\tok       bool\n\t}{\n\t\t{[]byte(\"\\\"hello\\\"\"), '\"', []byte(\"hello\"), true},\n\t\t{[]byte(\"'hello'\"), '\\'', []byte(\"hello\"), true},\n\t\t{[]byte(\"\\\"hello\"), '\"', nil, false},\n\t\t{[]byte(\"hello\\\"\"), '\"', nil, false},\n\t\t{[]byte(\"\\\"he\\\\\\\"llo\\\"\"), '\"', []byte(\"he\\\"llo\"), true},\n\t\t{[]byte(\"\\\"he\\\\nllo\\\"\"), '\"', []byte(\"he\\nllo\"), true},\n\t\t{[]byte(\"\\\"\\\"\"), '\"', []byte(\"\"), true},\n\t\t{[]byte(\"''\"), '\\'', []byte(\"\"), true},\n\t\t{[]byte(\"\\\"\\\\u0041\\\"\"), '\"', []byte(\"A\"), true},\n\t\t{[]byte(`\"Hello, 世界\"`), '\"', []byte(\"Hello, 世界\"), true},\n\t\t{[]byte(`\"Hello, \\x80\"`), '\"', nil, false},\n\t\t{[]byte(`\"invalid surrogate: \\uD83D\\u0041\"`), '\"', nil, false},\n\t}\n\n\tfor _, tc := range tests {\n\t\tresult, pass := unquoteBytes(tc.input, tc.border)\n\n\t\tif pass != tc.ok {\n\t\t\tt.Errorf(\"unquoteBytes(%q) = %v; want %v\", tc.input, pass, tc.ok)\n\t\t}\n\n\t\tif !bytes.Equal(result, tc.expected) {\n\t\t\tt.Errorf(\"unquoteBytes(%q) = %q; want %q\", tc.input, result, tc.expected)\n\t\t}\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/onbloc/json\"\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":"indent_test.gno","body":"package json\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\nfunc TestIndentJSON(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    []byte\n\t\tindent   string\n\t\texpected []byte\n\t}{\n\t\t{\n\t\t\tname:     \"empty object\",\n\t\t\tinput:    []byte(`{}`),\n\t\t\tindent:   \"  \",\n\t\t\texpected: []byte(`{}`),\n\t\t},\n\t\t{\n\t\t\tname:     \"empty array\",\n\t\t\tinput:    []byte(`[]`),\n\t\t\tindent:   \"  \",\n\t\t\texpected: []byte(`[]`),\n\t\t},\n\t\t{\n\t\t\tname:     \"nested object\",\n\t\t\tinput:    []byte(`{{}}`),\n\t\t\tindent:   \"\\t\",\n\t\t\texpected: []byte(\"{\\n\\t\\t{}\\n}\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"nested array\",\n\t\t\tinput:    []byte(`[[[]]]`),\n\t\t\tindent:   \"\\t\",\n\t\t\texpected: []byte(\"[[\\n\\t\\t[\\n\\t\\t\\t\\t\\n\\t\\t]\\n]]\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"top-level array\",\n\t\t\tinput:    []byte(`[\"apple\",\"banana\",\"cherry\"]`),\n\t\t\tindent:   \"\\t\",\n\t\t\texpected: []byte(`[\"apple\",\"banana\",\"cherry\"]`),\n\t\t},\n\t\t{\n\t\t\tname:     \"array of arrays\",\n\t\t\tinput:    []byte(`[\"apple\",[\"banana\",\"cherry\"],\"date\"]`),\n\t\t\tindent:   \"  \",\n\t\t\texpected: []byte(\"[\\\"apple\\\",[\\n    \\\"banana\\\",\\n    \\\"cherry\\\"\\n],\\\"date\\\"]\"),\n\t\t},\n\n\t\t{\n\t\t\tname:     \"nested array in object\",\n\t\t\tinput:    []byte(`{\"fruits\":[\"apple\",[\"banana\",\"cherry\"],\"date\"]}`),\n\t\t\tindent:   \"  \",\n\t\t\texpected: []byte(\"{\\n    \\\"fruits\\\": [\\\"apple\\\",[\\n        \\\"banana\\\",\\n        \\\"cherry\\\"\\n    ],\\\"date\\\"]\\n}\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"complex nested structure\",\n\t\t\tinput:    []byte(`{\"data\":{\"array\":[1,2,3],\"bool\":true,\"nestedArray\":[[\"a\",\"b\"],\"c\"]}}`),\n\t\t\tindent:   \"  \",\n\t\t\texpected: []byte(\"{\\n    \\\"data\\\": {\\n        \\\"array\\\": [1,2,3],\\\"bool\\\": true,\\\"nestedArray\\\": [[\\n            \\\"a\\\",\\n            \\\"b\\\"\\n        ],\\\"c\\\"]\\n    }\\n}\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"custom ident character\",\n\t\t\tinput:    []byte(`{\"fruits\":[\"apple\",[\"banana\",\"cherry\"],\"date\"]}`),\n\t\t\tindent:   \"*\",\n\t\t\texpected: []byte(\"{\\n**\\\"fruits\\\": [\\\"apple\\\",[\\n****\\\"banana\\\",\\n****\\\"cherry\\\"\\n**],\\\"date\\\"]\\n}\"),\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tactual, err := Indent(tt.input, tt.indent)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"IndentJSON() error = %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif !bytes.Equal(actual, tt.expected) {\n\t\t\t\tt.Errorf(\"IndentJSON() = %q, want %q\", actual, tt.expected)\n\t\t\t}\n\t\t})\n\t}\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":"node_test.gno","body":"package json\n\nimport (\n\t\"bytes\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nvar (\n\tnilKey   *string\n\tdummyKey = \"key\"\n)\n\ntype _args struct {\n\tprev *Node\n\tbuf  *buffer\n\ttyp  ValueType\n\tkey  **string\n}\n\ntype simpleNode struct {\n\tname string\n\tnode *Node\n}\n\nfunc TestNode_CreateNewNode(t *testing.T) {\n\trel := \u0026dummyKey\n\n\ttests := []struct {\n\t\tname        string\n\t\targs        _args\n\t\texpectCurr  *Node\n\t\texpectErr   bool\n\t\texpectPanic bool\n\t}{\n\t\t{\n\t\t\tname: \"child for non container type\",\n\t\t\targs: _args{\n\t\t\t\tprev: BoolNode(\"\", true),\n\t\t\t\tbuf:  newBuffer(make([]byte, 10)),\n\t\t\t\ttyp:  Boolean,\n\t\t\t\tkey:  \u0026rel,\n\t\t\t},\n\t\t\texpectCurr: nil,\n\t\t\texpectErr:  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\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tif tt.expectPanic {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tt.Errorf(\"%s panic occurred when not expected: %v\", tt.name, r)\n\t\t\t\t} else if tt.expectPanic {\n\t\t\t\t\tt.Errorf(\"%s expected panic but didn't occur\", tt.name)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tgot, err := NewNode(tt.args.prev, tt.args.buf, tt.args.typ, tt.args.key)\n\t\t\tif (err != nil) != tt.expectErr {\n\t\t\t\tt.Errorf(\"%s error = %v, expect error %v\", tt.name, err, tt.expectErr)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif tt.expectErr {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !compareNodes(got, tt.expectCurr) {\n\t\t\t\tt.Errorf(\"%s got = %v, want %v\", tt.name, got, tt.expectCurr)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNode_Value(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tdata        []byte\n\t\t_type       ValueType\n\t\texpected    any\n\t\terrExpected bool\n\t}{\n\t\t{name: \"null\", data: []byte(\"null\"), _type: Null, expected: nil},\n\t\t{name: \"1\", data: []byte(\"1\"), _type: Number, expected: float64(1)},\n\t\t{name: \".1\", data: []byte(\".1\"), _type: Number, expected: float64(.1)},\n\t\t{name: \"-.1e1\", data: []byte(\"-.1e1\"), _type: Number, expected: float64(-1)},\n\t\t{name: \"string\", data: []byte(\"\\\"foo\\\"\"), _type: String, expected: \"foo\"},\n\t\t{name: \"space\", data: []byte(\"\\\"foo bar\\\"\"), _type: String, expected: \"foo bar\"},\n\t\t{name: \"true\", data: []byte(\"true\"), _type: Boolean, expected: true},\n\t\t{name: \"invalid true\", data: []byte(\"tru\"), _type: Unknown, errExpected: true},\n\t\t{name: \"invalid false\", data: []byte(\"fals\"), _type: Unknown, errExpected: true},\n\t\t{name: \"false\", data: []byte(\"false\"), _type: Boolean, expected: false},\n\t\t{name: \"e1\", data: []byte(\"e1\"), _type: Unknown, errExpected: true},\n\t\t{name: \"1a\", data: []byte(\"1a\"), _type: Unknown, errExpected: true},\n\t\t{name: \"string error\", data: []byte(\"\\\"foo\\nbar\\\"\"), _type: String, errExpected: true},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcurr := \u0026Node{\n\t\t\t\tdata:     tt.data,\n\t\t\t\tnodeType: tt._type,\n\t\t\t\tborders:  [2]int{0, len(tt.data)},\n\t\t\t}\n\n\t\t\tgot, err := curr.Value()\n\t\t\tif err != nil {\n\t\t\t\tif !tt.errExpected {\n\t\t\t\t\tt.Errorf(\"%s error = %v, expect error %v\", tt.name, err, tt.errExpected)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif got != tt.expected {\n\t\t\t\tt.Errorf(\"%s got = %v, want %v\", tt.name, got, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNode_Delete(t *testing.T) {\n\troot := Must(Unmarshal([]byte(`{\"foo\":\"bar\"}`)))\n\tif err := root.Delete(); err != nil {\n\t\tt.Errorf(\"Delete returns error: %v\", err)\n\t}\n\n\tif value, err := Marshal(root); err != nil {\n\t\tt.Errorf(\"Marshal returns error: %v\", err)\n\t} else if string(value) != `{\"foo\":\"bar\"}` {\n\t\tt.Errorf(\"Marshal returns wrong value: %s\", string(value))\n\t}\n\n\tfoo := root.MustKey(\"foo\")\n\tif err := foo.Delete(); err != nil {\n\t\tt.Errorf(\"Delete returns error while handling foo: %v\", err)\n\t}\n\n\tif value, err := Marshal(root); err != nil {\n\t\tt.Errorf(\"Marshal returns error: %v\", err)\n\t} else if string(value) != `{}` {\n\t\tt.Errorf(\"Marshal returns wrong value: %s\", string(value))\n\t}\n\n\tif value, err := Marshal(foo); err != nil {\n\t\tt.Errorf(\"Marshal returns error: %v\", err)\n\t} else if string(value) != `\"bar\"` {\n\t\tt.Errorf(\"Marshal returns wrong value: %s\", string(value))\n\t}\n\n\tif foo.prev != nil {\n\t\tt.Errorf(\"foo.prev should be nil\")\n\t}\n}\n\nfunc TestNode_ObjectNode(t *testing.T) {\n\tobjs := map[string]*Node{\n\t\t\"key1\": NullNode(\"null\"),\n\t\t\"key2\": NumberNode(\"answer\", 42),\n\t\t\"key3\": StringNode(\"string\", \"foobar\"),\n\t\t\"key4\": BoolNode(\"bool\", true),\n\t}\n\n\tnode := ObjectNode(\"test\", objs)\n\n\tif len(node.next) != len(objs) {\n\t\tt.Errorf(\"ObjectNode: want %v got %v\", len(objs), len(node.next))\n\t}\n\n\tfor k, v := range objs {\n\t\tif node.next[k] == nil {\n\t\t\tt.Errorf(\"ObjectNode: want %v got %v\", v, node.next[k])\n\t\t}\n\t}\n}\n\nfunc TestNode_AppendObject(t *testing.T) {\n\tif err := Must(Unmarshal([]byte(`{\"foo\":\"bar\",\"baz\":null}`))).AppendObject(\"biz\", NullNode(\"\")); err != nil {\n\t\tt.Errorf(\"AppendArray should return error\")\n\t}\n\n\troot := Must(Unmarshal([]byte(`{\"foo\":\"bar\"}`)))\n\tif err := root.AppendObject(\"baz\", NullNode(\"\")); err != nil {\n\t\tt.Errorf(\"AppendObject should not return error: %s\", err)\n\t}\n\n\tif value, err := Marshal(root); err != nil {\n\t\tt.Errorf(\"Marshal returns error: %v\", err)\n\t} else if isSameObject(string(value), `\"{\"foo\":\"bar\",\"baz\":null}\"`) {\n\t\tt.Errorf(\"Marshal returns wrong value: %s\", string(value))\n\t}\n\n\t// FIXME: this may fail if execute test in more than 3 times in a row.\n\tif err := root.AppendObject(\"biz\", NumberNode(\"\", 42)); err != nil {\n\t\tt.Errorf(\"AppendObject returns error: %v\", err)\n\t}\n\n\tval, err := Marshal(root)\n\tif err != nil {\n\t\tt.Errorf(\"Marshal returns error: %v\", err)\n\t}\n\n\t// FIXME: this may fail if execute test in more than 3 times in a row.\n\tif isSameObject(string(val), `\"{\"foo\":\"bar\",\"baz\":null,\"biz\":42}\"`) {\n\t\tt.Errorf(\"Marshal returns wrong value: %s\", string(val))\n\t}\n}\n\nfunc TestNode_ArrayNode(t *testing.T) {\n\tarr := []*Node{\n\t\tNullNode(\"nil\"),\n\t\tNumberNode(\"num\", 42),\n\t\tStringNode(\"str\", \"foobar\"),\n\t\tBoolNode(\"bool\", true),\n\t}\n\n\tnode := ArrayNode(\"test\", arr)\n\n\tif len(node.next) != len(arr) {\n\t\tt.Errorf(\"ArrayNode: want %v got %v\", len(arr), len(node.next))\n\t}\n\n\tfor i, v := range arr {\n\t\tif node.next[strconv.Itoa(i)] == nil {\n\t\t\tt.Errorf(\"ArrayNode: want %v got %v\", v, node.next[strconv.Itoa(i)])\n\t\t}\n\t}\n}\n\nfunc TestNode_AppendArray(t *testing.T) {\n\tif err := Must(Unmarshal([]byte(`[{\"foo\":\"bar\"}]`))).AppendArray(NullNode(\"\")); err != nil {\n\t\tt.Errorf(\"should return error\")\n\t}\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\tif value, err := Marshal(root); err != nil {\n\t\tt.Errorf(\"Marshal returns error: %v\", err)\n\t} else if string(value) != `[{\"foo\":\"bar\"},null]` {\n\t\tt.Errorf(\"Marshal returns wrong value: %s\", string(value))\n\t}\n\n\tif err := root.AppendArray(\n\t\tNumberNode(\"\", 1),\n\t\tStringNode(\"\", \"foo\"),\n\t\tMust(Unmarshal([]byte(`[0,1,null,true,\"example\"]`))),\n\t\tMust(Unmarshal([]byte(`{\"foo\": true, \"bar\": null, \"baz\": 123}`))),\n\t); err != nil {\n\t\tt.Errorf(\"AppendArray returns error: %v\", err)\n\t}\n\n\tif value, err := Marshal(root); err != nil {\n\t\tt.Errorf(\"Marshal returns error: %v\", err)\n\t} else if string(value) != `[{\"foo\":\"bar\"},null,1,\"foo\",[0,1,null,true,\"example\"],{\"foo\": true, \"bar\": null, \"baz\": 123}]` {\n\t\tt.Errorf(\"Marshal returns wrong value: %s\", string(value))\n\t}\n}\n\n/******** value getter ********/\n\nfunc TestNode_GetBool(t *testing.T) {\n\troot, err := Unmarshal([]byte(`true`))\n\tif err != nil {\n\t\tt.Errorf(\"Error on Unmarshal(): %s\", err.Error())\n\t\treturn\n\t}\n\n\tvalue, err := root.GetBool()\n\tif err != nil {\n\t\tt.Errorf(\"Error on root.GetBool(): %s\", err.Error())\n\t}\n\n\tif !value {\n\t\tt.Errorf(\"root.GetBool() is corrupted\")\n\t}\n}\n\nfunc TestNode_GetBool_NotSucceed(t *testing.T) {\n\ttests := []simpleNode{\n\t\t{\"nil node\", (*Node)(nil)},\n\t\t{\"literally null node\", NullNode(\"\")},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif _, err := tt.node.GetBool(); err == nil {\n\t\t\t\tt.Errorf(\"%s should be an error\", tt.name)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNode_IsBool(t *testing.T) {\n\ttests := []simpleNode{\n\t\t{\"true\", BoolNode(\"\", true)},\n\t\t{\"false\", BoolNode(\"\", false)},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif !tt.node.IsBool() {\n\t\t\t\tt.Errorf(\"%s should be a bool\", tt.name)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNode_IsBool_With_Unmarshal(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tjson []byte\n\t\twant bool\n\t}{\n\t\t{\"true\", []byte(\"true\"), true},\n\t\t{\"false\", []byte(\"false\"), true},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\troot, err := Unmarshal(tt.json)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Error on Unmarshal(): %s\", err.Error())\n\t\t\t}\n\n\t\t\tif root.IsBool() != tt.want {\n\t\t\t\tt.Errorf(\"%s should be a bool\", tt.name)\n\t\t\t}\n\t\t})\n\t}\n}\n\nvar nullJson = []byte(`null`)\n\nfunc TestNode_GetNull(t *testing.T) {\n\troot, err := Unmarshal(nullJson)\n\tif err != nil {\n\t\tt.Errorf(\"Error on Unmarshal(): %s\", err.Error())\n\t}\n\n\tvalue, err := root.GetNull()\n\tif err != nil {\n\t\tt.Errorf(\"error occurred while getting null, %s\", err)\n\t}\n\n\tif value != nil {\n\t\tt.Errorf(\"value is not matched. expected: nil, got: %v\", value)\n\t}\n}\n\nfunc TestNode_GetNull_NotSucceed(t *testing.T) {\n\ttests := []simpleNode{\n\t\t{\"nil node\", (*Node)(nil)},\n\t\t{\"number node is null\", NumberNode(\"\", 42)},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif _, err := tt.node.GetNull(); err == nil {\n\t\t\t\tt.Errorf(\"%s should be an error\", tt.name)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNode_MustNull(t *testing.T) {\n\troot, err := Unmarshal(nullJson)\n\tif err != nil {\n\t\tt.Errorf(\"Error on Unmarshal(): %s\", err.Error())\n\t}\n\n\tvalue := root.MustNull()\n\tif value != nil {\n\t\tt.Errorf(\"value is not matched. expected: nil, got: %v\", value)\n\t}\n}\n\nfunc TestNode_GetNumeric_Float(t *testing.T) {\n\troot, err := Unmarshal([]byte(`123.456`))\n\tif err != nil {\n\t\tt.Errorf(\"Error on Unmarshal(): %s\", err)\n\t\treturn\n\t}\n\n\tvalue, err := root.GetNumeric()\n\tif err != nil {\n\t\tt.Errorf(\"Error on root.GetNumeric(): %s\", err)\n\t}\n\n\tif value != float64(123.456) {\n\t\tt.Errorf(ufmt.Sprintf(\"value is not matched. expected: 123.456, got: %v\", value))\n\t}\n}\n\nfunc TestNode_GetNumeric_Scientific_Notation(t *testing.T) {\n\troot, err := Unmarshal([]byte(`1e3`))\n\tif err != nil {\n\t\tt.Errorf(\"Error on Unmarshal(): %s\", err)\n\t\treturn\n\t}\n\n\tvalue, err := root.GetNumeric()\n\tif err != nil {\n\t\tt.Errorf(\"Error on root.GetNumeric(): %s\", err)\n\t}\n\n\tif value != float64(1000) {\n\t\tt.Errorf(ufmt.Sprintf(\"value is not matched. expected: 1000, got: %v\", value))\n\t}\n}\n\nfunc TestNode_GetNumeric_With_Unmarshal(t *testing.T) {\n\troot, err := Unmarshal([]byte(`123`))\n\tif err != nil {\n\t\tt.Errorf(\"Error on Unmarshal(): %s\", err)\n\t\treturn\n\t}\n\n\tvalue, err := root.GetNumeric()\n\tif err != nil {\n\t\tt.Errorf(\"Error on root.GetNumeric(): %s\", err)\n\t}\n\n\tif value != float64(123) {\n\t\tt.Errorf(ufmt.Sprintf(\"value is not matched. expected: 123, got: %v\", value))\n\t}\n}\n\nfunc TestNode_GetNumeric_NotSucceed(t *testing.T) {\n\ttests := []simpleNode{\n\t\t{\"nil node\", (*Node)(nil)},\n\t\t{\"null node\", NullNode(\"\")},\n\t\t{\"string node\", StringNode(\"\", \"123\")},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif _, err := tt.node.GetNumeric(); err == nil {\n\t\t\t\tt.Errorf(\"%s should be an error\", tt.name)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNode_GetString(t *testing.T) {\n\troot, err := Unmarshal([]byte(`\"123foobar 3456\"`))\n\tif err != nil {\n\t\tt.Errorf(\"Error on Unmarshal(): %s\", err)\n\t}\n\n\tvalue, err := root.GetString()\n\tif err != nil {\n\t\tt.Errorf(\"Error on root.GetString(): %s\", err)\n\t}\n\n\tif value != \"123foobar 3456\" {\n\t\tt.Errorf(ufmt.Sprintf(\"value is not matched. expected: 123, got: %s\", value))\n\t}\n}\n\nfunc TestNode_GetString_NotSucceed(t *testing.T) {\n\ttests := []simpleNode{\n\t\t{\"nil node\", (*Node)(nil)},\n\t\t{\"null node\", NullNode(\"\")},\n\t\t{\"number node\", NumberNode(\"\", 123)},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif _, err := tt.node.GetString(); err == nil {\n\t\t\t\tt.Errorf(\"%s should be an error\", tt.name)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNode_MustString(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tdata []byte\n\t}{\n\t\t{\"foo\", []byte(`\"foo\"`)},\n\t\t{\"foo bar\", []byte(`\"foo bar\"`)},\n\t\t{\"\", []byte(`\"\"`)},\n\t\t{\"안녕하세요\", []byte(`\"안녕하세요\"`)},\n\t\t{\"こんにちは\", []byte(`\"こんにちは\"`)},\n\t\t{\"你好\", []byte(`\"你好\"`)},\n\t\t{\"one \\\"encoded\\\" string\", []byte(`\"one \\\"encoded\\\" string\"`)},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\troot, err := Unmarshal(tt.data)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Error on Unmarshal(): %s\", err)\n\t\t\t}\n\n\t\t\tvalue := root.MustString()\n\t\t\tif value != tt.name {\n\t\t\t\tt.Errorf(\"value is not matched. expected: %s, got: %s\", tt.name, value)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestUnmarshal_Array(t *testing.T) {\n\troot, err := Unmarshal([]byte(\" [1,[\\\"1\\\",[1,[1,2,3]]]]\\r\\n\"))\n\tif err != nil {\n\t\tt.Errorf(\"Error on Unmarshal: %s\", err.Error())\n\t}\n\n\tif root == nil {\n\t\tt.Errorf(\"Error on Unmarshal: root is nil\")\n\t}\n\n\tif root.Type() != Array {\n\t\tt.Errorf(\"Error on Unmarshal: wrong type\")\n\t}\n\n\tarray, err := root.GetArray()\n\tif err != nil {\n\t\tt.Errorf(\"error occurred while getting array, %s\", err)\n\t} else if len(array) != 2 {\n\t\tt.Errorf(\"expected 2 elements, got %d\", len(array))\n\t} else if val, err := array[0].GetNumeric(); err != nil {\n\t\tt.Errorf(\"value of array[0] is not numeric. got: %v\", array[0].value)\n\t} else if val != 1 {\n\t\tt.Errorf(\"Error on array[0].GetNumeric(): expected to be '1', got: %v\", val)\n\t} else if val, err := array[1].GetArray(); err != nil {\n\t\tt.Errorf(\"error occurred while getting array, %s\", err.Error())\n\t} else if len(val) != 2 {\n\t\tt.Errorf(\"Error on array[1].GetArray(): expected 2 elements, got %d\", len(val))\n\t} else if el, err := val[0].GetString(); err != nil {\n\t\tt.Errorf(\"error occurred while getting string, %s\", err.Error())\n\t} else if el != \"1\" {\n\t\tt.Errorf(\"Error on val[0].GetString(): expected to be '1', got: %s\", el)\n\t}\n}\n\nvar sampleArr = []byte(`[-1, 2, 3, 4, 5, 6]`)\n\nfunc TestNode_GetArray(t *testing.T) {\n\troot, err := Unmarshal(sampleArr)\n\tif err != nil {\n\t\tt.Errorf(\"Error on Unmarshal(): %s\", err)\n\t\treturn\n\t}\n\n\tarray, err := root.GetArray()\n\tif err != nil {\n\t\tt.Errorf(\"Error on root.GetArray(): %s\", err)\n\t}\n\n\tif len(array) != 6 {\n\t\tt.Errorf(ufmt.Sprintf(\"length is not matched. expected: 3, got: %d\", len(array)))\n\t}\n\n\tfor i, node := range array {\n\t\tfor j, val := range []int{-1, 2, 3, 4, 5, 6} {\n\t\t\tif i == j {\n\t\t\t\tif v, err := node.GetNumeric(); err != nil {\n\t\t\t\t\tt.Errorf(ufmt.Sprintf(\"Error on node.GetNumeric(): %s\", err))\n\t\t\t\t} else if v != float64(val) {\n\t\t\t\t\tt.Errorf(ufmt.Sprintf(\"value is not matched. expected: %d, got: %v\", val, v))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestNode_GetArray_NotSucceed(t *testing.T) {\n\ttests := []simpleNode{\n\t\t{\"nil node\", (*Node)(nil)},\n\t\t{\"null node\", NullNode(\"\")},\n\t\t{\"number node\", NumberNode(\"\", 123)},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif _, err := tt.node.GetArray(); err == nil {\n\t\t\t\tt.Errorf(\"%s should be an error\", tt.name)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNode_IsArray(t *testing.T) {\n\troot, err := Unmarshal(sampleArr)\n\tif err != nil {\n\t\tt.Errorf(\"Error on Unmarshal(): %s\", err)\n\t\treturn\n\t}\n\n\tif root.Type() != Array {\n\t\tt.Errorf(ufmt.Sprintf(\"Must be an array. got: %s\", root.Type().String()))\n\t}\n}\n\nfunc TestNode_ArrayEach(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tjson     string\n\t\texpected []int\n\t}{\n\t\t{\n\t\t\tname:     \"empty array\",\n\t\t\tjson:     `[]`,\n\t\t\texpected: []int{},\n\t\t},\n\t\t{\n\t\t\tname:     \"single element\",\n\t\t\tjson:     `[42]`,\n\t\t\texpected: []int{42},\n\t\t},\n\t\t{\n\t\t\tname:     \"multiple elements\",\n\t\t\tjson:     `[1, 2, 3, 4, 5]`,\n\t\t\texpected: []int{1, 2, 3, 4, 5},\n\t\t},\n\t\t{\n\t\t\tname:     \"multiple elements but all values are same\",\n\t\t\tjson:     `[1, 1, 1, 1, 1]`,\n\t\t\texpected: []int{1, 1, 1, 1, 1},\n\t\t},\n\t\t{\n\t\t\tname:     \"multiple elements with non-numeric values\",\n\t\t\tjson:     `[\"a\", \"b\", \"c\", \"d\", \"e\"]`,\n\t\t\texpected: []int{},\n\t\t},\n\t\t{\n\t\t\tname:     \"non-array node\",\n\t\t\tjson:     `{\"not\": \"an array\"}`,\n\t\t\texpected: []int{},\n\t\t},\n\t\t{\n\t\t\tname:     \"array containing numeric and non-numeric elements\",\n\t\t\tjson:     `[\"1\", 2, 3, \"4\", 5, \"6\"]`,\n\t\t\texpected: []int{2, 3, 5},\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\troot, err := Unmarshal([]byte(tc.json))\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Unmarshal failed: %v\", err)\n\t\t\t}\n\n\t\t\tvar result []int // callback result\n\t\t\troot.ArrayEach(func(index int, element *Node) {\n\t\t\t\tif val, err := strconv.Atoi(element.String()); err == nil {\n\t\t\t\t\tresult = append(result, val)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tif len(result) != len(tc.expected) {\n\t\t\t\tt.Errorf(\"%s: expected %d elements, got %d\", tc.name, len(tc.expected), len(result))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor i, val := range result {\n\t\t\t\tif val != tc.expected[i] {\n\t\t\t\t\tt.Errorf(\"%s: expected value at index %d to be %d, got %d\", tc.name, i, tc.expected[i], val)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNode_Key(t *testing.T) {\n\troot, err := Unmarshal([]byte(`{\"foo\": true, \"bar\": null, \"baz\": 123, \"biz\": [1,2,3]}`))\n\tif err != nil {\n\t\tt.Errorf(\"Error on Unmarshal(): %s\", err.Error())\n\t}\n\n\tobj := root.MustObject()\n\tfor key, node := range obj {\n\t\tif key != node.Key() {\n\t\t\tt.Errorf(\"Key() = %v, want %v\", node.Key(), key)\n\t\t}\n\t}\n\n\tkeys := []string{\"foo\", \"bar\", \"baz\", \"biz\"}\n\tfor _, key := range keys {\n\t\tif obj[key].Key() != key {\n\t\t\tt.Errorf(\"Key() = %v, want %v\", obj[key].Key(), key)\n\t\t}\n\t}\n\n\t// TODO: resolve stack overflow\n\t// if root.MustKey(\"foo\").Clone().Key() != \"\" {\n\t// \tt.Errorf(\"wrong key found for cloned key\")\n\t// }\n\n\tif (*Node)(nil).Key() != \"\" {\n\t\tt.Errorf(\"wrong key found for nil node\")\n\t}\n}\n\nfunc TestNode_Size(t *testing.T) {\n\troot, err := Unmarshal(sampleArr)\n\tif err != nil {\n\t\tt.Errorf(\"error occurred while unmarshal\")\n\t}\n\n\tsize := root.Size()\n\tif size != 6 {\n\t\tt.Errorf(ufmt.Sprintf(\"Size() must be 6. got: %v\", size))\n\t}\n\n\tif (*Node)(nil).Size() != 0 {\n\t\tt.Errorf(ufmt.Sprintf(\"Size() must be 0. got: %v\", (*Node)(nil).Size()))\n\t}\n}\n\nfunc TestNode_Index(t *testing.T) {\n\troot, err := Unmarshal([]byte(`[1, 2, 3, 4, 5, 6]`))\n\tif err != nil {\n\t\tt.Error(\"error occurred while unmarshal\")\n\t}\n\n\tarr := root.MustArray()\n\tfor i, node := range arr {\n\t\tif i != node.Index() {\n\t\t\tt.Errorf(ufmt.Sprintf(\"Index() must be nil. got: %v\", i))\n\t\t}\n\t}\n}\n\nfunc TestNode_Index_NotSucceed(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tnode *Node\n\t\twant int\n\t}{\n\t\t{\"nil node\", (*Node)(nil), -1},\n\t\t{\"null node\", NullNode(\"\"), -1},\n\t\t{\"object node\", ObjectNode(\"\", nil), -1},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := tt.node.Index(); got != tt.want {\n\t\t\t\tt.Errorf(\"Index() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNode_GetIndex(t *testing.T) {\n\troot := Must(Unmarshal([]byte(`[1, 2, 3, 4, 5, 6]`)))\n\texpected := []int{1, 2, 3, 4, 5, 6}\n\n\tif len(expected) != root.Size() {\n\t\tt.Errorf(\"length is not matched. expected: %d, got: %d\", len(expected), root.Size())\n\t}\n\n\t// TODO: if length exceeds, stack overflow occurs. need to fix\n\tfor i, v := range expected {\n\t\tval, err := root.GetIndex(i)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"error occurred while getting index %d, %s\", i, err)\n\t\t}\n\n\t\tif val.MustNumeric() != float64(v) {\n\t\t\tt.Errorf(\"value is not matched. expected: %d, got: %v\", v, val.MustNumeric())\n\t\t}\n\t}\n}\n\nfunc TestNode_GetIndex_InputIndex_Exceed_Original_Node_Index(t *testing.T) {\n\troot, err := Unmarshal([]byte(`[1, 2, 3, 4, 5, 6]`))\n\tif err != nil {\n\t\tt.Errorf(\"error occurred while unmarshal\")\n\t}\n\n\t_, err = root.GetIndex(10)\n\tif err == nil {\n\t\tt.Errorf(\"GetIndex should return error\")\n\t}\n}\n\nfunc TestNode_DeleteIndex(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\texpected string\n\t\tindex    int\n\t\tok       bool\n\t}{\n\t\t{`null`, ``, 0, false},\n\t\t{`1`, ``, 0, false},\n\t\t{`{}`, ``, 0, false},\n\t\t{`{\"foo\":\"bar\"}`, ``, 0, false},\n\t\t{`true`, ``, 0, false},\n\t\t{`[]`, ``, 0, false},\n\t\t{`[]`, ``, -1, false},\n\t\t{`[1]`, `[]`, 0, true},\n\t\t{`[{}]`, `[]`, 0, true},\n\t\t{`[{}, [], 42]`, `[{}, []]`, -1, true},\n\t\t{`[{}, [], 42]`, `[[], 42]`, 0, true},\n\t\t{`[{}, [], 42]`, `[{}, 42]`, 1, true},\n\t\t{`[{}, [], 42]`, `[{}, []]`, 2, true},\n\t\t{`[{}, [], 42]`, ``, 10, false},\n\t\t{`[{}, [], 42]`, ``, -10, false},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\troot := Must(Unmarshal([]byte(tt.name)))\n\t\t\terr := root.DeleteIndex(tt.index)\n\t\t\tif err != nil \u0026\u0026 tt.ok {\n\t\t\t\tt.Errorf(\"DeleteIndex returns error: %v\", err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNode_GetKey(t *testing.T) {\n\troot, err := Unmarshal([]byte(`{\"foo\": true, \"bar\": null}`))\n\tif err != nil {\n\t\tt.Error(\"error occurred while unmarshal\")\n\t}\n\n\tvalue, err := root.GetKey(\"foo\")\n\tif err != nil {\n\t\tt.Errorf(\"error occurred while getting key, %s\", err)\n\t}\n\n\tif value.MustBool() != true {\n\t\tt.Errorf(\"value is not matched. expected: true, got: %v\", value.MustBool())\n\t}\n\n\tvalue, err = root.GetKey(\"bar\")\n\tif err != nil {\n\t\tt.Errorf(\"error occurred while getting key, %s\", err)\n\t}\n\n\t_, err = root.GetKey(\"baz\")\n\tif err == nil {\n\t\tt.Errorf(\"key baz is not exist. must be failed\")\n\t}\n\n\tif value.MustNull() != nil {\n\t\tt.Errorf(\"value is not matched. expected: nil, got: %v\", value.MustNull())\n\t}\n}\n\nfunc TestNode_GetKey_NotSucceed(t *testing.T) {\n\ttests := []simpleNode{\n\t\t{\"nil node\", (*Node)(nil)},\n\t\t{\"null node\", NullNode(\"\")},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif _, err := tt.node.GetKey(\"\"); err == nil {\n\t\t\t\tt.Errorf(\"%s should be an error\", tt.name)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNode_GetUniqueKeyList(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tjson     string\n\t\texpected []string\n\t}{\n\t\t{\n\t\t\tname:     \"simple foo/bar\",\n\t\t\tjson:     `{\"foo\": true, \"bar\": null}`,\n\t\t\texpected: []string{\"foo\", \"bar\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"empty object\",\n\t\t\tjson:     `{}`,\n\t\t\texpected: []string{},\n\t\t},\n\t\t{\n\t\t\tname: \"nested object\",\n\t\t\tjson: `{\n\t\t\t\t\"outer\": {\n\t\t\t\t\t\"inner\": {\n\t\t\t\t\t\t\"key\": \"value\"\n\t\t\t\t\t},\n\t\t\t\t\t\"array\": [1, 2, 3]\n\t\t\t\t},\n\t\t\t\t\"another\": \"item\"\n\t\t\t}`,\n\t\t\texpected: []string{\"outer\", \"inner\", \"key\", \"array\", \"another\"},\n\t\t},\n\t\t{\n\t\t\tname: \"complex object\",\n\t\t\tjson: `{\n\t\t\t\t\"Image\": {\n\t\t\t\t\t\"Width\": 800,\n\t\t\t\t\t\"Height\": 600,\n\t\t\t\t\t\"Title\": \"View from 15th Floor\",\n\t\t\t\t\t\"Thumbnail\": {\n\t\t\t\t\t\t\"Url\": \"http://www.example.com/image/481989943\",\n\t\t\t\t\t\t\"Height\": 125,\n\t\t\t\t\t\t\"Width\": 100\n\t\t\t\t\t},\n\t\t\t\t\t\"Animated\": false,\n\t\t\t\t\t\"IDs\": [116, 943, 234, 38793]\n\t\t\t\t}\n\t\t\t}`,\n\t\t\texpected: []string{\"Image\", \"Width\", \"Height\", \"Title\", \"Thumbnail\", \"Url\", \"Animated\", \"IDs\"},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\troot, err := Unmarshal([]byte(tt.json))\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"error occurred while unmarshal\")\n\t\t\t}\n\n\t\t\tvalue := root.UniqueKeyLists()\n\t\t\tif len(value) != len(tt.expected) {\n\t\t\t\tt.Errorf(\"%s length must be %v. got: %v. retrieved keys: %s\", tt.name, len(tt.expected), len(value), value)\n\t\t\t}\n\n\t\t\tfor _, key := range value {\n\t\t\t\tif !contains(tt.expected, key) {\n\t\t\t\t\tt.Errorf(\"EachKey() must be in %v. got: %v\", tt.expected, key)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\n// TODO: resolve stack overflow\nfunc TestNode_IsEmpty(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tnode     *Node\n\t\texpected bool\n\t}{\n\t\t{\"nil node\", (*Node)(nil), false}, // nil node is not empty.\n\t\t// {\"null node\", NullNode(\"\"), true},\n\t\t{\"empty object\", ObjectNode(\"\", nil), true},\n\t\t{\"empty array\", ArrayNode(\"\", nil), true},\n\t\t{\"non-empty object\", ObjectNode(\"\", map[string]*Node{\"foo\": BoolNode(\"foo\", true)}), false},\n\t\t{\"non-empty array\", ArrayNode(\"\", []*Node{BoolNode(\"0\", true)}), false},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := tt.node.Empty(); got != tt.expected {\n\t\t\t\tt.Errorf(\"%s = %v, want %v\", tt.name, got, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNode_Index_EmptyList(t *testing.T) {\n\troot, err := Unmarshal([]byte(`[]`))\n\tif err != nil {\n\t\tt.Errorf(\"error occurred while unmarshal\")\n\t}\n\n\tarray := root.MustArray()\n\tfor i, node := range array {\n\t\tif i != node.Index() {\n\t\t\tt.Errorf(ufmt.Sprintf(\"Index() must be nil. got: %v\", i))\n\t\t}\n\t}\n}\n\nfunc TestNode_GetObject(t *testing.T) {\n\troot, err := Unmarshal([]byte(`{\"foo\": true,\"bar\": null}`))\n\tif err != nil {\n\t\tt.Errorf(\"Error on Unmarshal(): %s\", err.Error())\n\t\treturn\n\t}\n\n\tvalue, err := root.GetObject()\n\tif err != nil {\n\t\tt.Errorf(\"Error on root.GetObject(): %s\", err.Error())\n\t}\n\n\tif _, ok := value[\"foo\"]; !ok {\n\t\tt.Errorf(\"root.GetObject() is corrupted: foo\")\n\t}\n\n\tif _, ok := value[\"bar\"]; !ok {\n\t\tt.Errorf(\"root.GetObject() is corrupted: bar\")\n\t}\n}\n\nfunc TestNode_GetObject_NotSucceed(t *testing.T) {\n\ttests := []simpleNode{\n\t\t{\"nil node\", (*Node)(nil)},\n\t\t{\"get object from null node\", NullNode(\"\")},\n\t\t{\"not object node\", NumberNode(\"\", 123)},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif _, err := tt.node.GetObject(); err == nil {\n\t\t\t\tt.Errorf(\"%s should be an error\", tt.name)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNode_ObjectEach(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tjson     string\n\t\texpected map[string]int\n\t}{\n\t\t{\n\t\t\tname:     \"empty object\",\n\t\t\tjson:     `{}`,\n\t\t\texpected: make(map[string]int),\n\t\t},\n\t\t{\n\t\t\tname:     \"single key-value pair\",\n\t\t\tjson:     `{\"key\": 42}`,\n\t\t\texpected: map[string]int{\"key\": 42},\n\t\t},\n\t\t{\n\t\t\tname:     \"multiple key-value pairs\",\n\t\t\tjson:     `{\"one\": 1, \"two\": 2, \"three\": 3}`,\n\t\t\texpected: map[string]int{\"one\": 1, \"two\": 2, \"three\": 3},\n\t\t},\n\t\t{\n\t\t\tname:     \"multiple key-value pairs with some non-numeric values\",\n\t\t\tjson:     `{\"one\": 1, \"two\": \"2\", \"three\": 3, \"four\": \"4\"}`,\n\t\t\texpected: map[string]int{\"one\": 1, \"three\": 3},\n\t\t},\n\t\t{\n\t\t\tname:     \"non-object node\",\n\t\t\tjson:     `[\"not\", \"an\", \"object\"]`,\n\t\t\texpected: make(map[string]int),\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\troot, err := Unmarshal([]byte(tc.json))\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Unmarshal failed: %v\", err)\n\t\t\t}\n\n\t\t\tresult := make(map[string]int)\n\t\t\troot.ObjectEach(func(key string, value *Node) {\n\t\t\t\t// extract integer values from the object\n\t\t\t\tif val, err := strconv.Atoi(value.String()); err == nil {\n\t\t\t\t\tresult[key] = val\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tif len(result) != len(tc.expected) {\n\t\t\t\tt.Errorf(\"%s: expected %d key-value pairs, got %d\", tc.name, len(tc.expected), len(result))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor key, val := range tc.expected {\n\t\t\t\tif result[key] != val {\n\t\t\t\t\tt.Errorf(\"%s: expected value for key %s to be %d, got %d\", tc.name, key, val, result[key])\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc Example_TestNode_Must() {\n\tdata := []byte(`{\n        \"Image\": {\n            \"Width\":  800,\n            \"Height\": 600,\n            \"Title\":  \"View from 15th Floor\",\n            \"Thumbnail\": {\n                \"Url\":    \"http://www.example.com/image/481989943\",\n                \"Height\": 125,\n                \"Width\":  100\n            },\n            \"Animated\" : false,\n            \"IDs\": [116, 943, 234, 38793]\n        }\n    }`)\n\n\troot := Must(Unmarshal(data))\n\tif root.Size() != 1 {\n\t\tufmt.Printf(\"root.Size() must be 1. got: %v\\n\", root.Size())\n\t\treturn\n\t}\n\n\tufmt.Printf(\"Object has %d inheritors inside\\n\", root.Size())\n\t// Output:\n\t// Object has 1 inheritors inside\n}\n\n// Calculate AVG price from different types of objects, JSON from: https://goessner.net/articles/JsonPath/index.html#e3\nfunc TestExampleUnmarshal(t *testing.T) {\n\tdata := []byte(`{ \"store\": {\n    \"book\": [ \n      { \"category\": \"reference\",\n        \"author\": \"Nigel Rees\",\n        \"title\": \"Sayings of the Century\",\n        \"price\": 8.95\n      },\n      { \"category\": \"fiction\",\n        \"author\": \"Evelyn Waugh\",\n        \"title\": \"Sword of Honour\",\n        \"price\": 12.99\n      },\n      { \"category\": \"fiction\",\n        \"author\": \"Herman Melville\",\n        \"title\": \"Moby Dick\",\n        \"isbn\": \"0-553-21311-3\",\n        \"price\": 8.99\n      },\n      { \"category\": \"fiction\",\n        \"author\": \"J. R. R. Tolkien\",\n        \"title\": \"The Lord of the Rings\",\n        \"isbn\": \"0-395-19395-8\",\n        \"price\": 22.99\n      }\n    ],\n    \"bicycle\": { \"color\": \"red\",\n      \"price\": 19.95\n    },\n    \"tools\": null\n  }\n}`)\n\n\troot, err := Unmarshal(data)\n\tif err != nil {\n\t\tt.Errorf(\"error occurred when unmarshal\")\n\t}\n\n\tstore := root.MustKey(\"store\").MustObject()\n\n\tvar prices float64\n\tsize := 0\n\tfor _, objects := range store {\n\t\tif objects.IsArray() \u0026\u0026 objects.Size() \u003e 0 {\n\t\t\tsize += objects.Size()\n\t\t\tfor _, object := range objects.MustArray() {\n\t\t\t\tprices += object.MustKey(\"price\").MustNumeric()\n\t\t\t}\n\t\t} else if objects.IsObject() \u0026\u0026 objects.HasKey(\"price\") {\n\t\t\tsize++\n\t\t\tprices += objects.MustKey(\"price\").MustNumeric()\n\t\t}\n\t}\n\n\tresult := int(prices / float64(size))\n\tufmt.Sprintf(\"AVG price: %d\", result)\n}\n\nfunc TestNode_ExampleMust_panic(t *testing.T) {\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Errorf(\"The code did not panic\")\n\t\t}\n\t}()\n\tdata := []byte(`{]`)\n\troot := Must(Unmarshal(data))\n\tufmt.Sprintf(\"Object has %d inheritors inside\", root.Size())\n}\n\nfunc TestNode_Path(t *testing.T) {\n\tdata := []byte(`{\n        \"Image\": {\n            \"Width\":  800,\n            \"Height\": 600,\n            \"Title\":  \"View from 15th Floor\",\n            \"Thumbnail\": {\n                \"Url\":    \"http://www.example.com/image/481989943\",\n                \"Height\": 125,\n                \"Width\":  100\n            },\n            \"Animated\" : false,\n            \"IDs\": [116, 943, 234, 38793]\n          }\n      }`)\n\n\troot, err := Unmarshal(data)\n\tif err != nil {\n\t\tt.Errorf(\"Error on Unmarshal(): %s\", err.Error())\n\t\treturn\n\t}\n\n\tif root.Path() != \"$\" {\n\t\tt.Errorf(\"Wrong root.Path()\")\n\t}\n\n\telement := root.MustKey(\"Image\").MustKey(\"Thumbnail\").MustKey(\"Url\")\n\tif element.Path() != \"$['Image']['Thumbnail']['Url']\" {\n\t\tt.Errorf(\"Wrong path found: %s\", element.Path())\n\t}\n\n\tif (*Node)(nil).Path() != \"\" {\n\t\tt.Errorf(\"Wrong (nil).Path()\")\n\t}\n}\n\nfunc TestNode_Path2(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tnode *Node\n\t\twant string\n\t}{\n\t\t{\n\t\t\tname: \"Node with key\",\n\t\t\tnode: \u0026Node{\n\t\t\t\tprev: \u0026Node{},\n\t\t\t\tkey:  func() *string { s := \"key\"; return \u0026s }(),\n\t\t\t},\n\t\t\twant: \"$['key']\",\n\t\t},\n\t\t{\n\t\t\tname: \"Node with index\",\n\t\t\tnode: \u0026Node{\n\t\t\t\tprev:  \u0026Node{},\n\t\t\t\tindex: func() *int { i := 1; return \u0026i }(),\n\t\t\t},\n\t\t\twant: \"$[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\tif got := tt.node.Path(); got != tt.want {\n\t\t\t\tt.Errorf(\"Path() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNode_Root(t *testing.T) {\n\troot := \u0026Node{}\n\tchild := \u0026Node{prev: root}\n\tgrandChild := \u0026Node{prev: child}\n\n\ttests := []struct {\n\t\tname string\n\t\tnode *Node\n\t\twant *Node\n\t}{\n\t\t{\n\t\t\tname: \"Root node\",\n\t\t\tnode: root,\n\t\t\twant: root,\n\t\t},\n\t\t{\n\t\t\tname: \"Child node\",\n\t\t\tnode: child,\n\t\t\twant: root,\n\t\t},\n\t\t{\n\t\t\tname: \"Grandchild node\",\n\t\t\tnode: grandChild,\n\t\t\twant: root,\n\t\t},\n\t\t{\n\t\t\tname: \"Node is nil\",\n\t\t\tnode: nil,\n\t\t\twant: nil,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := tt.node.root(); got != tt.want {\n\t\t\t\tt.Errorf(\"root() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc contains(slice []string, item string) bool {\n\tfor _, a := range slice {\n\t\tif a == item {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n// ignore the sequence of keys by ordering them.\n// need to avoid import encoding/json and reflect package.\n// because gno does not support them for now.\n// TODO: use encoding/json to compare the result after if possible in gno.\nfunc isSameObject(a, b string) bool {\n\taPairs := strings.Split(strings.Trim(a, \"{}\"), \",\")\n\tbPairs := strings.Split(strings.Trim(b, \"{}\"), \",\")\n\n\taMap := make(map[string]string)\n\tbMap := make(map[string]string)\n\tfor _, pair := range aPairs {\n\t\tkv := strings.Split(pair, \":\")\n\t\tkey := strings.Trim(kv[0], `\"`)\n\t\tvalue := strings.Trim(kv[1], `\"`)\n\t\taMap[key] = value\n\t}\n\tfor _, pair := range bPairs {\n\t\tkv := strings.Split(pair, \":\")\n\t\tkey := strings.Trim(kv[0], `\"`)\n\t\tvalue := strings.Trim(kv[1], `\"`)\n\t\tbMap[key] = value\n\t}\n\n\taKeys := make([]string, 0, len(aMap))\n\tbKeys := make([]string, 0, len(bMap))\n\tfor k := range aMap {\n\t\taKeys = append(aKeys, k)\n\t}\n\n\tfor k := range bMap {\n\t\tbKeys = append(bKeys, k)\n\t}\n\n\tsort.Strings(aKeys)\n\tsort.Strings(bKeys)\n\n\tif len(aKeys) != len(bKeys) {\n\t\treturn false\n\t}\n\n\tfor i := range aKeys {\n\t\tif aKeys[i] != bKeys[i] {\n\t\t\treturn false\n\t\t}\n\n\t\tif aMap[aKeys[i]] != bMap[bKeys[i]] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc compareNodes(n1, n2 *Node) bool {\n\tif n1 == nil || n2 == nil {\n\t\treturn n1 == n2\n\t}\n\n\tif n1.key != n2.key {\n\t\treturn false\n\t}\n\n\tif !bytes.Equal(n1.data, n2.data) {\n\t\treturn false\n\t}\n\n\tif n1.index != n2.index {\n\t\treturn false\n\t}\n\n\tif n1.borders != n2.borders {\n\t\treturn false\n\t}\n\n\tif n1.modified != n2.modified {\n\t\treturn false\n\t}\n\n\tif n1.nodeType != n2.nodeType {\n\t\treturn false\n\t}\n\n\tif !compareNodes(n1.prev, n2.prev) {\n\t\treturn false\n\t}\n\n\tif len(n1.next) != len(n2.next) {\n\t\treturn false\n\t}\n\n\tfor k, v := range n1.next {\n\t\tif !compareNodes(v, n2.next[k]) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\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":"parser_test.gno","body":"package json\n\nimport \"testing\"\n\nfunc TestParseStringLiteral(t *testing.T) {\n\ttests := []struct {\n\t\tinput    string\n\t\texpected string\n\t\tisError  bool\n\t}{\n\t\t{`\"Hello, World!\"`, \"\\\"Hello, World!\\\"\", false},\n\t\t{`\\uFF11`, \"\\uFF11\", false},\n\t\t{`\\uFFFF`, \"\\uFFFF\", false},\n\t\t{`true`, \"true\", false},\n\t\t{`false`, \"false\", false},\n\t\t{`\\uDF00`, \"\", true},\n\t}\n\n\tfor i, tt := range tests {\n\t\ts, err := ParseStringLiteral([]byte(tt.input))\n\n\t\tif !tt.isError \u0026\u0026 err != nil {\n\t\t\tt.Errorf(\"%d. unexpected error: %s\", i, err)\n\t\t}\n\n\t\tif tt.isError \u0026\u0026 err == nil {\n\t\t\tt.Errorf(\"%d. expected error, but not error\", i)\n\t\t}\n\n\t\tif s != tt.expected {\n\t\t\tt.Errorf(\"%d. expected=%s, but actual=%s\", i, tt.expected, s)\n\t\t}\n\t}\n}\n\nfunc TestParseBoolLiteral(t *testing.T) {\n\ttests := []struct {\n\t\tinput    string\n\t\texpected bool\n\t\tisError  bool\n\t}{\n\t\t{`true`, true, false},\n\t\t{`false`, false, false},\n\t\t{`TRUE`, false, true},\n\t\t{`FALSE`, false, true},\n\t\t{`foo`, false, true},\n\t\t{`\"true\"`, false, true},\n\t\t{`\"false\"`, false, true},\n\t}\n\n\tfor i, tt := range tests {\n\t\tb, err := ParseBoolLiteral([]byte(tt.input))\n\n\t\tif !tt.isError \u0026\u0026 err != nil {\n\t\t\tt.Errorf(\"%d. unexpected error: %s\", i, err)\n\t\t}\n\n\t\tif tt.isError \u0026\u0026 err == nil {\n\t\t\tt.Errorf(\"%d. expected error, but not error\", i)\n\t\t}\n\n\t\tif b != tt.expected {\n\t\t\tt.Errorf(\"%d. expected=%t, but actual=%t\", i, tt.expected, b)\n\t\t}\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":"path_test.gno","body":"package json\n\nimport \"testing\"\n\nfunc TestParseJSONPath(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tpath     string\n\t\texpected []string\n\t}{\n\t\t{name: \"Empty string path\", path: \"\", expected: []string{}},\n\t\t{name: \"Root only path\", path: \"$\", expected: []string{\"$\"}},\n\t\t{name: \"Root with dot path\", path: \"$.\", expected: []string{\"$\"}},\n\t\t{name: \"All objects in path\", path: \"$..\", expected: []string{\"$\", \"..\"}},\n\t\t{name: \"Only children in path\", path: \"$.*\", expected: []string{\"$\", \"*\"}},\n\t\t{name: \"All objects' children in path\", path: \"$..*\", expected: []string{\"$\", \"..\", \"*\"}},\n\t\t{name: \"Simple dot notation path\", path: \"$.root.element\", expected: []string{\"$\", \"root\", \"element\"}},\n\t\t{name: \"Complex dot notation path with wildcard\", path: \"$.root.*.element\", expected: []string{\"$\", \"root\", \"*\", \"element\"}},\n\t\t{name: \"Path with array wildcard\", path: \"$.phoneNumbers[*].type\", expected: []string{\"$\", \"phoneNumbers\", \"*\", \"type\"}},\n\t\t{name: \"Path with filter expression\", path: \"$.store.book[?(@.price \u003c 10)].title\", expected: []string{\"$\", \"store\", \"book\", \"?(@.price \u003c 10)\", \"title\"}},\n\t\t{name: \"Path with formula\", path: \"$..phoneNumbers..('ty' + 'pe')\", expected: []string{\"$\", \"..\", \"phoneNumbers\", \"..\", \"('ty' + 'pe')\"}},\n\t\t{name: \"Simple bracket notation path\", path: \"$['root']['element']\", expected: []string{\"$\", \"'root'\", \"'element'\"}},\n\t\t{name: \"Complex bracket notation path with wildcard\", path: \"$['root'][*]['element']\", expected: []string{\"$\", \"'root'\", \"*\", \"'element'\"}},\n\t\t{name: \"Bracket notation path with integer index\", path: \"$['store']['book'][0]['title']\", expected: []string{\"$\", \"'store'\", \"'book'\", \"0\", \"'title'\"}},\n\t\t{name: \"Complex path with wildcard in bracket notation\", path: \"$['root'].*['element']\", expected: []string{\"$\", \"'root'\", \"*\", \"'element'\"}},\n\t\t{name: \"Mixed notation path with dot after bracket\", path: \"$.['root'].*.['element']\", expected: []string{\"$\", \"'root'\", \"*\", \"'element'\"}},\n\t\t{name: \"Mixed notation path with dot before bracket\", path: \"$['root'].*.['element']\", expected: []string{\"$\", \"'root'\", \"*\", \"'element'\"}},\n\t\t{name: \"Single character path with root\", path: \"$.a\", expected: []string{\"$\", \"a\"}},\n\t\t{name: \"Multiple characters path with root\", path: \"$.abc\", expected: []string{\"$\", \"abc\"}},\n\t\t{name: \"Multiple segments path with root\", path: \"$.a.b.c\", expected: []string{\"$\", \"a\", \"b\", \"c\"}},\n\t\t{name: \"Multiple segments path with wildcard and root\", path: \"$.a.*.c\", expected: []string{\"$\", \"a\", \"*\", \"c\"}},\n\t\t{name: \"Multiple segments path with filter and root\", path: \"$.a[?(@.b == 'c')].d\", expected: []string{\"$\", \"a\", \"?(@.b == 'c')\", \"d\"}},\n\t\t{name: \"Complex path with multiple filters\", path: \"$.a[?(@.b == 'c')].d[?(@.e == 'f')].g\", expected: []string{\"$\", \"a\", \"?(@.b == 'c')\", \"d\", \"?(@.e == 'f')\", \"g\"}},\n\t\t{name: \"Complex path with multiple filters and wildcards\", path: \"$.a[?(@.b == 'c')].*.d[?(@.e == 'f')].g\", expected: []string{\"$\", \"a\", \"?(@.b == 'c')\", \"*\", \"d\", \"?(@.e == 'f')\", \"g\"}},\n\t\t{name: \"Path with array index and root\", path: \"$.a[0].b\", expected: []string{\"$\", \"a\", \"0\", \"b\"}},\n\t\t{name: \"Path with multiple array indices and root\", path: \"$.a[0].b[1].c\", expected: []string{\"$\", \"a\", \"0\", \"b\", \"1\", \"c\"}},\n\t\t{name: \"Path with array index, wildcard and root\", path: \"$.a[0].*.c\", expected: []string{\"$\", \"a\", \"0\", \"*\", \"c\"}},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\treult, _ := ParsePath(tt.path)\n\t\t\tif !isEqualSlice(reult, tt.expected) {\n\t\t\t\tt.Errorf(\"ParsePath(%s) expected: %v, got: %v\", tt.path, tt.expected, reult)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc isEqualSlice(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor i, v := range a {\n\t\tif v != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"Gl4kgCFIrQzHk2phtSiwmW6DZZg+Mb8jRs2FxhBt5hAZHeN3zcPYOwush3q59IzxWfWftjzCvO/zMg1c4OMbug=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"table","path":"gno.land/p/sunspirit/table","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/sunspirit/table\"\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"},{"name":"table_test.gno","body":"package table\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 TestNew(t *testing.T) {\n\theader := []string{\"Name\", \"Age\", \"Country\"}\n\trows := [][]string{\n\t\t{\"Alice\", \"30\", \"USA\"},\n\t\t{\"Bob\", \"25\", \"UK\"},\n\t}\n\n\ttable, err := New(header, rows)\n\turequire.NoError(t, err)\n\n\tuassert.Equal(t, len(header), len(table.header))\n\tuassert.Equal(t, len(rows), len(table.rows))\n}\n\nfunc Test_AddRow(t *testing.T) {\n\theader := []string{\"Name\", \"Age\"}\n\trows := [][]string{\n\t\t{\"Alice\", \"30\"},\n\t\t{\"Bob\", \"25\"},\n\t}\n\n\ttable, err := New(header, rows)\n\turequire.NoError(t, err)\n\n\t// Add a valid row\n\terr = table.AddRow([]string{\"Charlie\", \"28\"})\n\turequire.NoError(t, err)\n\n\texpectedRows := [][]string{\n\t\t{\"Alice\", \"30\"},\n\t\t{\"Bob\", \"25\"},\n\t\t{\"Charlie\", \"28\"},\n\t}\n\tuassert.Equal(t, len(expectedRows), len(table.rows))\n\n\t// Attempt to add a row with a different number of columns\n\terr = table.AddRow([]string{\"David\"})\n\tuassert.Error(t, err)\n}\n\nfunc Test_AddColumn(t *testing.T) {\n\theader := []string{\"Name\", \"Age\"}\n\trows := [][]string{\n\t\t{\"Alice\", \"30\"},\n\t\t{\"Bob\", \"25\"},\n\t}\n\n\ttable, err := New(header, rows)\n\turequire.NoError(t, err)\n\n\t// Add a valid column\n\terr = table.AddColumn(\"Country\", []string{\"USA\", \"UK\"})\n\turequire.NoError(t, err)\n\n\texpectedHeader := []string{\"Name\", \"Age\", \"Country\"}\n\texpectedRows := [][]string{\n\t\t{\"Alice\", \"30\", \"USA\"},\n\t\t{\"Bob\", \"25\", \"UK\"},\n\t}\n\tuassert.Equal(t, len(expectedHeader), len(table.header))\n\tuassert.Equal(t, len(expectedRows), len(table.rows))\n\n\t// Attempt to add a column with a different number of values\n\terr = table.AddColumn(\"City\", []string{\"New York\"})\n\tuassert.Error(t, err)\n}\n\nfunc Test_RemoveRow(t *testing.T) {\n\theader := []string{\"Name\", \"Age\", \"Country\"}\n\trows := [][]string{\n\t\t{\"Alice\", \"30\", \"USA\"},\n\t\t{\"Bob\", \"25\", \"UK\"},\n\t}\n\n\ttable, err := New(header, rows)\n\turequire.NoError(t, err)\n\n\t// Remove the first row\n\terr = table.RemoveRow(0)\n\turequire.NoError(t, err)\n\n\texpectedRows := [][]string{\n\t\t{\"Bob\", \"25\", \"UK\"},\n\t}\n\tuassert.Equal(t, len(expectedRows), len(table.rows))\n\n\t// Attempt to remove a row out of range\n\terr = table.RemoveRow(5)\n\tuassert.Error(t, err)\n}\n\nfunc Test_RemoveColumn(t *testing.T) {\n\theader := []string{\"Name\", \"Age\", \"Country\"}\n\trows := [][]string{\n\t\t{\"Alice\", \"30\", \"USA\"},\n\t\t{\"Bob\", \"25\", \"UK\"},\n\t}\n\n\ttable, err := New(header, rows)\n\turequire.NoError(t, err)\n\n\t// Remove the second column (Age)\n\terr = table.RemoveColumn(1)\n\turequire.NoError(t, err)\n\n\texpectedHeader := []string{\"Name\", \"Country\"}\n\texpectedRows := [][]string{\n\t\t{\"Alice\", \"USA\"},\n\t\t{\"Bob\", \"UK\"},\n\t}\n\tuassert.Equal(t, len(expectedHeader), len(table.header))\n\tuassert.Equal(t, len(expectedRows), len(table.rows))\n\n\t// Attempt to remove a column out of range\n\terr = table.RemoveColumn(5)\n\tuassert.Error(t, err)\n}\n\nfunc Test_Validate(t *testing.T) {\n\theader := []string{\"Name\", \"Age\", \"Country\"}\n\trows := [][]string{\n\t\t{\"Alice\", \"30\", \"USA\"},\n\t\t{\"Bob\", \"25\"},\n\t}\n\n\ttable, err := New(header, rows[:1])\n\turequire.NoError(t, err)\n\n\t// Validate should pass\n\terr = table.Validate()\n\turequire.NoError(t, err)\n\n\t// Add an invalid row and validate again\n\ttable.rows = append(table.rows, rows[1])\n\terr = table.Validate()\n\tuassert.Error(t, err)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"QLFkqrD8AIBpbOeOT342GDKrlLkEKiiGrT45A1UAKrQykElHeQY9Dwookx/U72gx291nNqEkV/HacCp9MTmTnQ=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"md","path":"gno.land/p/sunspirit/md","files":[{"name":"gnomod.toml","body":"module = \"gno.land/p/sunspirit/md\"\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"},{"name":"md_test.gno","body":"package md\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/sunspirit/table\"\n)\n\nfunc TestNewBuilder(t *testing.T) {\n\tmdBuilder := NewBuilder()\n\n\tuassert.Equal(t, len(mdBuilder.elements), 0, \"Expected 0 elements\")\n}\n\nfunc TestAdd(t *testing.T) {\n\tmdBuilder := NewBuilder()\n\n\theader := H1(\"Hi\")\n\tbody := Paragraph(\"This is a test\")\n\n\tmdBuilder.Add(header, body)\n\n\tuassert.Equal(t, len(mdBuilder.elements), 2, \"Expected 2 element\")\n\tuassert.Equal(t, mdBuilder.elements[0], header, \"Expected element %s, got %s\", header, mdBuilder.elements[0])\n\tuassert.Equal(t, mdBuilder.elements[1], body, \"Expected element %s, got %s\", body, mdBuilder.elements[1])\n}\n\nfunc TestRender(t *testing.T) {\n\tmdBuilder := NewBuilder()\n\n\theader := H1(\"Hello\")\n\tbody := Paragraph(\"This is a test\")\n\n\tseperator := \"\\n\"\n\texpected := header + seperator + body\n\n\toutput := mdBuilder.Add(header, body).Render(seperator)\n\n\tuassert.Equal(t, output, expected, \"Expected rendered string %s, got %s\", expected, output)\n}\n\nfunc Test_Bold(t *testing.T) {\n\tuassert.Equal(t, Bold(\"Hello\"), \"**Hello**\")\n}\n\nfunc Test_Italic(t *testing.T) {\n\tuassert.Equal(t, Italic(\"Hello\"), \"*Hello*\")\n}\n\nfunc Test_Strikethrough(t *testing.T) {\n\tuassert.Equal(t, Strikethrough(\"Hello\"), \"~~Hello~~\")\n}\n\nfunc Test_H1(t *testing.T) {\n\tuassert.Equal(t, H1(\"Header 1\"), \"# Header 1\\n\")\n}\n\nfunc Test_H2(t *testing.T) {\n\tuassert.Equal(t, H2(\"Header 2\"), \"## Header 2\\n\")\n}\n\nfunc Test_H3(t *testing.T) {\n\tuassert.Equal(t, H3(\"Header 3\"), \"### Header 3\\n\")\n}\n\nfunc Test_H4(t *testing.T) {\n\tuassert.Equal(t, H4(\"Header 4\"), \"#### Header 4\\n\")\n}\n\nfunc Test_H5(t *testing.T) {\n\tuassert.Equal(t, H5(\"Header 5\"), \"##### Header 5\\n\")\n}\n\nfunc Test_H6(t *testing.T) {\n\tuassert.Equal(t, H6(\"Header 6\"), \"###### Header 6\\n\")\n}\n\nfunc Test_BulletList(t *testing.T) {\n\titems := []string{\"Item 1\", \"Item 2\", \"Item 3\"}\n\tresult := BulletList(items)\n\texpected := \"- Item 1\\n- Item 2\\n- Item 3\\n\"\n\tuassert.Equal(t, result, expected)\n}\n\nfunc Test_OrderedList(t *testing.T) {\n\titems := []string{\"Item 1\", \"Item 2\", \"Item 3\"}\n\tresult := OrderedList(items)\n\texpected := \"1. Item 1\\n2. Item 2\\n3. Item 3\\n\"\n\tuassert.Equal(t, result, expected)\n}\n\nfunc Test_TodoList(t *testing.T) {\n\titems := []string{\"Task 1\", \"Task 2\"}\n\tdone := []bool{true, false}\n\tresult := TodoList(items, done)\n\texpected := \"- [x] Task 1\\n- [ ] Task 2\\n\"\n\tuassert.Equal(t, result, expected)\n}\n\nfunc Test_Blockquote(t *testing.T) {\n\ttext := \"This is a blockquote.\\nIt has multiple lines.\"\n\tresult := Blockquote(text)\n\texpected := \"\u003e This is a blockquote.\\n\u003e It has multiple lines.\\n\"\n\tuassert.Equal(t, result, expected)\n}\n\nfunc Test_InlineCode(t *testing.T) {\n\tresult := InlineCode(\"code\")\n\tuassert.Equal(t, result, \"`code`\")\n}\n\nfunc Test_LanguageCodeBlock(t *testing.T) {\n\tresult := LanguageCodeBlock(\"python\", \"print('Hello')\")\n\texpected := \"```python\\nprint('Hello')\\n```\"\n\tuassert.Equal(t, result, expected)\n}\n\nfunc Test_CodeBlock(t *testing.T) {\n\tresult := CodeBlock(\"print('Hello')\")\n\texpected := \"```\\nprint('Hello')\\n```\"\n\tuassert.Equal(t, result, expected)\n}\n\nfunc Test_LineBreak(t *testing.T) {\n\tresult := LineBreak(2)\n\texpected := \"\\n\\n\\n\"\n\tuassert.Equal(t, result, expected)\n\n\tresult = LineBreak(0)\n\texpected = \"\"\n\tuassert.Equal(t, result, expected)\n}\n\nfunc Test_HorizontalRule(t *testing.T) {\n\tresult := HorizontalRule()\n\tuassert.Equal(t, result, \"---\\n\")\n}\n\nfunc Test_Link(t *testing.T) {\n\tresult := Link(\"Google\", \"http://google.com\")\n\tuassert.Equal(t, result, \"[Google](http://google.com)\")\n}\n\nfunc Test_Image(t *testing.T) {\n\tresult := Image(\"Alt text\", \"http://image.url\")\n\tuassert.Equal(t, result, \"![Alt text](http://image.url)\")\n}\n\nfunc Test_Footnote(t *testing.T) {\n\tresult := Footnote(\"1\", \"This is a footnote.\")\n\tuassert.Equal(t, result, \"[1]: This is a footnote.\")\n}\n\nfunc Test_Paragraph(t *testing.T) {\n\tresult := Paragraph(\"This is a paragraph.\")\n\tuassert.Equal(t, result, \"This is a paragraph.\\n\")\n}\n\nfunc Test_Table(t *testing.T) {\n\ttb, err := table.New([]string{\"Header1\", \"Header2\"}, [][]string{\n\t\t{\"Row1Col1\", \"Row1Col2\"},\n\t\t{\"Row2Col1\", \"Row2Col2\"},\n\t})\n\tuassert.NoError(t, err)\n\n\tresult := Table(tb)\n\texpected := \"| Header1 | Header2 |\\n| ---|---|\\n| Row1Col1 | Row1Col2 |\\n| Row2Col1 | Row2Col2 |\\n\"\n\tuassert.Equal(t, result, expected)\n}\n\nfunc Test_EscapeMarkdown(t *testing.T) {\n\tresult := EscapeMarkdown(\"- This is `code`\")\n\tuassert.Equal(t, result, \"``- This is `code```\")\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"yZHlkaoReHkZRMAHELZrb1bZrgfOI4g+BGTlKO9Z5aZSLQoR6nEgEoP+O24KGEB29ExFCxKgjNJ+cxOGDlzuoA=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1kfd9f5zlvcvy6aammcmqswa7cyjpu2nyt9qfen","package":{"name":"piechart","path":"gno.land/p/samcrew/piechart","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\"\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/demo/svg\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/p/sunspirit/md\"\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"},{"name":"piechart_test.gno","body":"package piechart\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestRender(t *testing.T) {\n\ttitle := \"Test\"\n\tslices := []PieSlice{\n\t\t{Value: 10, Color: \"#00FF00\", Label: \"Green\"},\n\t\t{Value: 20, Color: \"#FFFF00\", Label: \"Yellow\"},\n\t\t{Value: 30, Color: \"#FF0000\", Label: \"Red\"},\n\t}\n\n\tresult := Render(slices, title)\n\n\t// Check if the result contains the expected image SVG structure\n\tif !strings.Contains(result, \"data:image/svg+xml;base64,\") {\n\t\tt.Errorf(\"Expected result to contain data:image/svg+xml;base64, got %s\", result)\n\t}\n\n\t// Check if the result contains the title\n\tif !strings.Contains(result, title) {\n\t\tt.Errorf(\"SVG does not contain the title %q\", title)\n\t}\n\n\t// Check if the result contains non-empty slices\n\temptySlices := []PieSlice{}\n\temptyResult := Render(emptySlices, title)\n\texpectedErr := \"\\npiechart fails: no data provided\"\n\tif emptyResult != expectedErr {\n\t\tt.Errorf(\"Expected exact error for empty slices: %q, got %q\", expectedErr, emptyResult)\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"DDv5aZiTEaKrWq07kNO5DxpzrwnEgwjsSyi0VwpM1yxd8C8A0/ZBVpR86CY/eVbOvg9dU9r4GD3fsnWEMrs99A=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1kfd9f5zlvcvy6aammcmqswa7cyjpu2nyt9qfen","package":{"name":"tablesort","path":"gno.land/p/samcrew/tablesort","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\"\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/v3/memberstore:members?filter=T1](/r/gov/dao/v3/memberstore: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\"\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\"\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"},{"name":"tablesort_test.gno","body":"package tablesort\n\nimport (\n\t\"net/url\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestRender(t *testing.T) {\n\t// --- Case 1: Testing Render with a Table with \"Role\" column sorted descending and param prefix \"members-\"\n\ttable := \u0026Table{\n\t\tHeadings: []string{\"Tier\", \"Member\", \"Role\"},\n\t\tRows: [][]string{\n\t\t\t{\"T1\", \"g11111\", \"finance-officer\"},\n\t\t\t{\"T2\", \"g22222\", \"developer\"},\n\t\t\t{\"T3\", \"g33333\", \"developer\"},\n\t\t},\n\t}\n\n\tu, _ := url.Parse(\"/test?members-sort-desc=Tier\")\n\tmd := Render(u, table, \"members-\")\n\n\texpected := \"| [Tier ↓](/test?members-sort-asc=Tier) | [Member](/test?members-sort-desc=Member) | [Role](/test?members-sort-desc=Role) |\\n\" +\n\t\t\"| --- | --- | --- |\\n\" +\n\t\t\"| T3 | g33333 | developer |\\n\" +\n\t\t\"| T2 | g22222 | developer |\\n\" +\n\t\t\"| T1 | g11111 | finance-officer |\\n\"\n\n\t// Trim spaces for comparison\n\tmd = strings.TrimSpace(md)\n\texpected = strings.TrimSpace(expected)\n\n\tif md != expected {\n\t\tt.Errorf(\"Render() output mismatch.\\nExpected:\\n%s\\nGot:\\n%s\", expected, md)\n\t}\n\n\t// --- Case 2: Testing Render with an invalid Table (row with missing cell)\n\ttable = \u0026Table{\n\t\tHeadings: []string{\"Tier\", \"Member\", \"Role\"},\n\t\tRows: [][]string{\n\t\t\t{\"T1\", \"g11111\"}, // Missing the \"Role\" cell\n\t\t},\n\t}\n\n\tmd = Render(u, table, \"\")\n\texpected = \"tablesort fails: row 1 has 2 cells, expected 3, because there are 3 columns.\\n\"\n\n\tif md != expected {\n\t\tt.Errorf(\"Expected error message:\\n%s\\nGot:\\n%s\", expected, md)\n\t}\n\n\t// --- Case 3: Testing SortRows\n\trows := [][]string{\n\t\t{\"T1\", \"g11111\", \"finance-officer\"},\n\t\t{\"T2\", \"g22222\", \"developer\"},\n\t\t{\"T3\", \"g33333\", \"developer\"},\n\t}\n\n\tSortRows(rows, 2, false) // Sort by \"Role\" descending\n\texpected = \"finance-officer\"\n\n\tif rows[0][2] != expected {\n\t\tt.Errorf(\"SortRows() failed. Expected first role: %s, got: %s\", expected, rows[0][2])\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"vxbuObyZKkdUDbFsfHKEzobrskGhWKyruv4/2Dy2KWpinrOsELtOB1gnH6KHPvnJB+MnkV24ALj7iBsoLw6iMA=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1kfd9f5zlvcvy6aammcmqswa7cyjpu2nyt9qfen","package":{"name":"urlfilter","path":"gno.land/p/samcrew/urlfilter","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?filter=size:XL) - [~~T2~~](/p/samcrew/urlfilter=T1,T2,size:XL) - [**size:XL**](/p/samcrew/urlfilter?filter=T1)\n```\n\n**Rendered as:**\n[**T1**](/p/samcrew/urlfilter?filter=size:XL) - [~~T2~~](/p/samcrew/urlfilter=T1,T2,size:XL) - [**size:XL**](/p/samcrew/urlfilter?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/v3/memberstore:members?filter=T1](/r/gov/dao/v3/memberstore:members?filter=T1)\n"},{"name":"gnomod.toml","body":"module = \"gno.land/p/samcrew/urlfilter\"\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\"\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"},{"name":"urlfilter_test.gno","body":"package urlfilter\n\nimport (\n\t\"net/url\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n)\n\nfunc buildTestTree() *bptree.BPTree {\n\troot := bptree.NewBPTree32()\n\n\t// keyF1 subtree\n\tt1 := bptree.NewBPTree32()\n\tt1.Set(\"key1_1\", nil)\n\tt1.Set(\"key1_2\", nil)\n\troot.Set(\"keyF1\", t1)\n\n\t// keyF2 subtree\n\tt2 := bptree.NewBPTree32()\n\tt2.Set(\"key2_1\", nil)\n\tt2.Set(\"key2_2\", nil)\n\troot.Set(\"keyF2\", t2)\n\n\treturn root\n}\n\nfunc TestApplyFilters(t *testing.T) {\n\tTreeParent := buildTestTree()\n\n\t// --- Case 1: No filter selected\n\tu, _ := url.Parse(\"/test\")\n\tmdFilters, items := ApplyFilters(u, TreeParent, \"filter\")\n\texpectedMarkdown := \" | [~~keyF1~~](/test?filter=keyF1)  | [~~keyF2~~](/test?filter=keyF2) \"\n\tif mdFilters != expectedMarkdown {\n\t\tt.Errorf(\"Expected Markdown %q, got %q\", expectedMarkdown, mdFilters)\n\t}\n\t// All items should be present\n\tcount := 0\n\titems.Iterate(\"\", \"\", func(k string, _ interface{}) bool {\n\t\tcount++\n\t\treturn false\n\t})\n\tif count != 4 {\n\t\tt.Errorf(\"Expected 4 items, got %d\", count)\n\t}\n\n\t// Try using ApplyFilters with a different name.\n\twithCustom, _ := ApplyFilters(u, TreeParent, \"custom-param-name\")\n\tif !strings.Contains(withCustom, \"custom-param-name=keyF1\") {\n\t\tt.Errorf(\"Expected 'custom-param-name' parameter in Markdown, got %q\", mdFilters)\n\t}\n\n\t// --- Case 2: One filter active (keyF1)\n\tu, _ = url.Parse(\"/test?filter=keyF1\")\n\tmdFilters, items = ApplyFilters(u, TreeParent, \"filter\")\n\texpectedMarkdown = \" | [**keyF1**](/test)  | [~~keyF2~~](/test?filter=keyF1%2CkeyF2) \"\n\tif mdFilters != expectedMarkdown {\n\t\tt.Errorf(\"Expected Markdown %q, got %q\", expectedMarkdown, mdFilters)\n\t}\n\t// Only keyF1 items should be present\n\tkeys := map[string]bool{}\n\titems.Iterate(\"\", \"\", func(k string, _ interface{}) bool {\n\t\tkeys[k] = true\n\t\treturn false\n\t})\n\tif len(keys) != 2 || !keys[\"key1_1\"] || !keys[\"key1_2\"] {\n\t\tt.Errorf(\"Unexpected items in filtered result: %#v\", keys)\n\t}\n\n\t// --- Case 3: Multiple filters active (keyF1, keyF2)\n\tu, _ = url.Parse(\"/test?filter=keyF1,keyF2\")\n\tmdFilters, items = ApplyFilters(u, TreeParent, \"filter\")\n\t// Both filters should be bold, no remove query for last one\n\tif items.Size() != 4 {\n\t\tt.Errorf(\"Expected 4 items, got %d\", items.Size())\n\t}\n\n\t// --- Case 4: Filter not existing\n\tu, _ = url.Parse(\"/test?filter=unknown\")\n\tmdFilters, items = ApplyFilters(u, TreeParent, \"filter\")\n\t// No matching items\n\tif items.Size() != 0 {\n\t\tt.Errorf(\"Expected 0 items for unknown filter, got %d\", items.Size())\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"jxtFOdS3ZMY1uq7VaUGCekRub04bUgKkHoskA0k1XfNayrn8U1K8mP+1yWkl4OsS4PZ2tjt9kANI5IUzRD0Hlw=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1g73v2anukg4ej7axwqpthsatzrxjsh0wk797da","package":{"name":"dao","path":"gno.land/r/gov/dao","files":[{"name":"allowlist_test.gno","body":"package dao\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// allowedDAOs is the sole authorization for UpdateImpl, memberstore.Get,\n// treasury.Send and treasury.SetTokenKeys, and InAllowedDAOs() fails OPEN when\n// it is empty — the bootstrap window that lets the genesis MsgRun seed the\n// member set before lockdown.\n//\n// These tests pin that the transition empty -\u003e non-empty is one-way: once the\n// DAO is locked down, UpdateImpl cannot put it back into the fail-open state.\n// Both paths below reopened the gate before the guard, because\n// NewUpdateRequest copies nil into a NON-nil empty slice and the old test was\n// `r.AllowedDAOs != nil`.\n//\n// These call the real UpdateImpl through a code realm rather than replaying\n// its logic, so reverting the guard makes them fail.\nfunc TestUpdateImplIgnoresEmptyAllowedDAOs(cur realm, t *testing.T) {\n\tsavedDAOs, savedDAO := allowedDAOs, dao\n\tdefer func() { allowedDAOs, dao = savedDAOs, savedDAO }()\n\n\tlock := func() {\n\t\tallowedDAOs = nil // reopen so the next UpdateImpl is permitted\n\t\ttesting.SetRealm(testing.NewCodeRealm(v3))\n\t\tUpdateImpl(cross(cur), UpdateRequest{DAO: \u0026dummyDao{}, AllowedDAOs: []string{v3}})\n\t\tuassert.False(t, InAllowedDAOs(invalid), \"precondition: locked down\")\n\t}\n\n\t// Path 1: NewUpdateRequest(d, nil) — \"swap the implementation, leave\n\t// permissions alone\", and the form v3/loader uses.\n\tlock()\n\ttesting.SetRealm(testing.NewCodeRealm(v3))\n\tUpdateImpl(cross(cur), NewUpdateRequest(\u0026dummyDao{}, nil))\n\tuassert.False(t, InAllowedDAOs(invalid),\n\t\t\"a nil AllowedDAOs must not reopen the permission gate\")\n\n\t// Path 2: an explicitly empty slice via the struct literal.\n\tlock()\n\ttesting.SetRealm(testing.NewCodeRealm(v3))\n\tUpdateImpl(cross(cur), UpdateRequest{DAO: \u0026dummyDao{}, AllowedDAOs: []string{}})\n\tuassert.False(t, InAllowedDAOs(invalid),\n\t\t\"an empty AllowedDAOs must not reopen the permission gate\")\n\n\t// A legitimate extension of the list must still apply.\n\tlock()\n\ttesting.SetRealm(testing.NewCodeRealm(v3))\n\tUpdateImpl(cross(cur), NewUpdateRequest(\u0026dummyDao{}, []string{v3, v4}))\n\tuassert.True(t, InAllowedDAOs(v4), \"a non-empty AllowedDAOs must still be stored\")\n\tuassert.False(t, InAllowedDAOs(invalid), \"and must not admit anyone else\")\n}\n\n// The bootstrap window itself must survive the guard: with no allowlist\n// configured yet, any caller is allowed so the genesis MsgRun can seed the\n// member set and then lock down.\nfunc TestBootstrapWindowStillOpen(t *testing.T) {\n\tsaved := allowedDAOs\n\tdefer func() { allowedDAOs = saved }()\n\n\tallowedDAOs = nil\n\tuassert.True(t, InAllowedDAOs(\"gno.land/r/gov/dao/v3/loader\"),\n\t\t\"an unset allowlist must stay open for genesis bootstrap\")\n}\n\n// len(AllowedDAOs) != 0 is not sufficient on its own. InAllowedDAOs compares by\n// exact string and a user realm's PkgPath() is \"\", so a single \"\" entry admits\n// any caller whose previous frame is a user realm — the same fail-open outcome\n// the guard exists to prevent. NewUpgradeDaoImplRequest passes its realmPkg\n// argument straight into the list, so an empty one reaches here.\nfunc TestUpdateImplRejectsBlankAllowedDAOEntry(cur realm, t *testing.T) {\n\tsavedDAOs, savedDAO := allowedDAOs, dao\n\tdefer func() { allowedDAOs, dao = savedDAOs, savedDAO }()\n\n\tfor _, blank := range []string{\"\", \"   \"} {\n\t\tallowedDAOs = nil\n\t\ttesting.SetRealm(testing.NewCodeRealm(v3))\n\t\tUpdateImpl(cross(cur), UpdateRequest{DAO: \u0026dummyDao{}, AllowedDAOs: []string{v3}})\n\n\t\ttesting.SetRealm(testing.NewCodeRealm(v3))\n\t\turequire.AbortsWithMessage(t, cur,\n\t\t\t\"AllowedDAOs entries must be realm paths; got an empty one\",\n\t\t\tfunc() {\n\t\t\t\tUpdateImpl(cross(cur), UpdateRequest{\n\t\t\t\t\tDAO:         \u0026dummyDao{},\n\t\t\t\t\tAllowedDAOs: []string{v3, blank},\n\t\t\t\t})\n\t\t\t})\n\n\t\tuassert.False(t, InAllowedDAOs(\"\"),\n\t\t\t\"a blank entry must never make it into the allowlist\")\n\t\tuassert.True(t, InAllowedDAOs(v3),\n\t\t\t\"the rejected request must leave the previous allowlist intact\")\n\t}\n}\n\n// A padded entry passes a plain non-blank test but is useless: entries are\n// stored exactly as given and InAllowedDAOs compares whole strings, so\n// \" gno.land/r/x \" matches no caller. The list is still non-empty, so the\n// bootstrap window is closed. A proposal that padded every entry would lock\n// the DAO out of its own allowlist with no way back.\nfunc TestUpdateImplRejectsPaddedAllowedDAOEntry(cur realm, t *testing.T) {\n\tsavedDAOs, savedDAO := allowedDAOs, dao\n\tdefer func() { allowedDAOs, dao = savedDAOs, savedDAO }()\n\n\tfor _, padded := range []string{\" \" + v4, v4 + \" \", \"\\t\" + v4} {\n\t\tallowedDAOs = nil\n\t\ttesting.SetRealm(testing.NewCodeRealm(v3))\n\t\tUpdateImpl(cross(cur), UpdateRequest{DAO: \u0026dummyDao{}, AllowedDAOs: []string{v3}})\n\n\t\ttesting.SetRealm(testing.NewCodeRealm(v3))\n\t\turequire.AbortsWithMessage(t, cur,\n\t\t\t\"AllowedDAOs entries must not have leading or trailing spaces; entry 1\",\n\t\t\tfunc() {\n\t\t\t\tUpdateImpl(cross(cur), UpdateRequest{\n\t\t\t\t\tDAO:         \u0026dummyDao{},\n\t\t\t\t\tAllowedDAOs: []string{v3, padded},\n\t\t\t\t})\n\t\t\t})\n\n\t\tuassert.False(t, InAllowedDAOs(padded),\n\t\t\t\"a padded entry must never make it into the allowlist\")\n\t\tuassert.True(t, InAllowedDAOs(v3),\n\t\t\t\"the rejected request must leave the previous allowlist intact\")\n\t}\n}\n"},{"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":"proxy_test.gno","body":"package dao\n\nimport (\n\t\"chain/runtime/unsafe\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\n// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\n\nconst (\n\tv3 = \"gno.land/r/gov/dao/v3/impl\"\n\tv4 = \"gno.land/r/gov/dao/v4/impl\"\n\tv5 = \"gno.land/r/gov/dao/v5/impl\"\n\tv6 = \"gno.land/r/gov/dao/v6/impl\"\n)\n\nconst invalid = \"gno.land/r/invalid/dao\"\n\nvar alice = testutils.TestAddress(\"alice\")\n\nfunc TestProxy_Functions(cur realm, t *testing.T) {\n\t// initialize tests\n\tUpdateImpl(cross(cur), UpdateRequest{\n\t\tDAO:         \u0026dummyDao{},\n\t\tAllowedDAOs: []string{v3},\n\t})\n\n\t// invalid package cannot add a new dao in charge\n\ttesting.SetRealm(testing.NewCodeRealm(invalid))\n\turequire.AbortsWithMessage(t, cur, \"permission denied for prev realm: gno.land/r/invalid/dao\", func() {\n\t\tUpdateImpl(cross(cur), UpdateRequest{\n\t\t\tDAO: \u0026dummyDao{},\n\t\t})\n\t})\n\n\t// dao in charge can add a new dao\n\ttesting.SetRealm(testing.NewCodeRealm(v3))\n\turequire.NotPanics(t, cur, func() {\n\t\tUpdateImpl(cross(cur), UpdateRequest{\n\t\t\tDAO: \u0026dummyDao{},\n\t\t})\n\t})\n\n\t// v3 that is in charge adds v5 in charge\n\ttesting.SetRealm(testing.NewCodeRealm(v3))\n\turequire.NotPanics(t, cur, func() {\n\t\tUpdateImpl(cross(cur), UpdateRequest{\n\t\t\tDAO:         \u0026dummyDao{},\n\t\t\tAllowedDAOs: []string{v3, v5},\n\t\t})\n\t})\n\n\t// v3 can still do updates\n\ttesting.SetRealm(testing.NewCodeRealm(v3))\n\turequire.NotPanics(t, cur, func() {\n\t\tUpdateImpl(cross(cur), UpdateRequest{\n\t\t\tAllowedDAOs: []string{v4},\n\t\t})\n\t})\n\n\t// not after removing himself from allowedDAOs list\n\ttesting.SetRealm(testing.NewCodeRealm(v3))\n\turequire.AbortsWithMessage(t, cur, \"permission denied for prev realm: gno.land/r/gov/dao/v3/impl\", func() {\n\t\tUpdateImpl(cross(cur), UpdateRequest{\n\t\t\tAllowedDAOs: []string{v3},\n\t\t})\n\t})\n\n\tvar pid ProposalID\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\turequire.NotPanics(t, cur, func() {\n\t\te := NewSimpleExecutor(0, cur,\n\t\t\tfunc(realm) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\t\"\",\n\t\t)\n\t\tpid = MustCreateProposal(cross(cur), NewProposalRequest(\"Proposal Title\", \"Description\", e))\n\t})\n\n\tp, err := GetProposal(1000)\n\tif p != nil || err == nil {\n\t\tpanic(\"proposal should not exist and should return an error\")\n\t}\n\tp = MustGetProposal(pid)\n\turequire.Equal(t, \"Proposal Title\", p.Title())\n\turequire.Equal(t, p.Author().String(), alice.String())\n\n\t// need to switch the context back to v4\n\ttesting.SetRealm(testing.NewCodeRealm(v4))\n\turequire.Equal(\n\t\tt,\n\t\t\"Render: gno.land/r/gov/dao/test\",\n\t\tRender(cross(cur), \"test\"),\n\t)\n\n\t// reset state\n\ttesting.SetRealm(testing.NewCodeRealm(v4))\n\tUpdateImpl(cross(cur), UpdateRequest{\n\t\tDAO: \u0026dummyDao{},\n\t})\n\t// UpdateImpl deliberately ignores an empty AllowedDAOs, so it can no\n\t// longer be used to restore the bootstrap-open state — that is the point\n\t// of the guard. Reset the package var directly instead; we are in the\n\t// same package.\n\tallowedDAOs = nil\n}\n\ntype dummyDao struct{}\n\nfunc (dd *dummyDao) PreCreateProposal(_ int, rlm realm, r ProposalRequest) (address, error) {\n\treturn unsafe.OriginCaller(), nil\n}\n\nfunc (dd *dummyDao) PostCreateProposal(_ int, rlm realm, r ProposalRequest, pid ProposalID) {\n}\n\nfunc (dd *dummyDao) VoteOnProposal(_ int, rlm realm, r VoteRequest) error {\n\treturn nil\n}\n\nfunc (dd *dummyDao) PreExecuteProposal(_ int, rlm realm, pid ProposalID) (bool, error) {\n\treturn true, nil\n}\n\nfunc (dd *dummyDao) ExecuteProposal(_ int, rlm realm, pid ProposalID, e Executor) error {\n\treturn nil\n}\n\nfunc (dd *dummyDao) Render(cur realm, pkgpath string, path string) string {\n\treturn \"Render: \" + pkgpath + \"/\" + path\n}\n"},{"name":"types.gno","body":"package dao\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 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\nfunc (e *SimpleExecutor) Execute(cur realm) error {\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// Note what this does NOT gate: NewSafeExecutor has no call sites, so this\n\t// type is currently dead code. Live proposal execution goes through the\n\t// Executor interface to SimpleExecutor.Execute below, which has no\n\t// InAllowedDAOs check -- it is contained instead by the executor being\n\t// unexported inside ProposalRequest/Proposal with no accessor. Do not read\n\t// this method as evidence that executor invocation is allowlist-gated.\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"+bMq+Jm0tvyKKu27fwUDLDWW4FR1z4kdK9J3+Lo+YpZDOwgeJMtJTK691gDAev1215MSwlK1LC13q74r5+nGvw=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l","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/v1` 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/v1`, 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/v1`'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/v1/init.gno` likewise\n  auto-whitelists `gno.land/r/sys/namereg/v1`. 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\"\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/v1, 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":"crossrealm_test.gno","body":"package users\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\n// TestUpdateNameCallerIdentity verifies that the CurrentRealm() check in\n// UpdateName correctly identifies the calling controller.\n//\n// Background: RegisterUser uses PreviousRealm() because it is a crossing\n// function (cur realm). UpdateName uses CurrentRealm() because it is a\n// non-crossing method on *UserData. Per the interrealm spec:\n//\n//   - Crossing function: CurrentRealm = this realm, PreviousRealm = caller\n//   - Non-crossing method on external object, called from crossing context:\n//     CurrentRealm = caller (unchanged from crossing context)\n//\n// This test verifies that a whitelisted controller can call UpdateName,\n// and a non-whitelisted realm cannot.\nfunc TestUpdateNameCallerIdentity(cur realm, t *testing.T) {\n\tcontrollerPath := initControllerPath\n\tnonControllerPath := \"gno.land/r/evil/attacker\"\n\n\tt.Run(\"whitelisted_controller_can_update\", func(cur realm, t *testing.T) {\n\t\tcleanStore(t)\n\n\t\t// Register as whitelisted controller\n\t\ttesting.SetRealm(testing.NewCodeRealm(controllerPath))\n\t\turequire.NoError(t, RegisterUser(cross(cur), \"testuser1\", testutils.TestAddress(\"testuser1\")))\n\n\t\t// Resolve and update name — should succeed because controller is whitelisted\n\t\tdata := ResolveAddress(testutils.TestAddress(\"testuser1\"))\n\t\turequire.NotEqual(t, nil, data)\n\t\tuassert.NoError(t, data.UpdateName(0, cur, \"newname1\"))\n\t\tuassert.Equal(t, \"newname1\", data.Name())\n\t})\n\n\tt.Run(\"non_whitelisted_realm_cannot_update\", func(cur realm, t *testing.T) {\n\t\tcleanStore(t)\n\n\t\t// Register as whitelisted controller\n\t\ttesting.SetRealm(testing.NewCodeRealm(controllerPath))\n\t\turequire.NoError(t, RegisterUser(cross(cur), \"testuser2\", testutils.TestAddress(\"testuser2\")))\n\n\t\tdata := ResolveAddress(testutils.TestAddress(\"testuser2\"))\n\t\turequire.NotEqual(t, nil, data)\n\n\t\t// Switch to non-whitelisted realm — UpdateName should fail\n\t\ttesting.SetRealm(testing.NewCodeRealm(nonControllerPath))\n\t\terr := data.UpdateName(0, cur, \"hacked\")\n\t\tuassert.ErrorContains(t, err, \"does not exist in whitelist\")\n\t\tuassert.Equal(t, \"testuser2\", data.Name()) // name unchanged\n\t})\n}\n\n// TestDeleteCallerIdentity verifies the same CurrentRealm() behavior for Delete.\nfunc TestDeleteCallerIdentity(cur realm, t *testing.T) {\n\tcontrollerPath := initControllerPath\n\tnonControllerPath := \"gno.land/r/evil/attacker\"\n\n\tt.Run(\"whitelisted_controller_can_delete\", func(cur realm, t *testing.T) {\n\t\tcleanStore(t)\n\n\t\ttesting.SetRealm(testing.NewCodeRealm(controllerPath))\n\t\turequire.NoError(t, RegisterUser(cross(cur), \"deluser1\", testutils.TestAddress(\"deluser1\")))\n\n\t\tdata := ResolveAddress(testutils.TestAddress(\"deluser1\"))\n\t\turequire.NotEqual(t, nil, data)\n\t\tuassert.NoError(t, data.Delete(0, cur))\n\t\tuassert.True(t, data.IsDeleted())\n\t})\n\n\tt.Run(\"non_whitelisted_realm_cannot_delete\", func(cur realm, t *testing.T) {\n\t\tcleanStore(t)\n\n\t\ttesting.SetRealm(testing.NewCodeRealm(controllerPath))\n\t\turequire.NoError(t, RegisterUser(cross(cur), \"deluser2\", testutils.TestAddress(\"deluser2\")))\n\n\t\tdata := ResolveAddress(testutils.TestAddress(\"deluser2\"))\n\t\turequire.NotEqual(t, nil, data)\n\n\t\t// Switch to non-whitelisted realm — Delete should fail\n\t\ttesting.SetRealm(testing.NewCodeRealm(nonControllerPath))\n\t\terr := data.Delete(0, cur)\n\t\tuassert.ErrorContains(t, err, \"does not exist in whitelist\")\n\t\tuassert.False(t, data.IsDeleted()) // not deleted\n\t})\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":"store_test.gno","body":"package users\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/bptree/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     = \"alice\"\n\taliceAddr = testutils.TestAddress(alice)\n\tbob       = \"bob\"\n\tbobAddr   = testutils.TestAddress(bob)\n\n\twhitelistedCallerAddr = chain.PackageAddress(initControllerPath)\n)\n\nfunc TestRegister(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(initControllerPath))\n\n\tt.Run(\"valid_registration\", func(t *testing.T) {\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\n\t\tres, isLatest := ResolveName(alice)\n\t\tuassert.Equal(t, aliceAddr, res.Addr())\n\t\tuassert.True(t, isLatest)\n\n\t\tres = ResolveAddress(aliceAddr)\n\t\tuassert.Equal(t, alice, res.Name())\n\t})\n\n\tt.Run(\"invalid_inputs\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"\", aliceAddr), ErrEmptyUsername.Error())\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), alice, \"\"), ErrInvalidAddress.Error())\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), alice, \"invalidaddress\"), ErrInvalidAddress.Error())\n\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"username with a space\", aliceAddr), ErrInvalidUsername.Error())\n\t\tuassert.ErrorContains(t,\n\t\t\tRegisterUser(cross(cur), \"verylongusernameverylongusernameverylongusernameverylongusername1\", aliceAddr),\n\t\t\tErrInvalidUsername.Error())\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"namewith^\u0026()\", aliceAddr), ErrInvalidUsername.Error())\n\n\t\t// Lowercase-only enforcement (closes case-confusable squatting via\n\t\t// Alice/alice/ALICE registering as distinct names — see TO_REVIEW\n\t\t// adversarial review). reName mirrors gno's mempackage Re_name shape.\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"Alice\", aliceAddr), ErrInvalidUsername.Error())\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"ALICE\", aliceAddr), ErrInvalidUsername.Error())\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"aLice\", aliceAddr), ErrInvalidUsername.Error())\n\n\t\t// Must start with a lowercase letter. Names starting with a digit,\n\t\t// underscore, or hyphen are rejected.\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"1alice\", aliceAddr), ErrInvalidUsername.Error())\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"9\", aliceAddr), ErrInvalidUsername.Error())\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"_alice\", aliceAddr), ErrInvalidUsername.Error())\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"-alice\", aliceAddr), ErrInvalidUsername.Error())\n\n\t\t// Cannot end with a separator either (the new mempackage-aligned\n\t\t// regex requires the final char to be in [a-z0-9]).\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"alice_\", aliceAddr), ErrInvalidUsername.Error())\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"alice-\", aliceAddr), ErrInvalidUsername.Error())\n\n\t\t// Cannot have consecutive separators in the middle either.\n\t\t// Each separator MUST be followed by at least one alphanumeric.\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"alice--bob\", aliceAddr), ErrInvalidUsername.Error())\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"alice__bob\", aliceAddr), ErrInvalidUsername.Error())\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"alice-_bob\", aliceAddr), ErrInvalidUsername.Error())\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"alice_-bob\", aliceAddr), ErrInvalidUsername.Error())\n\n\t\t// Length cap of exactly 64 — boundary cases.\n\t\texactly65 := \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" // 65 chars\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), exactly65, aliceAddr), ErrInvalidUsername.Error())\n\t})\n\n\tt.Run(\"valid_edge_cases\", func(t *testing.T) {\n\t\t// Names valid under the mempackage-aligned reName: starts with a\n\t\t// letter, may contain hyphens or underscores in the middle, ends\n\t\t// in [a-z0-9]. The hyphen support is what enables the namereg/v1\n\t\t// `nym-...` prefix shape.\n\t\tcleanStore(t)\n\t\turequire.NoError(t, RegisterUser(cross(cur),\n\t\t\t\"nym-alice123\",\n\t\t\ttestutils.TestAddress(\"u_nym_alice\")))\n\n\t\tcleanStore(t)\n\t\turequire.NoError(t, RegisterUser(cross(cur),\n\t\t\t\"a_b_c\",\n\t\t\ttestutils.TestAddress(\"u_underscore\")))\n\n\t\tcleanStore(t)\n\t\turequire.NoError(t, RegisterUser(cross(cur),\n\t\t\t\"a\",\n\t\t\ttestutils.TestAddress(\"u_singlechar\")))\n\n\t\tcleanStore(t)\n\t\t// 64 chars exactly (length cap is inclusive).\n\t\texactly64 := \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n\t\turequire.NoError(t, RegisterUser(cross(cur),\n\t\t\texactly64,\n\t\t\ttestutils.TestAddress(\"u_64\")))\n\t})\n\n\tt.Run(\"addr_already_registered\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\n\t\t// Try registering again\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"othername\", aliceAddr), ErrAlreadyHasName.Error())\n\t})\n\n\tt.Run(\"name_taken\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\n\t\t// Try registering alice's name with bob's address\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), alice, bobAddr), ErrNameTaken.Error())\n\t})\n\n\tt.Run(\"user_deleted\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\t\tdata := ResolveAddress(aliceAddr)\n\t\turequire.NoError(t, data.Delete(0, cur))\n\n\t\t// Try re-registering after deletion\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"newname\", aliceAddr), ErrDeletedUser.Error())\n\t})\n\n\tt.Run(\"address_lookalike\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\t// Address as username\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", aliceAddr), ErrNameLikeAddress.Error())\n\t\t// Beginning of address as username\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), \"g1jg8mtutu9khhfwc4nxmu\", aliceAddr), ErrNameLikeAddress.Error())\n\t\tuassert.NoError(t, RegisterUser(cross(cur), \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5longerthananaddress\", aliceAddr))\n\t})\n}\n\nfunc TestUpdateName(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(initControllerPath))\n\n\tt.Run(\"valid_direct_alias\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\t\tdata := ResolveAddress(aliceAddr)\n\t\t{\n\t\t\ttesting.SetOriginCaller(whitelistedCallerAddr)\n\t\t\tuassert.NoError(t, data.UpdateName(0, cur, \"alice1\"))\n\t\t\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/sys/users\"))\n\t\t}\n\t})\n\n\tt.Run(\"valid_double_alias\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\t\tdata := ResolveAddress(aliceAddr)\n\t\t{\n\t\t\ttesting.SetOriginCaller(whitelistedCallerAddr)\n\t\t\tuassert.NoError(t, data.UpdateName(0, cur, \"alice2\"))\n\t\t\tuassert.NoError(t, data.UpdateName(0, cur, \"alice3\"))\n\t\t\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/sys/users\"))\n\t\t}\n\t\tuassert.Equal(t, ResolveAddress(aliceAddr).username, \"alice3\")\n\t})\n\n\tt.Run(\"name_taken\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\n\t\tdata := ResolveAddress(aliceAddr)\n\t\tuassert.Error(t, data.UpdateName(0, cur, alice), ErrNameTaken.Error())\n\t})\n\n\tt.Run(\"alias_before_name\", func(t *testing.T) {\n\t\tcleanStore(t)\n\t\tdata := ResolveAddress(aliceAddr) // not registered\n\n\t\tuassert.ErrorContains(t, data.UpdateName(0, cur, alice), ErrUserNotExistOrDeleted.Error())\n\t})\n\n\tt.Run(\"alias_after_delete\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\t\tdata := ResolveAddress(aliceAddr)\n\t\t{\n\t\t\turequire.NoError(t, data.Delete(0, cur))\n\t\t\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/sys/users\"))\n\t\t}\n\n\t\tdata = ResolveAddress(aliceAddr)\n\t\t{\n\t\t\tuassert.ErrorContains(t, data.UpdateName(0, cur, \"newalice\"), ErrUserNotExistOrDeleted.Error())\n\t\t\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/sys/users\"))\n\t\t}\n\t})\n\n\t// Audit finding #3: a controller holding a cached *UserData pointer to a\n\t// user that gets deleted between resolve and update must not be able to\n\t// insert a new alias. The alias_after_delete test above re-resolves and\n\t// gets nil, so it only exercises the u==nil branch. This test holds the\n\t// pointer across the delete and verifies the deleted-flag branch.\n\tt.Run(\"alias_with_cached_pointer_after_delete\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\t\t// Cache the pointer BEFORE deletion (simulating a controller that\n\t\t// resolved earlier and held the reference).\n\t\tcached := ResolveAddress(aliceAddr)\n\t\turequire.NotEqual(t, nil, cached)\n\n\t\t// Delete via a fresh resolve.\n\t\tdata := ResolveAddress(aliceAddr)\n\t\t{\n\t\t\turequire.NoError(t, data.Delete(0, cur))\n\t\t\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/sys/users\"))\n\t\t}\n\n\t\t// The cached pointer is non-nil but its .deleted is now true.\n\t\turequire.NotEqual(t, nil, cached)\n\t\tuassert.True(t, cached.IsDeleted())\n\n\t\t// Attempting UpdateName on the cached pointer must reject — without\n\t\t// this check, \"squattedname\" would be inserted into nameStore\n\t\t// pointing at the deleted user, becoming permanently unresolvable\n\t\t// AND unregisterable.\n\t\t{\n\t\t\ttesting.SetOriginCaller(whitelistedCallerAddr)\n\t\t\tuassert.ErrorContains(t, cached.UpdateName(0, cur, \"squattedname\"), ErrUserNotExistOrDeleted.Error())\n\t\t\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/sys/users\"))\n\t\t}\n\n\t\t// Confirm the squat didn't happen: nameStore should NOT have it.\n\t\tuassert.False(t, nameStore.Has(\"squattedname\"))\n\t})\n\n\tt.Run(\"invalid_inputs\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\t\tdata := ResolveAddress(aliceAddr)\n\t\t{\n\t\t\ttesting.SetOriginCaller(whitelistedCallerAddr)\n\t\t\tuassert.ErrorContains(t, data.UpdateName(0, cur, \"\"), ErrEmptyUsername.Error())\n\t\t\tuassert.ErrorContains(t, data.UpdateName(0, cur, \"username with a space\"), ErrInvalidUsername.Error())\n\t\t\tuassert.ErrorContains(t,\n\t\t\t\tdata.UpdateName(0, cur, \"verylongusernameverylongusernameverylongusernameverylongusername1\"),\n\t\t\t\tErrInvalidUsername.Error())\n\t\t\tuassert.ErrorContains(t, data.UpdateName(0, cur, \"namewith^\u0026()\"), ErrInvalidUsername.Error())\n\t\t\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/sys/users\"))\n\t\t}\n\t})\n\n\tt.Run(\"address_lookalike\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\t\tdata := ResolveAddress(aliceAddr)\n\n\t\t{\n\t\t\t// Address as username\n\t\t\tuassert.ErrorContains(t, data.UpdateName(0, cur, \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"), ErrNameLikeAddress.Error())\n\t\t\t// Beginning of address as username\n\t\t\tuassert.ErrorContains(t, data.UpdateName(0, cur, \"g1jg8mtutu9khhfwc4nxmu\"), ErrNameLikeAddress.Error())\n\t\t\tuassert.NoError(t, data.UpdateName(0, cur, \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5longerthananaddress\"))\n\t\t\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/sys/users\"))\n\t\t}\n\t})\n}\n\nfunc TestDelete(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(initControllerPath))\n\n\tt.Run(\"non_existent_user\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\tdata := ResolveAddress(testutils.TestAddress(\"unregistered\"))\n\t\tuassert.ErrorContains(t, data.Delete(0, cur), ErrUserNotExistOrDeleted.Error())\n\t})\n\n\tt.Run(\"double_delete\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\t\tdata := ResolveAddress(aliceAddr)\n\t\turequire.NoError(t, data.Delete(0, cur))\n\t\tdata = ResolveAddress(aliceAddr)\n\t\tuassert.ErrorContains(t, data.Delete(0, cur), ErrUserNotExistOrDeleted.Error())\n\t})\n\n\tt.Run(\"valid_delete\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\t\tdata := ResolveAddress(aliceAddr)\n\t\tuassert.NoError(t, data.Delete(0, cur))\n\n\t\tresolved1, _ := ResolveName(alice)\n\t\tuassert.Equal(t, nil, resolved1)\n\t\tuassert.Equal(t, nil, ResolveAddress(aliceAddr))\n\t})\n}\n\nfunc TestRegisterNotWhitelisted(cur realm, t *testing.T) {\n\tt.Run(\"register_not_whitelisted\", func(t *testing.T) {\n\t\tuassert.ErrorContains(t, RegisterUser(cross(cur), alice, aliceAddr), \"does not exist in whitelist\")\n\t})\n}\n\nfunc TestCanonicalize(cur realm, t *testing.T) {\n\tcases := []struct {\n\t\tin, want string\n\t}{\n\t\t// Single-rule cases.\n\t\t{\"l\", \"i\"}, {\"i\", \"i\"}, {\"1\", \"i\"},\n\t\t{\"0\", \"o\"}, {\"o\", \"o\"},\n\t\t{\"-\", \"\"}, {\".\", \"\"}, {\"_\", \"\"},\n\n\t\t// Identity / pass-through.\n\t\t{\"abc\", \"abc\"}, {\"xyz\", \"xyz\"}, {\"123\", \"i23\"},\n\n\t\t// Open Nym Tier examples from the design doc.\n\t\t{\"nym-vital1k123\", \"nymvitaiiki23\"},\n\t\t{\"nym-vitalik123\", \"nymvitaiiki23\"},\n\t\t{\"nym-vital1k999\", \"nymvitaiik999\"},\n\n\t\t// Same stem, different digit suffix → distinct canonicals.\n\t\t{\"nym-foolbar000\", \"nymfooibarooo\"},\n\t\t{\"nym-foolbar001\", \"nymfooibarooi\"},\n\n\t\t// Three-way separator equivalence.\n\t\t{\"xyz-com\", \"xyzcom\"},\n\t\t{\"xyz_com\", \"xyzcom\"},\n\t\t{\"xyz.com\", \"xyzcom\"},\n\n\t\t// Idempotency: applying twice equals applying once.\n\t\t{\"nymvitaiiki23\", \"nymvitaiiki23\"},\n\n\t\t// Empty input.\n\t\t{\"\", \"\"},\n\t}\n\tfor _, tc := range cases {\n\t\tgot := Canonicalize(tc.in)\n\t\tuassert.Equal(t, tc.want, got)\n\t}\n}\n\nfunc TestCanonicalize_NonASCIIPassthrough(cur realm, t *testing.T) {\n\t// ASCII-only contract: the function passes non-ASCII bytes through\n\t// unchanged. Locks the documented contract — registration paths\n\t// reject non-ASCII upstream via validateName, so this code path is\n\t// only reachable through direct callers from other realms.\n\tuassert.Equal(t, \"café\", Canonicalize(\"café\"))\n\tuassert.Equal(t, \"naïve\", Canonicalize(\"naïve\"))\n}\n\nfunc TestRegisterUser_CanonicalCollision(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(initControllerPath))\n\n\tt.Run(\"non_bypass_blocks\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), \"vitalik\", aliceAddr))\n\t\t// Different exact name, same canonical form → ErrCanonicalCollision.\n\t\tuassert.ErrorContains(t,\n\t\t\tRegisterUser(cross(cur), \"vital1k\", bobAddr),\n\t\t\tErrCanonicalCollision.Error(),\n\t\t)\n\t})\n\n\tt.Run(\"non_bypass_blocks_with_separator_strip\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), \"xyz-com\", aliceAddr))\n\t\tuassert.ErrorContains(t,\n\t\t\tRegisterUser(cross(cur), \"xyz_com\", bobAddr),\n\t\t\tErrCanonicalCollision.Error(),\n\t\t)\n\t})\n\n\tt.Run(\"non_bypass_allows_different_digit_suffix\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\t// Same alpha stem, different digits-after-canonicalization → no collision.\n\t\turequire.NoError(t, RegisterUser(cross(cur), \"nym-foolbar000\", aliceAddr))\n\t\turequire.NoError(t, RegisterUser(cross(cur), \"nym-foolbar999\",\n\t\t\ttestutils.TestAddress(\"foolbar999\")))\n\t})\n\n\tt.Run(\"exact_name_taken_takes_precedence\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), \"vitalik\", aliceAddr))\n\t\t// Same exact name → ErrNameTaken (NOT ErrCanonicalCollision).\n\t\t// The nameStore.Has check precedes the canonical check.\n\t\tuassert.ErrorContains(t,\n\t\t\tRegisterUser(cross(cur), \"vitalik\", bobAddr),\n\t\t\tErrNameTaken.Error(),\n\t\t)\n\t})\n}\n\nfunc TestRegisterUserIgnoreCanonical(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(initControllerPath))\n\n\tt.Run(\"bypass_succeeds_on_canonical_collision\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), \"vitalik\", aliceAddr))\n\t\t// Bypass succeeds even though canonical collides.\n\t\turequire.NoError(t, RegisterUserIgnoreCanonical(cross(cur), \"vital1k\", bobAddr))\n\n\t\t// Both names resolve.\n\t\tres, _ := ResolveName(\"vitalik\")\n\t\tuassert.Equal(t, aliceAddr, res.Addr())\n\t\tres, _ = ResolveName(\"vital1k\")\n\t\tuassert.Equal(t, bobAddr, res.Addr())\n\t})\n\n\tt.Run(\"bypass_later_wins_overwrite\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\t// First registration writes canonical entry.\n\t\turequire.NoError(t, RegisterUser(cross(cur), \"vitalik\", aliceAddr))\n\t\texisting, taken := IsCanonicalTaken(\"vital1k\")\n\t\turequire.True(t, taken)\n\t\tuassert.Equal(t, \"vitalik\", existing)\n\n\t\t// Bypass write overwrites the canonical entry (decision #14).\n\t\turequire.NoError(t, RegisterUserIgnoreCanonical(cross(cur), \"vital1k\", bobAddr))\n\t\texisting, taken = IsCanonicalTaken(\"vitalik\")\n\t\turequire.True(t, taken)\n\t\tuassert.Equal(t, \"vital1k\", existing)\n\t})\n\n\tt.Run(\"bypass_still_blocks_exact_taken\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), \"vitalik\", aliceAddr))\n\t\t// Same exact name still blocked, even via the bypass path.\n\t\tuassert.ErrorContains(t,\n\t\t\tRegisterUserIgnoreCanonical(cross(cur), \"vitalik\", bobAddr),\n\t\t\tErrNameTaken.Error(),\n\t\t)\n\t})\n}\n\nfunc TestUpdateName_CanonicalCollision(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(initControllerPath))\n\n\tt.Run(\"self_collision_blocks_per_decision_15\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\t// Alice registers vital1k. Canonical store maps \"vitaiik\" → \"vital1k\".\n\t\turequire.NoError(t, RegisterUser(cross(cur), \"vital1k\", aliceAddr))\n\t\tdata := ResolveAddress(aliceAddr)\n\n\t\t// Alice attempts to rename to a confusable variant of HER OWN name.\n\t\t// Decision #15: blocked. No self-collision exception in the\n\t\t// non-bypass path.\n\t\ttesting.SetOriginCaller(whitelistedCallerAddr)\n\t\tuassert.ErrorContains(t,\n\t\t\tdata.UpdateName(0, cur, \"vitalik\"),\n\t\t\tErrCanonicalCollision.Error(),\n\t\t)\n\t\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/sys/users\"))\n\t})\n\n\tt.Run(\"different_user_collision_blocks\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), \"vitalik\", aliceAddr))\n\t\turequire.NoError(t, RegisterUser(cross(cur), \"bob\", bobAddr))\n\n\t\tdata := ResolveAddress(bobAddr)\n\t\ttesting.SetOriginCaller(whitelistedCallerAddr)\n\t\tuassert.ErrorContains(t,\n\t\t\tdata.UpdateName(0, cur, \"vital1k\"),\n\t\t\tErrCanonicalCollision.Error(),\n\t\t)\n\t\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/sys/users\"))\n\t})\n\n\tt.Run(\"bypass_allows_self_collision_rename\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), \"vital1k\", aliceAddr))\n\t\tdata := ResolveAddress(aliceAddr)\n\n\t\t// Bypass path allows the rename (DAO grant scenario).\n\t\ttesting.SetOriginCaller(whitelistedCallerAddr)\n\t\turequire.NoError(t, data.UpdateNameIgnoreCanonical(0, cur, \"vitalik\"))\n\t\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/sys/users\"))\n\n\t\t// Both names point to alice; latest is \"vitalik\".\n\t\tuassert.Equal(t, \"vitalik\", ResolveAddress(aliceAddr).Name())\n\t\t// Old name still resolves to alice (decision #4: keep old entry).\n\t\tres, isLatest := ResolveName(\"vital1k\")\n\t\tuassert.Equal(t, aliceAddr, res.Addr())\n\t\tuassert.False(t, isLatest)\n\t})\n}\n\nfunc TestCanonicalEntry_Persists_After_Delete(cur realm, t *testing.T) {\n\t// Decision #5: Delete does NOT remove the canonical entry. Mirrors\n\t// the existing tombstone behavior (anti-revival policy).\n\ttesting.SetRealm(testing.NewCodeRealm(initControllerPath))\n\tcleanStore(t)\n\n\turequire.NoError(t, RegisterUser(cross(cur), \"vitalik\", aliceAddr))\n\tdata := ResolveAddress(aliceAddr)\n\turequire.NoError(t, data.Delete(0, cur))\n\n\t// Canonical entry retained.\n\texisting, taken := IsCanonicalTaken(\"vitalik\")\n\turequire.True(t, taken)\n\tuassert.Equal(t, \"vitalik\", existing)\n\n\t// A different user CANNOT register a confusable variant — the deleted\n\t// user's canonical claim still stands.\n\tuassert.ErrorContains(t,\n\t\tRegisterUser(cross(cur), \"vital1k\", bobAddr),\n\t\tErrCanonicalCollision.Error(),\n\t)\n}\n\nfunc TestCanonicalEntry_Persists_After_UpdateName(cur realm, t *testing.T) {\n\t// Decision #4: UpdateName keeps the OLD canonical entry. Mirrors the\n\t// existing nameStore alias retention (anti-rename-squat policy).\n\ttesting.SetRealm(testing.NewCodeRealm(initControllerPath))\n\tcleanStore(t)\n\n\turequire.NoError(t, RegisterUser(cross(cur), \"alice\", aliceAddr))\n\tdata := ResolveAddress(aliceAddr)\n\ttesting.SetOriginCaller(whitelistedCallerAddr)\n\turequire.NoError(t, data.UpdateName(0, cur, \"alice2\"))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/sys/users\"))\n\n\t// Both old and new canonical entries exist.\n\texisting, taken := IsCanonicalTaken(\"alice\")\n\turequire.True(t, taken)\n\tuassert.Equal(t, \"alice\", existing)\n\n\texisting, taken = IsCanonicalTaken(\"alice2\")\n\turequire.True(t, taken)\n\tuassert.Equal(t, \"alice2\", existing)\n}\n\n// cleanStore should not be needed, as vm store should be reset after each test.\n// Reference: https://github.com/gnolang/gno/issues/1982\nfunc cleanStore(t *testing.T) {\n\tt.Helper()\n\n\tnameStore = bptree.NewBPTree32()\n\taddressStore = bptree.NewBPTree32()\n\tcanonicalStore = bptree.NewBPTree32()\n}\n"},{"name":"users.gno","body":"package users\n\nimport \"gno.land/p/nt/bptree/v0/rotree\"\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"},{"name":"users_test.gno","body":"package users\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\t\"gno.land/p/nt/urequire/v0\"\n)\n\n// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\n\nfunc TestResolveName(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(initControllerPath))\n\n\tt.Run(\"single_name\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\n\t\tres, isLatest := ResolveName(alice)\n\t\tuassert.Equal(t, aliceAddr, res.Addr())\n\t\tuassert.Equal(t, alice, res.Name())\n\t\tuassert.True(t, isLatest)\n\t})\n\n\tt.Run(\"name+Alias\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\t\tdata, _ := ResolveName(alice)\n\t\turequire.NoError(t, data.UpdateName(0, cur, \"alice1\"))\n\n\t\tres, isLatest := ResolveName(\"alice1\")\n\t\turequire.NotEqual(t, nil, res)\n\n\t\tuassert.Equal(t, aliceAddr, res.Addr())\n\t\tuassert.Equal(t, \"alice1\", res.Name())\n\t\tuassert.True(t, isLatest)\n\t})\n\n\tt.Run(\"multiple_aliases\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\n\t\t// RegisterUser and check each Alias\n\t\tvar names []string\n\t\tnames = append(names, alice)\n\t\tfor i := 0; i \u003c 5; i++ {\n\t\t\talias := \"alice\" + strconv.Itoa(i)\n\t\t\tnames = append(names, alias)\n\n\t\t\tdata, _ := ResolveName(alice)\n\t\t\turequire.NoError(t, data.UpdateName(0, cur, alias))\n\t\t}\n\n\t\tfor _, alias := range names {\n\t\t\tres, _ := ResolveName(alias)\n\t\t\turequire.NotEqual(t, nil, res)\n\n\t\t\tuassert.Equal(t, aliceAddr, res.Addr())\n\t\t\tuassert.Equal(t, \"alice4\", res.Name())\n\t\t}\n\t})\n}\n\nfunc TestResolveAddress(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(initControllerPath))\n\n\tt.Run(\"single_name\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\n\t\tres := ResolveAddress(aliceAddr)\n\n\t\tuassert.Equal(t, aliceAddr, res.Addr())\n\t\tuassert.Equal(t, alice, res.Name())\n\t})\n\n\tt.Run(\"name+Alias\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\t\tdata, _ := ResolveName(alice)\n\t\turequire.NoError(t, data.UpdateName(0, cur, \"alice1\"))\n\n\t\tres := ResolveAddress(aliceAddr)\n\t\turequire.NotEqual(t, nil, res)\n\n\t\tuassert.Equal(t, aliceAddr, res.Addr())\n\t\tuassert.Equal(t, \"alice1\", res.Name())\n\t})\n\n\tt.Run(\"multiple_aliases\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\n\t\t// RegisterUser and check each Alias\n\t\tvar names []string\n\t\tnames = append(names, alice)\n\n\t\tfor i := 0; i \u003c 5; i++ {\n\t\t\talias := \"alice\" + strconv.Itoa(i)\n\t\t\tnames = append(names, alias)\n\t\t\tdata, _ := ResolveName(alice)\n\t\t\turequire.NoError(t, data.UpdateName(0, cur, alias))\n\t\t}\n\n\t\tres := ResolveAddress(aliceAddr)\n\t\tuassert.Equal(t, aliceAddr, res.Addr())\n\t\tuassert.Equal(t, \"alice4\", res.Name())\n\t})\n}\n\nfunc TestROStores(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(initControllerPath))\n\tcleanStore(t)\n\n\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\troNS := GetReadOnlyNameStore()\n\troAS := GetReadonlyAddrStore()\n\n\tt.Run(\"get user data\", func(t *testing.T) {\n\t\t// Name store\n\t\taliceDataRaw := roNS.Get(alice)\n\t\turequire.NotNil(t, aliceDataRaw)\n\n\t\troData, ok := aliceDataRaw.(*UserData)\n\t\tuassert.True(t, ok, \"Could not cast data from RO tree to UserData\")\n\n\t\t// Try to modify data\n\t\troData.Delete(0, cur)\n\t\traw := nameStore.Get(alice)\n\t\tuassert.False(t, raw.(*UserData).deleted)\n\n\t\t// Addr store\n\t\taliceDataRaw = roAS.Get(aliceAddr.String())\n\t\turequire.NotNil(t, aliceDataRaw)\n\n\t\troData, ok = aliceDataRaw.(*UserData)\n\t\tuassert.True(t, ok, \"Could not cast data from RO tree to UserData\")\n\n\t\t// Try to modify data\n\t\troData.Delete(0, cur)\n\t\traw = nameStore.Get(alice)\n\t\tuassert.False(t, raw.(*UserData).deleted)\n\t})\n\n\tt.Run(\"get deleted data\", func(t *testing.T) {\n\t\traw := nameStore.Get(alice)\n\t\taliceData := raw.(*UserData)\n\n\t\turequire.NoError(t, aliceData.Delete(0, cur))\n\t\turequire.True(t, aliceData.IsDeleted())\n\n\t\t// Should be nil because of makeSafeFn intercepting the value.\n\t\trawRoData := roNS.Get(alice)\n\t\tuassert.Equal(t, rawRoData, nil)\n\t\t_, ok := rawRoData.(*UserData) // shouldn't be castable\n\t\tuassert.False(t, ok)\n\t})\n}\n\nfunc TestResolveAny(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(initControllerPath))\n\n\tt.Run(\"name\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\n\t\tres, _ := ResolveAny(alice)\n\n\t\tuassert.Equal(t, aliceAddr, res.Addr())\n\t\tuassert.Equal(t, alice, res.Name())\n\t})\n\n\tt.Run(\"address\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))\n\n\t\tres, _ := ResolveAny(aliceAddr.String())\n\n\t\tuassert.Equal(t, aliceAddr, res.Addr())\n\t\tuassert.Equal(t, alice, res.Name())\n\t})\n\n\tt.Run(\"not_registered\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\tres, _ := ResolveAny(aliceAddr.String())\n\n\t\tuassert.Equal(t, nil, res)\n\t})\n}\n\nfunc TestProposeErrors(cur realm, t *testing.T) {\n\tt.Run(\"propose_register_user_errors\", func(t *testing.T) {\n\t\turequire.PanicsWithMessage(t, cur, ErrInvalidUsername.Error(), func() {\n\t\t\tProposeRegisterUser(cur, \"bad name\", aliceAddr)\n\t\t})\n\t\turequire.PanicsWithMessage(t, cur, ErrInvalidAddress.Error(), func() {\n\t\t\tProposeRegisterUser(cur, alice, \"badaddress\")\n\t\t})\n\t})\n\n\tt.Run(\"propose_update_name_errors\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.PanicsWithMessage(t, cur, ErrInvalidAddress.Error(), func() {\n\t\t\tProposeUpdateName(cur, \"badaddress\", \"alice1\")\n\t\t})\n\t\turequire.PanicsWithMessage(t, cur, ErrInvalidUsername.Error(), func() {\n\t\t\tProposeUpdateName(cur, aliceAddr, \"bad name\")\n\t\t})\n\t\t// Note: unregistered user is not checked at proposal creation time.\n\t\t// The callback handles it at execution time.\n\t})\n\n\tt.Run(\"propose_delete_user_errors\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\turequire.PanicsWithMessage(t, cur, ErrInvalidAddress.Error(), func() {\n\t\t\tProposeDeleteUser(cur, \"badaddress\")\n\t\t})\n\t\t// Note: unregistered user is not checked at proposal creation time.\n\t\t// The callback handles it at execution time.\n\t})\n}\n\n// Audit finding #6: ProposeControllerAdditionAndRemoval used to return early\n// from its callback when toAdd was already whitelisted (addToWhitelist\n// returned ErrAlreadyWhitelisted), skipping the remove step entirely. A\n// passed swap proposal would silently leave the old controller active.\n//\n// applyControllerSwap is the extracted callback body. These tests exercise\n// it directly to confirm:\n//   - normal swap (toAdd new, toRemove present) succeeds and updates state\n//   - toAdd already present is benign — remove still happens\n//   - toRemove already absent is benign — add still happens, no error\n//   - errors that aren't the idempotency cases still propagate\nfunc TestApplyControllerSwap(t *testing.T) {\n\t// Use unique addresses per subtest to avoid having to drain the\n\t// controllers set (addrset.Set has no clear/iterate-all method, and\n\t// state persists across subtests in this package's tests).\n\tt.Run(\"normal swap A-\u003eB\", func(t *testing.T) {\n\t\ta := testutils.TestAddress(\"swapA1\")\n\t\tb := testutils.TestAddress(\"swapB1\")\n\t\tcontrollers.Add(a)\n\t\tdefer controllers.Remove(b)\n\n\t\tuassert.NoError(t, applyControllerSwap(b, a))\n\t\tuassert.True(t, controllers.Has(b), \"b should be whitelisted\")\n\t\tuassert.False(t, controllers.Has(a), \"a should be removed\")\n\t})\n\n\tt.Run(\"toAdd already whitelisted, toRemove present\", func(t *testing.T) {\n\t\t// Regression for audit finding #6. Before the fix, this returned\n\t\t// ErrAlreadyWhitelisted from the swap callback, skipping the remove\n\t\t// step entirely — the swap silently no-op'd and the old controller\n\t\t// stayed active.\n\t\ta := testutils.TestAddress(\"swapA2\")\n\t\tb := testutils.TestAddress(\"swapB2\")\n\t\tcontrollers.Add(a)\n\t\tcontrollers.Add(b)\n\t\tdefer controllers.Remove(b)\n\n\t\tuassert.NoError(t, applyControllerSwap(b, a))\n\t\tuassert.True(t, controllers.Has(b), \"b should remain whitelisted\")\n\t\tuassert.False(t, controllers.Has(a), \"a should be removed even though b was already in\")\n\t})\n\n\tt.Run(\"toRemove already absent, toAdd new\", func(t *testing.T) {\n\t\ta := testutils.TestAddress(\"swapA3\")\n\t\tb := testutils.TestAddress(\"swapB3\")\n\t\tc := testutils.TestAddress(\"swapC3\") // never added\n\t\tcontrollers.Add(a)\n\t\tdefer controllers.Remove(a)\n\t\tdefer controllers.Remove(b)\n\n\t\t// Remove c which isn't in the set; should be benign.\n\t\tuassert.NoError(t, applyControllerSwap(b, c))\n\t\tuassert.True(t, controllers.Has(b), \"b should be whitelisted\")\n\t\tuassert.True(t, controllers.Has(a), \"a should still be whitelisted (unchanged)\")\n\t\tuassert.False(t, controllers.Has(c), \"c was never in the set\")\n\t})\n\n\tt.Run(\"both idempotency cases at once\", func(t *testing.T) {\n\t\t// toAdd already in, toRemove already out — should succeed cleanly,\n\t\t// no state change.\n\t\ta := testutils.TestAddress(\"swapA4\")\n\t\tb := testutils.TestAddress(\"swapB4\")\n\t\tc := testutils.TestAddress(\"swapC4\")\n\t\tcontrollers.Add(a)\n\t\tcontrollers.Add(b)\n\t\tdefer controllers.Remove(a)\n\t\tdefer controllers.Remove(b)\n\n\t\tuassert.NoError(t, applyControllerSwap(b, c))\n\t\tuassert.True(t, controllers.Has(a))\n\t\tuassert.True(t, controllers.Has(b))\n\t\tuassert.False(t, controllers.Has(c))\n\t})\n}\n\n// Audit finding #20: the controller whitelist must be queryable from\n// outside the package so operators can monitor authority without\n// source-diving or replaying governance proposals.\nfunc TestControllerQueries(t *testing.T) {\n\tt.Run(\"IsController reflects whitelist state\", func(t *testing.T) {\n\t\ta := testutils.TestAddress(\"queryA1\")\n\t\tb := testutils.TestAddress(\"queryB1\")\n\n\t\t// Before any add: both report false.\n\t\tuassert.False(t, IsController(a))\n\t\tuassert.False(t, IsController(b))\n\n\t\tcontrollers.Add(a)\n\t\tdefer controllers.Remove(a)\n\n\t\tuassert.True(t, IsController(a))\n\t\tuassert.False(t, IsController(b))\n\t})\n\n\tt.Run(\"Controllers returns a snapshot of current whitelist\", func(t *testing.T) {\n\t\t// Use distinct addresses that aren't already in the set from\n\t\t// other tests in this file.\n\t\ta := testutils.TestAddress(\"queryA2\")\n\t\tb := testutils.TestAddress(\"queryB2\")\n\t\tc := testutils.TestAddress(\"queryC2\")\n\n\t\tcontrollers.Add(a)\n\t\tcontrollers.Add(b)\n\t\tcontrollers.Add(c)\n\t\tdefer controllers.Remove(a)\n\t\tdefer controllers.Remove(b)\n\t\tdefer controllers.Remove(c)\n\n\t\tgot := Controllers()\n\n\t\t// All three must appear (regardless of order vs other tests'\n\t\t// leftover entries — we only assert ours are present).\n\t\tseen := map[string]bool{}\n\t\tfor _, e := range got {\n\t\t\tseen[e.String()] = true\n\t\t}\n\t\tuassert.True(t, seen[a.String()], \"snapshot must contain a\")\n\t\tuassert.True(t, seen[b.String()], \"snapshot must contain b\")\n\t\tuassert.True(t, seen[c.String()], \"snapshot must contain c\")\n\t})\n\n\tt.Run(\"Controllers returns a copy — caller mutation does not affect realm\", func(t *testing.T) {\n\t\ta := testutils.TestAddress(\"queryA3\")\n\t\tcontrollers.Add(a)\n\t\tdefer controllers.Remove(a)\n\n\t\tgot := Controllers()\n\t\t// Mutate the returned slice. The realm's controllers set must not\n\t\t// be affected.\n\t\tgot = got[:0]\n\n\t\tuassert.True(t, controllers.Has(a), \"realm state must be unaffected by caller-side slice mutation\")\n\t\tuassert.True(t, IsController(a))\n\t})\n}\n\n// ProposeRegisterUser auto-injects a CANONICAL COLLISION warning into\n// the proposal description when the proposed name canonical-collides\n// with an existing registration. The warning surfaces the colliding\n// existing name to voters; the proposal still goes through if voted in\n// (decision #3, DAO grants always bypass).\nfunc TestProposeRegisterUser_CollisionWarning(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(initControllerPath))\n\n\tt.Run(\"warning_injected_on_collision\", func(t *testing.T) {\n\t\tcleanStore(t)\n\t\turequire.NoError(t, RegisterUser(cross(cur), \"vitalik\", aliceAddr))\n\n\t\treq := ProposeRegisterUser(cur, \"vital1k\", bobAddr)\n\t\tuassert.True(t,\n\t\t\tstrings.Contains(req.Description(), \"CANONICAL COLLISION\"),\n\t\t\t\"description must include collision warning\")\n\t\tuassert.True(t,\n\t\t\tstrings.Contains(req.Description(), \"`vitalik`\"),\n\t\t\t\"description must name the existing colliding registration\")\n\t})\n\n\tt.Run(\"no_warning_when_no_collision\", func(t *testing.T) {\n\t\tcleanStore(t)\n\n\t\treq := ProposeRegisterUser(cur, \"freshname\", aliceAddr)\n\t\tuassert.False(t,\n\t\t\tstrings.Contains(req.Description(), \"CANONICAL COLLISION\"),\n\t\t\t\"description must not include collision warning when name is fresh\")\n\t})\n}\n\n// Note: full execution of ProposeRegisterUser/ProposeUpdateName closures\n// (with ignoreCanonical=true → later-wins overwrite) is exercised end-to-\n// end by the integration test in gno.land/pkg/integration/testdata/.\n// The bypass-write semantics themselves are covered here at the unit\n// level by TestRegisterUserIgnoreCanonical and TestUpdateName_CanonicalCollision.\n\n// TODO Uncomment after gnoweb /u/ page.\n//func TestUserRenderLink(cur realm, t *testing.T) {\n//\ttesting.SetOriginCaller(whitelistedCallerAddr)\n//\tcleanStore(t)\n//\n//\turequire.NoError(t, RegisterUser(alice, aliceAddr))\n//\n//\tdata, _ := ResolveName(alice)\n//\tuassert.Equal(t, data.RenderLink(\"\"), ufmt.Sprintf(\"[@%s](/u/%s)\", alice, alice))\n//\ttext := \"my link text!\"\n//\tuassert.Equal(t, data.RenderLink(text), ufmt.Sprintf(\"[%s](/u/%s)\", text, alice))\n//}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"3scBTl8HNLhCTS4ZEGX079WeqZy/hneOaaL9am6uKzgZ8fvDCUwCQgUbf2vwLNYL7wz+BL6hDSQlY1qKWbpeJA=="}],"memo":""}},{"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/v1 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/v1).\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/v1.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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"CuQu2zf/uqNbxe7AMDuoSqujbGJoNNGYgBflm+qI5vs1yh135rv4j9Jtl+v+zCxH25/iGw+Vmt+GnEZwtTEzDg=="}],"memo":""}},{"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\"\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"},{"name":"z_0_a_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_0_a\npackage z_0_a\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/r/archive/boards\"\n)\n\nvar bid boards.BoardID\n\nfunc init(cur realm) {\n\tcaller := testutils.TestAddress(\"caller\")\n\ttesting.SetRealm(testing.NewUserRealm(caller))\n\tbid = boards.CreateBoard(cross(cur), \"test_board\")\n\tboards.CreateThread(cross(cur), bid, \"First Post (title)\", \"Body of the first post. (body)\")\n\tpid := boards.CreateThread(cross(cur), bid, \"Second Post (title)\", \"Body of the second post. (body)\")\n\tboards.CreateReply(cross(cur), bid, pid, pid, \"Reply of the second post\")\n}\n\nfunc main() {\n\tprintln(boards.Render(\"test_board\"))\n}\n\n// Error:\n// unauthorized\n"},{"name":"z_0_c_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_0_c\npackage z_0_c\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar bid boards.BoardID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\tboards.CreateThread(cross(cur), 1, \"First Post (title)\", \"Body of the first post. (body)\")\n}\n\nfunc main() {\n\tprintln(boards.Render(\"test_board\"))\n}\n\n// Error:\n// board not exist\n"},{"name":"z_0_d_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_0_d\npackage z_0_d\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar bid boards.BoardID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\tbid = boards.CreateBoard(cross(cur), \"test_board\")\n\tboards.CreateReply(cross(cur), bid, 0, 0, \"Reply of the second post\")\n}\n\nfunc main() {\n\tprintln(boards.Render(\"test_board\"))\n}\n\n// Error:\n// thread not exist\n"},{"name":"z_0_e_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_0_e\npackage z_0_e\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar bid boards.BoardID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\tboards.CreateReply(cross(cur), bid, 0, 0, \"Reply of the second post\")\n}\n\nfunc main() {\n\tprintln(boards.Render(\"test_board\"))\n}\n\n// Error:\n// board not exist\n"},{"name":"z_0_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_0_filetest\n\npackage z_0_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar bid boards.BoardID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tbid = boards.CreateBoard(cross(cur), \"test_board\")\n\tboards.CreateThread(cross(cur), bid, \"First Post (title)\", \"Body of the first post. (body)\")\n\tpid := boards.CreateThread(cross(cur), bid, \"Second Post (title)\", \"Body of the second post. (body)\")\n\tboards.CreateReply(cross(cur), bid, pid, pid, \"Reply of the second post\")\n}\n\nfunc main() {\n\tprintln(boards.Render(\"test_board\"))\n}\n\n// Output:\n// \\[[post](/r/archive/boards$help\u0026func=CreateThread\u0026bid=1)]\n//\n// ----------------------------------------\n// ## [First Post (title)](/r/archive/boards:test_board/1)\n//\n// Body of the first post. (body)\n// \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm UTC](/r/archive/boards:test_board/1) \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=1\u0026threadid=1)] (0 replies) (0 reposts)\n//\n// ----------------------------------------\n// ## [Second Post (title)](/r/archive/boards:test_board/2)\n//\n// Body of the second post. (body)\n// \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm UTC](/r/archive/boards:test_board/2) \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=2\u0026threadid=2)] (1 replies) (0 reposts)\n//\n//\n"},{"name":"z_10_a_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_10_a_filetest\n\npackage z_10_a_filetest\n\n// SEND: 1000000ugnot\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar (\n\tbid boards.BoardID\n\tpid boards.PostID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tbid = boards.CreateBoard(cross(cur), \"test_board\")\n\tpid = boards.CreateThread(cross(cur), bid, \"First Post in (title)\", \"Body of the first post. (body)\")\n}\n\nfunc main(cur realm) {\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n\t// boardId 2 not exist\n\tboards.DeletePost(cross(cur), 2, pid, pid, \"\")\n\tprintln(\"----------------------------------------------------\")\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n}\n\n// Error:\n// invalid non-user call\n"},{"name":"z_10_b_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_10_b_filetest\n\npackage z_10_b_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar (\n\tbid boards.BoardID\n\tpid boards.PostID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tbid = boards.CreateBoard(cross(cur), \"test_board\")\n\tpid = boards.CreateThread(cross(cur), bid, \"First Post in (title)\", \"Body of the first post. (body)\")\n}\n\nfunc main(cur realm) {\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n\t// pid of 2 not exist\n\tboards.DeletePost(cross(cur), bid, 2, 2, \"\")\n\tprintln(\"----------------------------------------------------\")\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n}\n\n// Error:\n// invalid non-user call\n"},{"name":"z_10_c_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_10_c_filetest\n\npackage z_10_c_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar (\n\tbid boards.BoardID\n\tpid boards.PostID\n\trid boards.PostID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tbid = boards.CreateBoard(cross(cur), \"test_board\")\n\tpid = boards.CreateThread(cross(cur), bid, \"First Post in (title)\", \"Body of the first post. (body)\")\n\trid = boards.CreateReply(cross(cur), bid, pid, pid, \"First reply of the First post\\n\")\n}\n\nfunc main(cur realm) {\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\")))\n\tboards.DeletePost(cross(cur), bid, pid, rid, \"\")\n\tprintln(\"----------------------------------------------------\")\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n}\n\n// Output:\n// # First Post in (title)\n//\n// Body of the first post. (body)\n// \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/1) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=1\u0026threadid=1)] \\[[repost](/r/archive/boards$help\u0026func=CreateRepost\u0026bid=1\u0026postid=1)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=1\u0026threadid=1)]\n//\n// \u003e First reply of the First post\n// \u003e\n// \u003e \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/1/2) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=2\u0026threadid=1)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=2\u0026threadid=1)]\n//\n// ----------------------------------------------------\n// # First Post in (title)\n//\n// Body of the first post. (body)\n// \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/1) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=1\u0026threadid=1)] \\[[repost](/r/archive/boards$help\u0026func=CreateRepost\u0026bid=1\u0026postid=1)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=1\u0026threadid=1)]\n//\n"},{"name":"z_10_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_10_filetest\n\npackage z_10_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar (\n\tbid boards.BoardID\n\tpid boards.PostID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tbid = boards.CreateBoard(cross(cur), \"test_board\")\n\tpid = boards.CreateThread(cross(cur), bid, \"First Post in (title)\", \"Body of the first post. (body)\")\n}\n\nfunc main(cur realm) {\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\")))\n\tboards.DeletePost(cross(cur), bid, pid, pid, \"\")\n\tprintln(\"----------------------------------------------------\")\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n}\n\n// Output:\n// # First Post in (title)\n//\n// Body of the first post. (body)\n// \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/1) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=1\u0026threadid=1)] \\[[repost](/r/archive/boards$help\u0026func=CreateRepost\u0026bid=1\u0026postid=1)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=1\u0026threadid=1)]\n//\n// ----------------------------------------------------\n// thread does not exist with id: 1\n"},{"name":"z_11_a_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_11_a_filetest\n\npackage z_11_a_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar (\n\tbid boards.BoardID\n\tpid boards.PostID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tbid = boards.CreateBoard(cross(cur), \"test_board\")\n\tpid = boards.CreateThread(cross(cur), bid, \"First Post in (title)\", \"Body of the first post. (body)\")\n}\n\nfunc main(cur realm) {\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n\t// board 2 not exist\n\tboards.EditPost(cross(cur), 2, pid, pid, \"Edited: First Post in (title)\", \"Edited: Body of the first post. (body)\")\n\tprintln(\"----------------------------------------------------\")\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n}\n\n// Error:\n// invalid non-user call\n"},{"name":"z_11_b_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_11_b_filetest\n\npackage z_11_b_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar (\n\tbid boards.BoardID\n\tpid boards.PostID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tbid = boards.CreateBoard(cross(cur), \"test_board\")\n\tpid = boards.CreateThread(cross(cur), bid, \"First Post in (title)\", \"Body of the first post. (body)\")\n}\n\nfunc main(cur realm) {\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n\t// thread 2 not exist\n\tboards.EditPost(cross(cur), bid, 2, pid, \"Edited: First Post in (title)\", \"Edited: Body of the first post. (body)\")\n\tprintln(\"----------------------------------------------------\")\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n}\n\n// Error:\n// invalid non-user call\n"},{"name":"z_11_c_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_11_c_filetest\n\npackage z_11_c_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar (\n\tbid boards.BoardID\n\tpid boards.PostID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tbid = boards.CreateBoard(cross(cur), \"test_board\")\n\tpid = boards.CreateThread(cross(cur), bid, \"First Post in (title)\", \"Body of the first post. (body)\")\n}\n\nfunc main(cur realm) {\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n\t// post 2 not exist\n\tboards.EditPost(cross(cur), bid, pid, 2, \"Edited: First Post in (title)\", \"Edited: Body of the first post. (body)\")\n\tprintln(\"----------------------------------------------------\")\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n}\n\n// Error:\n// invalid non-user call\n"},{"name":"z_11_d_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_11_d_filetest\n\npackage z_11_d_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar (\n\tbid boards.BoardID\n\tpid boards.PostID\n\trid boards.PostID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tbid = boards.CreateBoard(cross(cur), \"test_board\")\n\tpid = boards.CreateThread(cross(cur), bid, \"First Post in (title)\", \"Body of the first post. (body)\")\n\trid = boards.CreateReply(cross(cur), bid, pid, pid, \"First reply of the First post\\n\")\n}\n\nfunc main(cur realm) {\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\")))\n\tboards.EditPost(cross(cur), bid, pid, rid, \"\", \"Edited: First reply of the First post\\n\")\n\tprintln(\"----------------------------------------------------\")\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n}\n\n// Output:\n// # First Post in (title)\n//\n// Body of the first post. (body)\n// \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/1) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=1\u0026threadid=1)] \\[[repost](/r/archive/boards$help\u0026func=CreateRepost\u0026bid=1\u0026postid=1)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=1\u0026threadid=1)]\n//\n// \u003e First reply of the First post\n// \u003e\n// \u003e \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/1/2) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=2\u0026threadid=1)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=2\u0026threadid=1)]\n//\n// ----------------------------------------------------\n// # First Post in (title)\n//\n// Body of the first post. (body)\n// \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/1) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=1\u0026threadid=1)] \\[[repost](/r/archive/boards$help\u0026func=CreateRepost\u0026bid=1\u0026postid=1)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=1\u0026threadid=1)]\n//\n// \u003e Edited: First reply of the First post\n// \u003e\n// \u003e \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/1/2) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=2\u0026threadid=1)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=2\u0026threadid=1)]\n//\n"},{"name":"z_11_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_11_filetest\n\npackage z_11_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar (\n\tbid boards.BoardID\n\tpid boards.PostID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tbid = boards.CreateBoard(cross(cur), \"test_board\")\n\tpid = boards.CreateThread(cross(cur), bid, \"First Post in (title)\", \"Body of the first post. (body)\")\n}\n\nfunc main(cur realm) {\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\")))\n\tboards.EditPost(cross(cur), bid, pid, pid, \"Edited: First Post in (title)\", \"Edited: Body of the first post. (body)\")\n\tprintln(\"----------------------------------------------------\")\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n}\n\n// Output:\n// # First Post in (title)\n//\n// Body of the first post. (body)\n// \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/1) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=1\u0026threadid=1)] \\[[repost](/r/archive/boards$help\u0026func=CreateRepost\u0026bid=1\u0026postid=1)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=1\u0026threadid=1)]\n//\n// ----------------------------------------------------\n// # Edited: First Post in (title)\n//\n// Edited: Body of the first post. (body)\n// \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/1) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=1\u0026threadid=1)] \\[[repost](/r/archive/boards$help\u0026func=CreateRepost\u0026bid=1\u0026postid=1)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=1\u0026threadid=1)]\n//\n"},{"name":"z_12_a_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_12_a_filetest\n\npackage z_12_a_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\t// create a post via registered user\n\tbid1 := boards.CreateBoard(cross(cur), \"test_board1\")\n\tpid := boards.CreateThread(cross(cur), bid1, \"First Post (title)\", \"Body of the first post. (body)\")\n\tbid2 := boards.CreateBoard(cross(cur), \"test_board2\")\n\n\t// create a repost via anon user\n\ttest2 := testutils.TestAddress(\"test2\")\n\ttesting.SetOriginCaller(test2)\n\ttesting.SetOriginSend(chain.Coins{{\"ugnot\", 9000000}})\n\n\trid := boards.CreateRepost(cross(cur), bid1, pid, \"\", \"Check this out\", bid2)\n\tprintln(rid)\n\tprintln(boards.Render(\"test_board1\"))\n}\n\n// Error:\n// please register, otherwise minimum fee 100000000 is required if anonymous\n"},{"name":"z_12_b_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_12_b_filetest\n\npackage z_12_b_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\tbid1 := boards.CreateBoard(cross(cur), \"test_board1\")\n\tpid := boards.CreateThread(cross(cur), bid1, \"First Post (title)\", \"Body of the first post. (body)\")\n\tbid2 := boards.CreateBoard(cross(cur), \"test_board2\")\n\n\t// create a repost to a non-existing board\n\trid := boards.CreateRepost(cross(cur), 5, pid, \"\", \"Check this out\", bid2)\n\tprintln(rid)\n\tprintln(boards.Render(\"test_board1\"))\n}\n\n// Error:\n// src board not exist\n"},{"name":"z_12_c_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_12_c_filetest\n\npackage z_12_c_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\tbid1 := boards.CreateBoard(cross(cur), \"test_board1\")\n\tboards.CreateThread(cross(cur), bid1, \"First Post (title)\", \"Body of the first post. (body)\")\n\tbid2 := boards.CreateBoard(cross(cur), \"test_board2\")\n\n\t// create a repost to a non-existing thread\n\trid := boards.CreateRepost(cross(cur), bid1, 5, \"\", \"Check this out\", bid2)\n\tprintln(rid)\n\tprintln(boards.Render(\"test_board1\"))\n}\n\n// Error:\n// thread not exist\n"},{"name":"z_12_d_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_12_d_filetest\n\npackage z_12_d_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\tbid1 := boards.CreateBoard(cross(cur), \"test_board1\")\n\tpid := boards.CreateThread(cross(cur), bid1, \"First Post (title)\", \"Body of the first post. (body)\")\n\tboards.CreateBoard(cross(cur), \"test_board2\")\n\n\t// create a repost to a non-existing destination board\n\trid := boards.CreateRepost(cross(cur), bid1, pid, \"\", \"Check this out\", 5)\n\tprintln(rid)\n\tprintln(boards.Render(\"test_board1\"))\n}\n\n// Error:\n// dst board not exist\n"},{"name":"z_12_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_12_filetest\n\npackage z_12_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar (\n\tbid1 boards.BoardID\n\tbid2 boards.BoardID\n\tpid  boards.PostID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tbid1 = boards.CreateBoard(cross(cur), \"test_board1\")\n\tpid = boards.CreateThread(cross(cur), bid1, \"First Post (title)\", \"Body of the first post. (body)\")\n\tbid2 = boards.CreateBoard(cross(cur), \"test_board2\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\")))\n\trid := boards.CreateRepost(cross(cur), bid1, pid, \"\", \"Check this out\", bid2)\n\tprintln(rid)\n\tprintln(boards.Render(\"test_board2\"))\n}\n\n// Output:\n// 1\n// \\[[post](/r/archive/boards$help\u0026func=CreateThread\u0026bid=2)]\n//\n// ----------------------------------------\n// Repost: Check this out\n// ## [First Post (title)](/r/archive/boards:test_board1/1)\n//\n// Body of the first post. (body)\n// \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm UTC](/r/archive/boards:test_board1/1) \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=1\u0026threadid=1)] (0 replies) (1 reposts)\n//\n//\n"},{"name":"z_1_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_1_filetest\n\npackage z_1_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar board *boards.Board\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\t_ = boards.CreateBoard(cross(cur), \"test_board_1\")\n\t_ = boards.CreateBoard(cross(cur), \"test_board_2\")\n}\n\nfunc main() {\n\tprintln(boards.Render(\"\"))\n}\n\n// Output:\n// These are all the boards of this realm:\n//\n//  * [/r/archive/boards:test_board_1](/r/archive/boards:test_board_1)\n//  * [/r/archive/boards:test_board_2](/r/archive/boards:test_board_2)\n//\n"},{"name":"z_2_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_2_filetest\n\npackage z_2_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar (\n\tbid boards.BoardID\n\tpid boards.PostID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tbid = boards.CreateBoard(cross(cur), \"test_board\")\n\tboards.CreateThread(cross(cur), bid, \"First Post (title)\", \"Body of the first post. (body)\")\n\tpid = boards.CreateThread(cross(cur), bid, \"Second Post (title)\", \"Body of the second post. (body)\")\n\tboards.CreateReply(cross(cur), bid, pid, pid, \"Reply of the second post\")\n}\n\nfunc main() {\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n}\n\n// Output:\n// # Second Post (title)\n//\n// Body of the second post. (body)\n// \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/2) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=2\u0026threadid=2)] \\[[repost](/r/archive/boards$help\u0026func=CreateRepost\u0026bid=1\u0026postid=2)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=2\u0026threadid=2)]\n//\n// \u003e Reply of the second post\n// \u003e \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/2/3) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=3\u0026threadid=2)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=3\u0026threadid=2)]\n//\n"},{"name":"z_3_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_3_filetest\n\npackage z_3_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar (\n\tbid boards.BoardID\n\tpid boards.PostID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tbid = boards.CreateBoard(cross(cur), \"test_board\")\n\tboards.CreateThread(cross(cur), bid, \"First Post (title)\", \"Body of the first post. (body)\")\n\tpid = boards.CreateThread(cross(cur), bid, \"Second Post (title)\", \"Body of the second post. (body)\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\")))\n\trid := boards.CreateReply(cross(cur), bid, pid, pid, \"Reply of the second post\")\n\tprintln(rid)\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n}\n\n// Output:\n// 3\n// # Second Post (title)\n//\n// Body of the second post. (body)\n// \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/2) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=2\u0026threadid=2)] \\[[repost](/r/archive/boards$help\u0026func=CreateRepost\u0026bid=1\u0026postid=2)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=2\u0026threadid=2)]\n//\n// \u003e Reply of the second post\n// \u003e \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/2/3) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=3\u0026threadid=2)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=3\u0026threadid=2)]\n//\n"},{"name":"z_4_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_4_filetest\n\npackage z_4_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar (\n\tbid boards.BoardID\n\tpid boards.PostID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tbid = boards.CreateBoard(cross(cur), \"test_board\")\n\tboards.CreateThread(cross(cur), bid, \"First Post (title)\", \"Body of the first post. (body)\")\n\tpid = boards.CreateThread(cross(cur), bid, \"Second Post (title)\", \"Body of the second post. (body)\")\n\trid := boards.CreateReply(cross(cur), bid, pid, pid, \"Reply of the second post\")\n\tprintln(rid)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\")))\n\trid2 := boards.CreateReply(cross(cur), bid, pid, pid, \"Second reply of the second post\")\n\tprintln(rid2)\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n}\n\n// Output:\n// 3\n// 4\n// # Second Post (title)\n//\n// Body of the second post. (body)\n// \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/2) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=2\u0026threadid=2)] \\[[repost](/r/archive/boards$help\u0026func=CreateRepost\u0026bid=1\u0026postid=2)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=2\u0026threadid=2)]\n//\n// \u003e Reply of the second post\n// \u003e \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/2/3) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=3\u0026threadid=2)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=3\u0026threadid=2)]\n//\n// \u003e Second reply of the second post\n// \u003e \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/2/4) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=4\u0026threadid=2)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=4\u0026threadid=2)]\n//\n"},{"name":"z_5_b_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_5_b_filetest\n\npackage z_5_b_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"chain\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nconst admin = address(\"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\")\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\t// create board via registered user\n\tbid := boards.CreateBoard(cross(cur), \"test_board\")\n\n\t// create post via anon user\n\ttest2 := testutils.TestAddress(\"test2\")\n\ttesting.SetOriginCaller(test2)\n\ttesting.SetOriginSend(chain.Coins{{\"ugnot\", 9000000}})\n\n\tpid := boards.CreateThread(cross(cur), bid, \"First Post (title)\", \"Body of the first post. (body)\")\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n}\n\n// Error:\n// please register, otherwise minimum fee 100000000 is required if anonymous\n"},{"name":"z_5_c_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_5_c_filetest\n\npackage z_5_c_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"chain\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nconst admin = address(\"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\")\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\t// create board via registered user\n\tbid := boards.CreateBoard(cross(cur), \"test_board\")\n\n\t// create post via anon user\n\ttest2 := testutils.TestAddress(\"test2\")\n\ttesting.SetOriginCaller(test2)\n\ttesting.SetOriginSend(chain.Coins{{\"ugnot\", 101000000}})\n\n\tpid := boards.CreateThread(cross(cur), bid, \"First Post (title)\", \"Body of the first post. (body)\")\n\tboards.CreateReply(cross(cur), bid, pid, pid, \"Reply of the first post\")\n\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n}\n\n// Output:\n// # First Post (title)\n//\n// Body of the first post. (body)\n// \\- [g1w3jhxapjta047h6lta047h6lta047h6laqcyu4](/u/g1w3jhxapjta047h6lta047h6lta047h6laqcyu4), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/1) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=1\u0026threadid=1)] \\[[repost](/r/archive/boards$help\u0026func=CreateRepost\u0026bid=1\u0026postid=1)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=1\u0026threadid=1)]\n//\n// \u003e Reply of the first post\n// \u003e \\- [g1w3jhxapjta047h6lta047h6lta047h6laqcyu4](/u/g1w3jhxapjta047h6lta047h6lta047h6laqcyu4), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/1/2) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=2\u0026threadid=1)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=2\u0026threadid=1)]\n//\n"},{"name":"z_5_d_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_5_d_filetest\n\npackage z_5_d_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"chain\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nconst admin = address(\"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\")\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\t// create board via registered user\n\tbid := boards.CreateBoard(cross(cur), \"test_board\")\n\tpid := boards.CreateThread(cross(cur), bid, \"First Post (title)\", \"Body of the first post. (body)\")\n\n\t// create reply via anon user\n\ttest2 := testutils.TestAddress(\"test2\")\n\ttesting.SetOriginCaller(test2)\n\ttesting.SetOriginSend(chain.Coins{{\"ugnot\", 9000000}})\n\tboards.CreateReply(cross(cur), bid, pid, pid, \"Reply of the first post\")\n\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n}\n\n// Error:\n// please register, otherwise minimum fee 100000000 is required if anonymous\n"},{"name":"z_5_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_5_filetest\n\npackage z_5_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar (\n\tbid boards.BoardID\n\tpid boards.PostID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tbid = boards.CreateBoard(cross(cur), \"test_board\")\n\tboards.CreateThread(cross(cur), bid, \"First Post (title)\", \"Body of the first post. (body)\")\n\tpid = boards.CreateThread(cross(cur), bid, \"Second Post (title)\", \"Body of the second post. (body)\")\n\t_ = boards.CreateReply(cross(cur), bid, pid, pid, \"Reply of the second post\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\")))\n\t_ = boards.CreateReply(cross(cur), bid, pid, pid, \"Second reply of the second post\\n\")\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n}\n\n// Output:\n// # Second Post (title)\n//\n// Body of the second post. (body)\n// \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/2) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=2\u0026threadid=2)] \\[[repost](/r/archive/boards$help\u0026func=CreateRepost\u0026bid=1\u0026postid=2)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=2\u0026threadid=2)]\n//\n// \u003e Reply of the second post\n// \u003e \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/2/3) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=3\u0026threadid=2)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=3\u0026threadid=2)]\n//\n// \u003e Second reply of the second post\n// \u003e\n// \u003e \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/2/4) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=4\u0026threadid=2)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=4\u0026threadid=2)]\n//\n"},{"name":"z_6_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_6_filetest\n\npackage z_6_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar (\n\tbid boards.BoardID\n\tpid boards.PostID\n\trid boards.PostID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tbid = boards.CreateBoard(cross(cur), \"test_board\")\n\tboards.CreateThread(cross(cur), bid, \"First Post (title)\", \"Body of the first post. (body)\")\n\tpid = boards.CreateThread(cross(cur), bid, \"Second Post (title)\", \"Body of the second post. (body)\")\n\trid = boards.CreateReply(cross(cur), bid, pid, pid, \"Reply of the second post\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\")))\n\tboards.CreateReply(cross(cur), bid, pid, pid, \"Second reply of the second post\\n\")\n\tboards.CreateReply(cross(cur), bid, pid, rid, \"First reply of the first reply\\n\")\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid))))\n}\n\n// Output:\n// # Second Post (title)\n//\n// Body of the second post. (body)\n// \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/2) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=2\u0026threadid=2)] \\[[repost](/r/archive/boards$help\u0026func=CreateRepost\u0026bid=1\u0026postid=2)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=2\u0026threadid=2)]\n//\n// \u003e Reply of the second post\n// \u003e \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/2/3) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=3\u0026threadid=2)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=3\u0026threadid=2)]\n// \u003e\n// \u003e \u003e First reply of the first reply\n// \u003e \u003e\n// \u003e \u003e \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/2/5) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=5\u0026threadid=2)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=5\u0026threadid=2)]\n//\n// \u003e Second reply of the second post\n// \u003e\n// \u003e \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/2/4) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=4\u0026threadid=2)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=4\u0026threadid=2)]\n//\n"},{"name":"z_7_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_7_filetest\n\npackage z_7_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nfunc init(cur realm) {\n\t// register\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\t// create board and post\n\tbid := boards.CreateBoard(cross(cur), \"test_board\")\n\tboards.CreateThread(cross(cur), bid, \"First Post (title)\", \"Body of the first post. (body)\")\n}\n\nfunc main() {\n\tprintln(boards.Render(\"test_board\"))\n}\n\n// Output:\n// \\[[post](/r/archive/boards$help\u0026func=CreateThread\u0026bid=1)]\n//\n// ----------------------------------------\n// ## [First Post (title)](/r/archive/boards:test_board/1)\n//\n// Body of the first post. (body)\n// \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm UTC](/r/archive/boards:test_board/1) \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=1\u0026threadid=1)] (0 replies) (0 reposts)\n//\n//\n"},{"name":"z_8_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_8_filetest\n\npackage z_8_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar (\n\tbid boards.BoardID\n\tpid boards.PostID\n\trid boards.PostID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tbid = boards.CreateBoard(cross(cur), \"test_board\")\n\tboards.CreateThread(cross(cur), bid, \"First Post (title)\", \"Body of the first post. (body)\")\n\tpid = boards.CreateThread(cross(cur), bid, \"Second Post (title)\", \"Body of the second post. (body)\")\n\trid = boards.CreateReply(cross(cur), bid, pid, pid, \"Reply of the second post\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\")))\n\tboards.CreateReply(cross(cur), bid, pid, pid, \"Second reply of the second post\\n\")\n\trid2 := boards.CreateReply(cross(cur), bid, pid, rid, \"First reply of the first reply\\n\")\n\tprintln(boards.Render(\"test_board/\" + strconv.Itoa(int(pid)) + \"/\" + strconv.Itoa(int(rid2))))\n}\n\n// Output:\n// _[see thread](/r/archive/boards:test_board/2)_\n//\n// Reply of the second post\n// \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/2/3) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=3\u0026threadid=2)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=3\u0026threadid=2)]\n//\n// _[see all 1 replies](/r/archive/boards:test_board/2/3)_\n//\n// \u003e First reply of the first reply\n// \u003e\n// \u003e \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:test_board/2/5) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=1\u0026postid=5\u0026threadid=2)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=1\u0026postid=5\u0026threadid=2)]\n//\n"},{"name":"z_9_a_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_9_a_filetest\n\npackage z_9_a_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar dstBoard boards.BoardID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tdstBoard = boards.CreateBoard(cross(cur), \"dst_board\")\n}\n\nfunc main(cur realm) {\n\tboards.CreateRepost(cross(cur), 0, 0, \"First Post in (title)\", \"Body of the first post. (body)\", dstBoard)\n}\n\n// Error:\n// invalid non-user call\n"},{"name":"z_9_b_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_9_b_filetest\n\npackage z_9_b_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar (\n\tsrcBoard boards.BoardID\n\tpid      boards.PostID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tsrcBoard = boards.CreateBoard(cross(cur), \"first_board\")\n\tpid = boards.CreateThread(cross(cur), srcBoard, \"First Post in (title)\", \"Body of the first post. (body)\")\n}\n\nfunc main(cur realm) {\n\tboards.CreateRepost(cross(cur), srcBoard, pid, \"First Post in (title)\", \"Body of the first post. (body)\", 0)\n}\n\n// Error:\n// invalid non-user call\n"},{"name":"z_9_filetest.gno","body":"// PKGPATH: gno.land/r/archive/boards/filetests/z_9_filetest\n\npackage z_9_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/archive/boards\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nvar (\n\tfirstBoard  boards.BoardID\n\tsecondBoard boards.BoardID\n\tpid         boards.PostID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))) // so that CurrentRealm.Addr() matches OrigCaller\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnouser123\", address(\"g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\"))\n\ttesting.SetHeight(123)\n\n\tfirstBoard = boards.CreateBoard(cross(cur), \"first_board\")\n\tsecondBoard = boards.CreateBoard(cross(cur), \"second_board\")\n\tpid = boards.CreateThread(cross(cur), firstBoard, \"First Post in (title)\", \"Body of the first post. (body)\")\n\n\tboards.CreateRepost(cross(cur), firstBoard, pid, \"First Post in (title)\", \"Body of the first post. (body)\", secondBoard)\n}\n\nfunc main() {\n\tprintln(boards.Render(\"second_board/\" + strconv.Itoa(int(pid))))\n}\n\n// Output:\n// # First Post in (title)\n//\n// Body of the first post. (body)\n// \\- [@gnouser123](/u/gnouser123), [2009-02-13 11:31pm (UTC)](/r/archive/boards:second_board/1/1) \\[[reply](/r/archive/boards$help\u0026func=CreateReply\u0026bid=2\u0026postid=1\u0026threadid=1)] \\[[x](/r/archive/boards$help\u0026func=DeletePost\u0026bid=2\u0026postid=1\u0026threadid=1)]\n//\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"ZFlYBP4vYoCBvL7wC7mFQiH3NkE3sFzAkeXQFG3f7M5QmqyaBZlgAvCBi5lGepD0FH8x1ZLYEV/panuDhirsfA=="}],"memo":""}},{"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":"echo_test.gno","body":"package echo\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc Test(t *testing.T) {\n\turequire.Equal(t, \"aa\", Render(\"aa\"))\n\turequire.Equal(t, \"\", Render(\"\"))\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/archive/echo\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"BZW6gJ+35S1VFxE+Cax9DDEK+50UZEJIPm8goCP/ECMM/OFv+kFZ+a/Na7ONLUA5WXvgtYzBnsnRFqll4kS2ew=="}],"memo":""}},{"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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"kM+VF6f3ZP3JihYPYwmFpy55ZLdITTS50rEg7G3Qcf81/AKBhxHlTIOHjZMrga6egp/vO0lja5P1QbnDHbCDKQ=="}],"memo":""}},{"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":"counter_test.gno","body":"package counter\n\nimport \"testing\"\n\nfunc TestIncrement(cur realm, t *testing.T) {\n\tcounter = 0\n\tval := Increment(cross(cur))\n\tif val != 1 {\n\t\tt.Fatalf(\"result from Increment(): %d != 1\", val)\n\t}\n\tif counter != val {\n\t\tt.Fatalf(\"counter (%d) != val (%d)\", counter, val)\n\t}\n}\n\nfunc TestRender(t *testing.T) {\n\tcounter = 1337\n\tres := Render(\"\")\n\tif res != \"1337\" {\n\t\tt.Fatalf(\"render result %q != %q\", res, \"1337\")\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/demo/counter\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"+CUQ7AMdnQvUQ5jMo8XlV8FwUDiBC2auonQY/KXpim8XBWykIim7QAAEJGCJE+PNlGkYWRrFTmH16q3TN5MjSw=="}],"memo":""}},{"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/demo/tokens/grc20\"\n\t\"gno.land/r/demo/defi/grc20reg\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"TnSfLqoYGPPARH5NIF5aB5W/cNI8c/YpnszYg03Vtt8YAsrXGDI4s1XiC4RTa8CqIS+JFHKBsxnCJD9751NkSw=="}],"memo":""}},{"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/demo/tokens/grc20\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/r/demo/defi/grc20reg\"\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/demo/defi/grc20reg 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":"atomicswap_test.gno","body":"package atomicswap\n\nimport (\n\t\"chain\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"testing\"\n\t\"time\"\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\t\"gno.land/r/tests/vm/test20\"\n)\n\nfunc TestNewCustomCoinSwap_Claim(cur realm, t *testing.T) {\n\tdefer resetTestState()\n\n\t// Setup\n\tpkgAddr := chain.PackageAddress(\"gno.land/r/demo/defi/atomicswap\")\n\tsender := testutils.TestAddress(\"sender1\")\n\trecipient := testutils.TestAddress(\"recipient1\")\n\tamount := chain.Coins{{Denom: \"ugnot\", Amount: 1}}\n\thashlock := sha256.Sum256([]byte(\"secret\"))\n\thashlockHex := hex.EncodeToString(hashlock[:])\n\ttimelock := time.Now().Add(1 * time.Hour)\n\ttesting.IssueCoins(pkgAddr, chain.Coins{{\"ugnot\", 100000000}})\n\n\t// Create a new swap\n\ttesting.SetRealm(testing.NewUserRealm(sender))\n\ttesting.SetOriginSend(amount)\n\tid, swap := NewCustomCoinSwap(cross(cur), recipient, hashlockHex, timelock)\n\tuassert.Equal(t, 1, id)\n\n\texpected := `- status: active\n- sender: g1wdjkuer9wgc47h6lta047h6lta047h6l56jtjc\n- recipient: g1wfjkx6tsd9jkuap3ta047h6lta047h6lkk20gv\n- amount: 1ugnot\n- hashlock: 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b\n- timelock: 2009-02-14T00:31:30Z\n- remaining: 1h0m0s`\n\tuassert.Equal(t, expected, swap.String())\n\tuassert.Equal(t, expected, Render(\"1\"))\n\n\t// Test initial state\n\tuassert.Equal(t, sender, swap.sender, \"expected sender to match\")\n\tuassert.Equal(t, recipient, swap.recipient, \"expected recipient to match\")\n\tuassert.Equal(t, swap.amountStr, amount.String(), \"expected amount to match\")\n\tuassert.Equal(t, hashlockHex, swap.hashlock, \"expected hashlock to match\")\n\tuassert.True(t, swap.timelock.Equal(timelock), \"expected timelock to match\")\n\tuassert.False(t, swap.claimed, \"expected claimed to be false\")\n\tuassert.False(t, swap.refunded, \"expected refunded to be false\")\n\n\t// Test claim — recipient calls via the public wrapper.\n\ttesting.SetRealm(testing.NewUserRealm(recipient))\n\tuassert.AbortsWithMessage(t, cur, \"invalid preimage\", func() { Claim(cross(cur), id, \"invalid\") })\n\tClaim(cross(cur), id, \"secret\")\n\tuassert.True(t, swap.claimed, \"expected claimed to be true\")\n\n\t// Test refund (should fail because already claimed)\n\tuassert.AbortsWithMessage(t, cur, \"already claimed\", func() { Refund(cross(cur), id) })\n\tuassert.AbortsWithMessage(t, cur, \"already claimed\", func() { Claim(cross(cur), id, \"secret\") })\n\n\texpected = `- status: claimed\n- sender: g1wdjkuer9wgc47h6lta047h6lta047h6l56jtjc\n- recipient: g1wfjkx6tsd9jkuap3ta047h6lta047h6lkk20gv\n- amount: 1ugnot\n- hashlock: 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b\n- timelock: 2009-02-14T00:31:30Z\n- remaining: 1h0m0s`\n\tuassert.Equal(t, expected, swap.String())\n\tuassert.Equal(t, expected, Render(\"1\"))\n}\n\nfunc TestNewCustomCoinSwap_Refund(cur realm, t *testing.T) {\n\tdefer resetTestState()\n\n\t// Setup\n\tpkgAddr := chain.PackageAddress(\"gno.land/r/demo/defi/atomicswap\")\n\tsender := testutils.TestAddress(\"sender2\")\n\trecipient := testutils.TestAddress(\"recipient2\")\n\tamount := chain.Coins{{Denom: \"ugnot\", Amount: 1}}\n\thashlock := sha256.Sum256([]byte(\"secret\"))\n\thashlockHex := hex.EncodeToString(hashlock[:])\n\ttimelock := time.Now().Add(1 * time.Hour)\n\n\t// Create a new swap\n\ttesting.SetRealm(testing.NewUserRealm(sender))\n\ttesting.SetOriginSend(amount)\n\tid, swap := NewCustomCoinSwap(cross(cur), recipient, hashlockHex, timelock)\n\tuassert.Equal(t, 1, id)\n\n\texpected := `- status: active\n- sender: g1wdjkuer9wge97h6lta047h6lta047h6ltfacad\n- recipient: g1wfjkx6tsd9jkuapjta047h6lta047h6lducc3v\n- amount: 1ugnot\n- hashlock: 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b\n- timelock: 2009-02-14T00:31:30Z\n- remaining: 1h0m0s`\n\tuassert.Equal(t, expected, swap.String())\n\tuassert.Equal(t, expected, Render(\"1\"))\n\n\t// Test Refund — sender calls via the public wrapper.\n\ttesting.IssueCoins(pkgAddr, chain.Coins{{\"ugnot\", 100000000}})\n\tuassert.AbortsWithMessage(t, cur, \"timelock not expired\", func() { Refund(cross(cur), id) })\n\tswap.timelock = time.Now().Add(-1 * time.Hour) // override timelock\n\tRefund(cross(cur), id)\n\tuassert.True(t, swap.refunded, \"expected refunded to be true\")\n\n\texpected = `- status: refunded\n- sender: g1wdjkuer9wge97h6lta047h6lta047h6ltfacad\n- recipient: g1wfjkx6tsd9jkuapjta047h6lta047h6lducc3v\n- amount: 1ugnot\n- hashlock: 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b\n- timelock: 2009-02-13T22:31:30Z\n- remaining: 0s`\n\tuassert.Equal(t, expected, swap.String())\n\tuassert.Equal(t, expected, Render(\"1\"))\n}\n\nfunc TestNewCustomGRC20Swap_Claim(cur realm, t *testing.T) {\n\tdefer resetTestState()\n\n\t// Setup\n\tsender := testutils.TestAddress(\"sender3\")\n\trecipient := testutils.TestAddress(\"recipient3\")\n\trlm := chain.PackageAddress(\"gno.land/r/demo/defi/atomicswap\")\n\thashlock := sha256.Sum256([]byte(\"secret\"))\n\thashlockHex := hex.EncodeToString(hashlock[:])\n\ttimelock := time.Now().Add(1 * time.Hour)\n\n\ttest20.PrivateLedger.Mint(sender, 100_000)\n\ttest20.PrivateLedger.Approve(sender, rlm, 70_000)\n\n\t// Create a new swap\n\ttesting.SetRealm(testing.NewUserRealm(sender))\n\tid, swap := NewCustomGRC20Swap(cross(cur), recipient, hashlockHex, timelock, test20.Token)\n\tuassert.Equal(t, 1, id)\n\n\texpected := `- status: active\n- sender: g1wdjkuer9wge47h6lta047h6lta047h6l5rk38l\n- recipient: g1wfjkx6tsd9jkuapnta047h6lta047h6ly6k4pv\n- amount: 70000TST\n- hashlock: 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b\n- timelock: 2009-02-14T00:31:30Z\n- remaining: 1h0m0s`\n\n\tuassert.Equal(t, expected, swap.String())\n\tuassert.Equal(t, expected, Render(\"1\"))\n\n\t// Test initial state\n\tuassert.Equal(t, sender, swap.sender, \"expected sender to match\")\n\tuassert.Equal(t, recipient, swap.recipient, \"expected recipient to match\")\n\tbal := test20.Token.BalanceOf(sender)\n\tuassert.Equal(t, bal, int64(30_000))\n\tbal = test20.Token.BalanceOf(rlm)\n\tuassert.Equal(t, bal, int64(70_000))\n\tbal = test20.Token.BalanceOf(recipient)\n\tuassert.Equal(t, bal, int64(0))\n\n\tuassert.Equal(t, hashlockHex, swap.hashlock, \"expected hashlock to match\")\n\tuassert.True(t, swap.timelock.Equal(timelock), \"expected timelock to match\")\n\tuassert.False(t, swap.claimed, \"expected claimed to be false\")\n\tuassert.False(t, swap.refunded, \"expected refunded to be false\")\n\n\t// Test claim\n\ttesting.SetRealm(testing.NewUserRealm(recipient))\n\tuassert.AbortsWithMessage(t, cur, \"invalid preimage\", func() { Claim(cross(cur), id, \"invalid\") })\n\tClaim(cross(cur), id, \"secret\")\n\tuassert.True(t, swap.claimed, \"expected claimed to be true\")\n\n\tbal = test20.Token.BalanceOf(sender)\n\tuassert.Equal(t, bal, int64(30_000))\n\tbal = test20.Token.BalanceOf(rlm)\n\tuassert.Equal(t, bal, int64(0))\n\tbal = test20.Token.BalanceOf(recipient)\n\tuassert.Equal(t, bal, int64(70_000))\n\n\t// Test refund (should fail because already claimed)\n\tuassert.AbortsWithMessage(t, cur, \"already claimed\", func() { Refund(cross(cur), id) })\n\tuassert.AbortsWithMessage(t, cur, \"already claimed\", func() { Claim(cross(cur), id, \"secret\") })\n\n\texpected = `- status: claimed\n- sender: g1wdjkuer9wge47h6lta047h6lta047h6l5rk38l\n- recipient: g1wfjkx6tsd9jkuapnta047h6lta047h6ly6k4pv\n- amount: 70000TST\n- hashlock: 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b\n- timelock: 2009-02-14T00:31:30Z\n- remaining: 1h0m0s`\n\tuassert.Equal(t, expected, swap.String())\n\tuassert.Equal(t, expected, Render(\"1\"))\n}\n\nfunc TestNewCustomGRC20Swap_Refund(cur realm, t *testing.T) {\n\tdefer resetTestState()\n\n\t// Setup\n\tpkgAddr := chain.PackageAddress(\"gno.land/r/demo/defi/atomicswap\")\n\tsender := testutils.TestAddress(\"sender5\")\n\trecipient := testutils.TestAddress(\"recipient5\")\n\trlm := chain.PackageAddress(\"gno.land/r/demo/defi/atomicswap\")\n\thashlock := sha256.Sum256([]byte(\"secret\"))\n\thashlockHex := hex.EncodeToString(hashlock[:])\n\ttimelock := time.Now().Add(1 * time.Hour)\n\n\ttest20.PrivateLedger.Mint(sender, 100_000)\n\ttest20.PrivateLedger.Approve(sender, rlm, 70_000)\n\n\t// Create a new swap\n\ttesting.SetRealm(testing.NewUserRealm(sender))\n\tid, swap := NewCustomGRC20Swap(cross(cur), recipient, hashlockHex, timelock, test20.Token)\n\tuassert.Equal(t, 1, id)\n\n\texpected := `- status: active\n- sender: g1wdjkuer9wg647h6lta047h6lta047h6l5p6k3k\n- recipient: g1wfjkx6tsd9jkuap4ta047h6lta047h6lmwmj6v\n- amount: 70000TST\n- hashlock: 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b\n- timelock: 2009-02-14T00:31:30Z\n- remaining: 1h0m0s`\n\tuassert.Equal(t, expected, swap.String())\n\tuassert.Equal(t, expected, Render(\"1\"))\n\n\t// Test initial state\n\tuassert.Equal(t, sender, swap.sender, \"expected sender to match\")\n\tuassert.Equal(t, recipient, swap.recipient, \"expected recipient to match\")\n\tbal := test20.Token.BalanceOf(sender)\n\tuassert.Equal(t, bal, int64(30_000))\n\tbal = test20.Token.BalanceOf(rlm)\n\tuassert.Equal(t, bal, int64(70_000))\n\tbal = test20.Token.BalanceOf(recipient)\n\tuassert.Equal(t, bal, int64(0))\n\n\t// Test Refund — sender is still the current realm.\n\ttesting.IssueCoins(pkgAddr, chain.Coins{{\"ugnot\", 100000000}})\n\tuassert.AbortsWithMessage(t, cur, \"timelock not expired\", func() { Refund(cross(cur), id) })\n\n\tswap.timelock = time.Now().Add(-1 * time.Hour) // override timelock\n\tRefund(cross(cur), id)\n\tuassert.True(t, swap.refunded, \"expected refunded to be true\")\n\n\tbal = test20.Token.BalanceOf(sender)\n\tuassert.Equal(t, bal, int64(100_000))\n\tbal = test20.Token.BalanceOf(rlm)\n\tuassert.Equal(t, bal, int64(0))\n\tbal = test20.Token.BalanceOf(recipient)\n\tuassert.Equal(t, bal, int64(0))\n\n\texpected = `- status: refunded\n- sender: g1wdjkuer9wg647h6lta047h6lta047h6l5p6k3k\n- recipient: g1wfjkx6tsd9jkuap4ta047h6lta047h6lmwmj6v\n- amount: 70000TST\n- hashlock: 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b\n- timelock: 2009-02-13T22:31:30Z\n- remaining: 0s`\n\tuassert.Equal(t, expected, swap.String())\n\tuassert.Equal(t, expected, Render(\"1\"))\n}\n\nfunc TestNewGRC20Swap_Claim(cur realm, t *testing.T) {\n\tdefer resetTestState()\n\n\t// Setup\n\tsender := testutils.TestAddress(\"sender4\")\n\trecipient := testutils.TestAddress(\"recipient4\")\n\trlm := chain.PackageAddress(\"gno.land/r/demo/defi/atomicswap\")\n\thashlock := sha256.Sum256([]byte(\"secret\"))\n\thashlockHex := hex.EncodeToString(hashlock[:])\n\ttimelock := time.Now().Add(defaultTimelockDuration)\n\n\ttest20.PrivateLedger.Mint(sender, 100_000)\n\ttest20.PrivateLedger.Approve(sender, rlm, 70_000)\n\n\t// Create a new swap\n\ttesting.SetRealm(testing.NewUserRealm(sender))\n\tid, swap := NewGRC20Swap(cross(cur), recipient, hashlockHex, \"gno.land/r/tests/vm/test20.TST\")\n\tuassert.Equal(t, 1, id)\n\n\texpected := `- status: active\n- sender: g1wdjkuer9wg697h6lta047h6lta047h6ltt3lty\n- recipient: g1wfjkx6tsd9jkuap5ta047h6lta047h6ljg4l2v\n- amount: 70000TST\n- hashlock: 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b\n- timelock: 2009-02-20T23:31:30Z\n- remaining: 168h0m0s`\n\tuassert.Equal(t, expected, swap.String())\n\tuassert.Equal(t, expected, Render(\"1\"))\n\n\t// Test initial state\n\tuassert.Equal(t, sender, swap.sender, \"expected sender to match\")\n\tuassert.Equal(t, recipient, swap.recipient, \"expected recipient to match\")\n\tbal := test20.Token.BalanceOf(sender)\n\tuassert.Equal(t, bal, int64(30_000))\n\tbal = test20.Token.BalanceOf(rlm)\n\tuassert.Equal(t, bal, int64(70_000))\n\tbal = test20.Token.BalanceOf(recipient)\n\tuassert.Equal(t, bal, int64(0))\n\n\tuassert.Equal(t, hashlockHex, swap.hashlock, \"expected hashlock to match\")\n\tuassert.True(t, swap.timelock.Equal(timelock), \"expected timelock to match\")\n\tuassert.False(t, swap.claimed, \"expected claimed to be false\")\n\tuassert.False(t, swap.refunded, \"expected refunded to be false\")\n\n\t// Test claim\n\ttesting.SetRealm(testing.NewUserRealm(recipient))\n\tuassert.AbortsWithMessage(t, cur, \"invalid preimage\", func() { Claim(cross(cur), id, \"invalid\") })\n\tClaim(cross(cur), id, \"secret\")\n\tuassert.True(t, swap.claimed, \"expected claimed to be true\")\n\n\tbal = test20.Token.BalanceOf(sender)\n\tuassert.Equal(t, int64(30_000), bal)\n\tbal = test20.Token.BalanceOf(rlm)\n\tuassert.Equal(t, int64(0), bal)\n\tbal = test20.Token.BalanceOf(recipient)\n\tuassert.Equal(t, int64(70_000), bal)\n\n\t// Test refund (should fail because already claimed)\n\tuassert.AbortsWithMessage(t, cur, \"already claimed\", func() { Refund(cross(cur), id) })\n\tuassert.AbortsWithMessage(t, cur, \"already claimed\", func() { Claim(cross(cur), id, \"secret\") })\n\n\texpected = `- status: claimed\n- sender: g1wdjkuer9wg697h6lta047h6lta047h6ltt3lty\n- recipient: g1wfjkx6tsd9jkuap5ta047h6lta047h6ljg4l2v\n- amount: 70000TST\n- hashlock: 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b\n- timelock: 2009-02-20T23:31:30Z\n- remaining: 168h0m0s`\n\tuassert.Equal(t, expected, swap.String())\n\tuassert.Equal(t, expected, Render(\"1\"))\n}\n\nfunc TestNewGRC20Swap_Refund(cur realm, t *testing.T) {\n\tdefer resetTestState()\n\n\t// Setup\n\tpkgAddr := chain.PackageAddress(\"gno.land/r/demo/defi/atomicswap\")\n\tsender := testutils.TestAddress(\"sender6\")\n\trecipient := testutils.TestAddress(\"recipient6\")\n\trlm := chain.PackageAddress(\"gno.land/r/demo/defi/atomicswap\")\n\thashlock := sha256.Sum256([]byte(\"secret\"))\n\thashlockHex := hex.EncodeToString(hashlock[:])\n\n\ttest20.PrivateLedger.Mint(sender, 100_000)\n\ttest20.PrivateLedger.Approve(sender, rlm, 70_000)\n\n\t// Create a new swap\n\ttesting.SetRealm(testing.NewUserRealm(sender))\n\tid, swap := NewGRC20Swap(cross(cur), recipient, hashlockHex, \"gno.land/r/tests/vm/test20.TST\")\n\tuassert.Equal(t, 1, id)\n\n\texpected := `- status: active\n- sender: g1wdjkuer9wgm97h6lta047h6lta047h6ltj497r\n- recipient: g1wfjkx6tsd9jkuapkta047h6lta047h6lqyf9rv\n- amount: 70000TST\n- hashlock: 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b\n- timelock: 2009-02-20T23:31:30Z\n- remaining: 168h0m0s`\n\tuassert.Equal(t, expected, swap.String())\n\tuassert.Equal(t, expected, Render(\"1\"))\n\n\t// Test initial state\n\tuassert.Equal(t, sender, swap.sender, \"expected sender to match\")\n\tuassert.Equal(t, recipient, swap.recipient, \"expected recipient to match\")\n\tbal := test20.Token.BalanceOf(sender)\n\tuassert.Equal(t, bal, int64(30_000))\n\tbal = test20.Token.BalanceOf(rlm)\n\tuassert.Equal(t, bal, int64(70_000))\n\tbal = test20.Token.BalanceOf(recipient)\n\tuassert.Equal(t, bal, int64(0))\n\n\t// Test Refund — sender is still the current realm.\n\ttesting.IssueCoins(pkgAddr, chain.Coins{{\"ugnot\", 100000000}})\n\tuassert.AbortsWithMessage(t, cur, \"timelock not expired\", func() { Refund(cross(cur), id) })\n\n\tswap.timelock = time.Now().Add(-1 * time.Hour) // override timelock\n\tRefund(cross(cur), id)\n\tuassert.True(t, swap.refunded, \"expected refunded to be true\")\n\n\tbal = test20.Token.BalanceOf(sender)\n\tuassert.Equal(t, bal, int64(100_000))\n\tbal = test20.Token.BalanceOf(rlm)\n\tuassert.Equal(t, bal, int64(0))\n\tbal = test20.Token.BalanceOf(recipient)\n\tuassert.Equal(t, bal, int64(0))\n\n\texpected = `- status: refunded\n- sender: g1wdjkuer9wgm97h6lta047h6lta047h6ltj497r\n- recipient: g1wfjkx6tsd9jkuapkta047h6lta047h6lqyf9rv\n- amount: 70000TST\n- hashlock: 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b\n- timelock: 2009-02-13T22:31:30Z\n- remaining: 0s`\n\tuassert.Equal(t, expected, swap.String())\n\tuassert.Equal(t, expected, Render(\"1\"))\n}\n\nfunc TestRender(cur realm, t *testing.T) {\n\tdefer resetTestState()\n\n\t// Setup\n\talice := testutils.TestAddress(\"alice\")\n\tbob := testutils.TestAddress(\"bob\")\n\tcharly := testutils.TestAddress(\"charly\")\n\trlm := chain.PackageAddress(\"gno.land/r/demo/defi/atomicswap\")\n\thashlock := sha256.Sum256([]byte(\"secret\"))\n\thashlockHex := hex.EncodeToString(hashlock[:])\n\ttimelock := time.Now().Add(1 * time.Hour)\n\n\ttest20.PrivateLedger.Mint(alice, 100_000)\n\t// SetRealm mutates the test's cur in place to look like alice's\n\t// userRealm. cur's HIV pointer is unchanged so IsCurrent still passes;\n\t// RealmTeller(0, cur) binds to alice via cur.Address().\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\tuserTeller := test20.Token.RealmTeller(0, cur)\n\tuserTeller.Approve(0, cur, rlm, 10_000)\n\tbobSwapID, _ := NewCustomGRC20Swap(cross(cur), bob, hashlockHex, timelock, test20.Token)\n\n\tuserTeller.Approve(0, cur, rlm, 20_000)\n\t_, _ = NewCustomGRC20Swap(cross(cur), charly, hashlockHex, timelock, test20.Token)\n\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\tClaim(cross(cur), bobSwapID, \"secret\")\n\texpected := `- 2: g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh -(20000TST)\u003e g1vd5xzunv09047h6lta047h6lta047h6lhsyveh - active\n- 1: g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh -(10000TST)\u003e g1vfhkyh6lta047h6lta047h6lta047h6l03vdhu - claimed\n`\n\tuassert.Equal(t, expected, Render(\"\"))\n}\n\nfunc resetTestState() {\n\tswaps = avl.Tree{}\n\tcounter = 0\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"YR1aQ0VRdOPpUsmFXily3ptOu8ch28VllM32JxfXRtZ0VupeX8nAiWCzpNfYeBjteCTxgSdobxhcSQ5ibLIJPA=="}],"memo":""}},{"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/demo/tokens/grc20\"\n\t\"gno.land/p/nt/ownable/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/r/demo/defi/grc20reg\"\n)\n\nvar (\n\tToken         *grc20.Token\n\tprivateLedger *grc20.PrivateLedger\n\tuserTeller    grc20.Teller\n\tOwnable       = ownable.NewWithAddress(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\") // 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":"foo20_test.gno","body":"package foo20\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// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\n\nfunc TestReadOnlyPublicMethods(cur realm, t *testing.T) {\n\tvar (\n\t\tadmin = address(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\")\n\t\talice = testutils.TestAddress(\"alice\")\n\t\tbob   = testutils.TestAddress(\"bob\")\n\t)\n\n\ttype test struct {\n\t\tname    string\n\t\tbalance int64\n\t\tfn      func() int64\n\t}\n\n\t// check balances #1.\n\t{\n\t\ttests := []test{\n\t\t\t{\"TotalSupply\", 10_000_000_000, func() int64 { return TotalSupply() }},\n\t\t\t{\"BalanceOf(admin)\", 10_000_000_000, func() int64 { return BalanceOf(admin) }},\n\t\t\t{\"BalanceOf(alice)\", 0, func() int64 { return BalanceOf(alice) }},\n\t\t\t{\"Allowance(admin, alice)\", 0, func() int64 { return Allowance(admin, alice) }},\n\t\t\t{\"BalanceOf(bob)\", 0, func() int64 { return BalanceOf(bob) }},\n\t\t}\n\t\tfor _, tc := range tests {\n\t\t\tgot := tc.fn()\n\t\t\tuassert.Equal(t, got, tc.balance)\n\t\t}\n\t}\n\n\t// bob uses the faucet.\n\ttesting.SetOriginCaller(bob)\n\tFaucet(cross(cur))\n\n\t// check balances #2.\n\t{\n\t\ttests := []test{\n\t\t\t{\"TotalSupply\", 10_010_000_000, func() int64 { return TotalSupply() }},\n\t\t\t{\"BalanceOf(admin)\", 10_000_000_000, func() int64 { return BalanceOf(admin) }},\n\t\t\t{\"BalanceOf(alice)\", 0, func() int64 { return BalanceOf(alice) }},\n\t\t\t{\"Allowance(admin, alice)\", 0, func() int64 { return Allowance(admin, alice) }},\n\t\t\t{\"BalanceOf(bob)\", 10_000_000, func() int64 { return BalanceOf(bob) }},\n\t\t}\n\t\tfor _, tc := range tests {\n\t\t\tgot := tc.fn()\n\t\t\tuassert.Equal(t, got, tc.balance)\n\t\t}\n\t}\n}\n\nfunc TestErrConditions(cur realm, t *testing.T) {\n\tvar (\n\t\tadmin = address(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\")\n\t\tempty = address(\"\")\n\t)\n\n\ttype test struct {\n\t\tname    string\n\t\tmsg     string\n\t\tisCross bool\n\t\tfn      func()\n\t}\n\n\tprivateLedger.Mint(address(admin), 10000)\n\t{\n\t\ttests := []test{\n\t\t\t{\"Transfer(admin, 1)\", \"cannot send transfer to self\", false, func() {\n\t\t\t\t// XXX: should replace with: Transfer(admin, 1)\n\t\t\t\t// but there is currently a limitation in manipulating the frame stack and simulate\n\t\t\t\t// calling this package from an outside point of view.\n\t\t\t\tadminAddr := address(admin)\n\t\t\t\tif err := privateLedger.Transfer(adminAddr, adminAddr, 1); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}},\n\t\t\t{\"Approve(empty, 1))\", \"invalid address\", true, func() { Approve(cross(cur), empty, 1) }},\n\t\t}\n\t\tfor _, tc := range tests {\n\t\t\tif tc.isCross {\n\t\t\t\tuassert.AbortsWithMessage(t, cur, tc.msg, tc.fn)\n\t\t\t} else {\n\t\t\t\tuassert.PanicsWithMessage(t, cur, tc.msg, tc.fn)\n\t\t\t}\n\t\t}\n\t}\n}\n\n//func TestNewFoo20(t *testing.T) {\n//\tt.Run(\"invalid input\", func(t *testing.T) {\n//\t\ttestCases := []struct {\n//\t\t\tmsg string\n//\t\t\tfn  func()\n//\t\t}{\n//\t\t\t// Test AbortsWithMessage\n//\tuassert.PanicsWithMessage\", func() { NewFoo20(\"foo\", \"f\", 0) }},\n//\t\t\t{\"symbol cannot be empty\", func() { NewFoo20(\"foo\", \"\", 1) }},\n//\t\t\t{\"name cannot be empty\", func() { NewFoo20(\"\", \"f\", 1) }},\n//\t\t}\n//\t\tfor _, tc := range testCases {\n//\t\t\tuassert.AbortsWithMessage(t, cur, tc.msg, tc.fn)\n//\t\t}\n//\t})\n//\tt.Run(\"transfer\", func(t *testing.T) {\n//\t\t// ... existing code ...\n//\t})\n//}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/demo/defi/foo20\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"rKRU9+UWvyhCjEyUXzY/pGGdHyWNJUBFC3THeOjhm/lXFnwJ5K0EAzgT2kUWg1OjLE3M+4OM6J09ck/ltZ/OLA=="}],"memo":""}},{"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"},{"name":"z_0_filetest.gno","body":"// PKGPATH: gno.land/r/demo/main\n\npackage main\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\t\"gno.land/r/demo/disperse\"\n)\n\nfunc main(cur realm) {\n\tmainAddr := chain.PackageAddress(\"gno.land/r/demo/main\")\n\tdisperseAddr := chain.PackageAddress(\"gno.land/r/demo/disperse\")\n\tbeneficiary1 := address(\"g1dmt3sa5ucvecxuhf3j6ne5r0e3z4x7h6c03xc0\")\n\tbeneficiary2 := address(\"g1akeqsvhucjt8gf5yupyzjxsjd29wv8fayng37c\")\n\n\ttesting.IssueCoins(mainAddr, chain.Coins{{Denom: \"ugnot\", Amount: 250}})\n\ttesting.SetOriginSend(chain.Coins{{Denom: \"ugnot\", Amount: 250}})\n\ttesting.SetRealm(testing.NewUserRealm(mainAddr))\n\n\tbanker_ := banker.NewBanker(banker.BankerTypeRealmSend, cur)\n\tprintln(\"main balance before send:\", banker_.GetCoins(mainAddr))\n\tprintln(\"disperse balance before send:\", banker_.GetCoins(disperseAddr))\n\n\tbanker_.SendCoins(mainAddr, disperseAddr, chain.Coins{{\"ugnot\", 250}})\n\tprintln(\"main balance after send:\", banker_.GetCoins(mainAddr))\n\tprintln(\"disperse balance after send:\", banker_.GetCoins(disperseAddr))\n\n\taddressesStr := beneficiary1.String() + \",\" + beneficiary2.String()\n\tdisperse.DisperseUgnotString(cross(cur), addressesStr, \"150,50\")\n\n\tprintln(\"main balance after disperse:\", banker_.GetCoins(mainAddr))\n\tprintln(\"disperse balance after disperse:\", banker_.GetCoins(disperseAddr))\n\tprintln(\"beneficiary1 balance:\", banker_.GetCoins(beneficiary1))\n\tprintln(\"beneficiary2 balance:\", banker_.GetCoins(beneficiary2))\n}\n\n// Output:\n// main balance before send: 250ugnot\n// disperse balance before send:\n// main balance after send:\n// disperse balance after send: 250ugnot\n// main balance after disperse: 50ugnot\n// disperse balance after disperse:\n// beneficiary1 balance: 150ugnot\n// beneficiary2 balance: 50ugnot\n"},{"name":"z_1_filetest.gno","body":"// PKGPATH: gno.land/r/demo/main\n\npackage main\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\t\"gno.land/r/demo/disperse\"\n)\n\nfunc main(cur realm) {\n\tmainAddr := chain.PackageAddress(\"gno.land/r/demo/main\")\n\tdisperseAddr := chain.PackageAddress(\"gno.land/r/demo/disperse\")\n\tbeneficiary1 := address(\"g1dmt3sa5ucvecxuhf3j6ne5r0e3z4x7h6c03xc0\")\n\tbeneficiary2 := address(\"g1akeqsvhucjt8gf5yupyzjxsjd29wv8fayng37c\")\n\n\t// Envelope = 300 ugnot, but only 200 forwarded to disperse (the\n\t// remaining 100 stays in mainAddr). Tests that the realm-balance\n\t// check, not OriginSend, is what gates dispersal.\n\ttesting.IssueCoins(mainAddr, chain.Coins{{Denom: \"ugnot\", Amount: 300}})\n\ttesting.SetOriginSend(chain.Coins{{Denom: \"ugnot\", Amount: 300}})\n\ttesting.SetRealm(testing.NewUserRealm(mainAddr))\n\n\tbanker_ := banker.NewBanker(banker.BankerTypeRealmSend, cur)\n\tprintln(\"main balance before send:\", banker_.GetCoins(mainAddr))\n\tprintln(\"disperse balance before send:\", banker_.GetCoins(disperseAddr))\n\n\tbanker_.SendCoins(mainAddr, disperseAddr, chain.Coins{{\"ugnot\", 200}})\n\tprintln(\"main balance after send:\", banker_.GetCoins(mainAddr))\n\tprintln(\"disperse balance after send:\", banker_.GetCoins(disperseAddr))\n\n\taddressesStr := beneficiary1.String() + \",\" + beneficiary2.String()\n\tdisperse.DisperseUgnotString(cross(cur), addressesStr, \"150,50\")\n\n\tprintln(\"main balance after disperse:\", banker_.GetCoins(mainAddr))\n\tprintln(\"disperse balance after disperse:\", banker_.GetCoins(disperseAddr))\n\tprintln(\"beneficiary1 balance:\", banker_.GetCoins(beneficiary1))\n\tprintln(\"beneficiary2 balance:\", banker_.GetCoins(beneficiary2))\n}\n\n// Output:\n// main balance before send: 300ugnot\n// disperse balance before send:\n// main balance after send: 100ugnot\n// disperse balance after send: 200ugnot\n// main balance after disperse: 100ugnot\n// disperse balance after disperse:\n// beneficiary1 balance: 150ugnot\n// beneficiary2 balance: 50ugnot\n"},{"name":"z_2_filetest.gno","body":"// PKGPATH: gno.land/r/demo/main\n\npackage main\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\t\"gno.land/r/demo/disperse\"\n)\n\nfunc main(cur realm) {\n\tmainAddr := chain.PackageAddress(\"gno.land/r/demo/main\")\n\tdisperseAddr := chain.PackageAddress(\"gno.land/r/demo/disperse\")\n\tbeneficiary1 := address(\"g1dmt3sa5ucvecxuhf3j6ne5r0e3z4x7h6c03xc0\")\n\tbeneficiary2 := address(\"g1akeqsvhucjt8gf5yupyzjxsjd29wv8fayng37c\")\n\n\t// Mismatch: requested dispersal sum (200) exceeds the realm balance (100).\n\ttesting.IssueCoins(mainAddr, chain.Coins{{Denom: \"ugnot\", Amount: 100}})\n\ttesting.SetOriginSend(chain.Coins{{Denom: \"ugnot\", Amount: 100}})\n\ttesting.SetRealm(testing.NewUserRealm(mainAddr))\n\n\tbanker_ := banker.NewBanker(banker.BankerTypeRealmSend, cur)\n\tprintln(\"main balance before send:\", banker_.GetCoins(mainAddr))\n\tprintln(\"disperse balance before send:\", banker_.GetCoins(disperseAddr))\n\n\tbanker_.SendCoins(mainAddr, disperseAddr, chain.Coins{{\"ugnot\", 100}})\n\tprintln(\"main balance after send:\", banker_.GetCoins(mainAddr))\n\tprintln(\"disperse balance after send:\", banker_.GetCoins(disperseAddr))\n\n\taddressesStr := beneficiary1.String() + \",\" + beneficiary2.String()\n\tdisperse.DisperseUgnotString(cross(cur), addressesStr, \"150,50\")\n}\n\n// Error:\n// disperse: mismatch between coins sent and params called\n"},{"name":"z_3_filetest.gno","body":"// PKGPATH: gno.land/r/demo/main\n\npackage main\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\ttokens \"gno.land/r/demo/defi/grc20factory\"\n\t\"gno.land/r/demo/disperse\"\n)\n\nfunc main(cur realm) {\n\tdisperseAddr := chain.PackageAddress(\"gno.land/r/demo/disperse\")\n\tmainAddr := chain.PackageAddress(\"gno.land/r/demo/main\")\n\tbeneficiary1 := address(\"g1dmt3sa5ucvecxuhf3j6ne5r0e3z4x7h6c03xc0\")\n\tbeneficiary2 := address(\"g1akeqsvhucjt8gf5yupyzjxsjd29wv8fayng37c\")\n\n\ttesting.SetOriginCaller(mainAddr)\n\n\ttokens.New(cross(cur), \"test\", \"TEST\", 4, 0, 0)\n\ttokens.Mint(cross(cur), \"TEST\", mainAddr, 200)\n\tprintln(\"main balance before:\", tokens.BalanceOf(\"TEST\", mainAddr))\n\n\ttokens.Approve(cross(cur), \"TEST\", disperseAddr, 200)\n\tprintln(\"disperse allowance before:\", tokens.Allowance(\"TEST\", mainAddr, disperseAddr))\n\n\taddressesStr := beneficiary1.String() + \",\" + beneficiary2.String()\n\tdisperse.DisperseGRC20String(cross(cur), addressesStr, \"150TEST,50TEST\")\n\n\tprintln(\"main balance after:\", tokens.BalanceOf(\"TEST\", mainAddr))\n\tprintln(\"disperse allowance after:\", tokens.Allowance(\"TEST\", mainAddr, disperseAddr))\n\tprintln(\"beneficiary1 balance:\", tokens.BalanceOf(\"TEST\", beneficiary1))\n\tprintln(\"beneficiary2 balance:\", tokens.BalanceOf(\"TEST\", beneficiary2))\n}\n\n// Output:\n// main balance before: 200\n// disperse allowance before: 200\n// main balance after: 0\n// disperse allowance after: 0\n// beneficiary1 balance: 150\n// beneficiary2 balance: 50\n"},{"name":"z_4_filetest.gno","body":"// PKGPATH: gno.land/r/demo/main\n\npackage main\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\ttokens \"gno.land/r/demo/defi/grc20factory\"\n\t\"gno.land/r/demo/disperse\"\n)\n\nfunc main(cur realm) {\n\tdisperseAddr := chain.PackageAddress(\"gno.land/r/demo/disperse\")\n\tmainAddr := chain.PackageAddress(\"gno.land/r/demo/main\")\n\tbeneficiary1 := address(\"g1dmt3sa5ucvecxuhf3j6ne5r0e3z4x7h6c03xc0\")\n\tbeneficiary2 := address(\"g1akeqsvhucjt8gf5yupyzjxsjd29wv8fayng37c\")\n\n\ttesting.SetOriginCaller(mainAddr)\n\n\ttokens.New(cross(cur), \"test1\", \"TEST1\", 4, 0, 0)\n\ttokens.Mint(cross(cur), \"TEST1\", mainAddr, 200)\n\tprintln(\"main balance before (TEST1):\", tokens.BalanceOf(\"TEST1\", mainAddr))\n\n\ttokens.New(cross(cur), \"test2\", \"TEST2\", 4, 0, 0)\n\ttokens.Mint(cross(cur), \"TEST2\", mainAddr, 200)\n\tprintln(\"main balance before (TEST2):\", tokens.BalanceOf(\"TEST2\", mainAddr))\n\n\ttokens.Approve(cross(cur), \"TEST1\", disperseAddr, 200)\n\tprintln(\"disperse allowance before (TEST1):\", tokens.Allowance(\"TEST1\", mainAddr, disperseAddr))\n\n\ttokens.Approve(cross(cur), \"TEST2\", disperseAddr, 200)\n\tprintln(\"disperse allowance before (TEST2):\", tokens.Allowance(\"TEST2\", mainAddr, disperseAddr))\n\n\taddressesStr := beneficiary1.String() + \",\" + beneficiary2.String()\n\tdisperse.DisperseGRC20String(cross(cur), addressesStr, \"200TEST1,200TEST2\")\n\n\tprintln(\"main balance after (TEST1):\", tokens.BalanceOf(\"TEST1\", mainAddr))\n\tprintln(\"main balance after (TEST2):\", tokens.BalanceOf(\"TEST2\", mainAddr))\n\tprintln(\"disperse allowance after (TEST1):\", tokens.Allowance(\"TEST1\", mainAddr, disperseAddr))\n\tprintln(\"disperse allowance after (TEST2):\", tokens.Allowance(\"TEST2\", mainAddr, disperseAddr))\n\tprintln(\"beneficiary1 balance (TEST1):\", tokens.BalanceOf(\"TEST1\", beneficiary1))\n\tprintln(\"beneficiary1 balance (TEST2):\", tokens.BalanceOf(\"TEST2\", beneficiary1))\n\tprintln(\"beneficiary2 balance (TEST1):\", tokens.BalanceOf(\"TEST1\", beneficiary2))\n\tprintln(\"beneficiary2 balance (TEST2):\", tokens.BalanceOf(\"TEST2\", beneficiary2))\n}\n\n// Output:\n// main balance before (TEST1): 200\n// main balance before (TEST2): 200\n// disperse allowance before (TEST1): 200\n// disperse allowance before (TEST2): 200\n// main balance after (TEST1): 0\n// main balance after (TEST2): 0\n// disperse allowance after (TEST1): 0\n// disperse allowance after (TEST2): 0\n// beneficiary1 balance (TEST1): 200\n// beneficiary1 balance (TEST2): 0\n// beneficiary2 balance (TEST1): 0\n// beneficiary2 balance (TEST2): 200\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"1G93Tv7avd6/RIEp6rFSiLA+NVZIQo5lyA4emFOkUq1F/mBxaPOH4RXoP1nPEvGgCfux7hM70ymPcwhXyQvYrA=="}],"memo":""}},{"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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"xqcYMNOEtmuCuwlLOqMvLv6WXePu0W8S0M44XpYAlUojcqOV2fsNIkR3JNRw/PillVFTrhAA9yA2P/CKFh47fQ=="}],"memo":""}},{"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":"profile_test.gno","body":"package profile\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// Global addresses for test users\nvar (\n\talice   = testutils.TestAddress(\"alice\")\n\tbob     = testutils.TestAddress(\"bob\")\n\tcharlie = testutils.TestAddress(\"charlie\")\n\tdave    = testutils.TestAddress(\"dave\")\n\teve     = testutils.TestAddress(\"eve\")\n\tfrank   = testutils.TestAddress(\"frank\")\n\tuser1   = testutils.TestAddress(\"user1\")\n\tuser2   = testutils.TestAddress(\"user2\")\n)\n\nfunc TestStringFields(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\n\t// Get before setting\n\tname := GetStringField(alice, DisplayName, \"anon\")\n\tuassert.Equal(t, \"anon\", name)\n\n\t// Set new key\n\tupdated := SetStringField(cross(cur), DisplayName, \"Alice foo\")\n\tuassert.Equal(t, updated, false)\n\tupdated = SetStringField(cross(cur), Homepage, \"https://example.com\")\n\tuassert.Equal(t, updated, false)\n\n\t// Update the key\n\tupdated = SetStringField(cross(cur), DisplayName, \"Alice foo\")\n\tuassert.Equal(t, updated, true)\n\n\t// Get after setting\n\tname = GetStringField(alice, DisplayName, \"anon\")\n\thomepage := GetStringField(alice, Homepage, \"\")\n\tbio := GetStringField(alice, Bio, \"42\")\n\n\tuassert.Equal(t, \"Alice foo\", name)\n\tuassert.Equal(t, \"https://example.com\", homepage)\n\tuassert.Equal(t, \"42\", bio)\n}\n\nfunc TestIntFields(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(bob))\n\n\t// Get before setting\n\tage := GetIntField(bob, Age, 25)\n\tuassert.Equal(t, 25, age)\n\n\t// Set new key\n\tupdated := SetIntField(cross(cur), Age, 30)\n\tuassert.Equal(t, updated, false)\n\n\t// Update the key\n\tupdated = SetIntField(cross(cur), Age, 30)\n\tuassert.Equal(t, updated, true)\n\n\t// Get after setting\n\tage = GetIntField(bob, Age, 25)\n\tuassert.Equal(t, 30, age)\n}\n\nfunc TestBoolFields(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(charlie))\n\n\t// Get before setting\n\thiring := GetBoolField(charlie, AvailableForHiring, false)\n\tuassert.Equal(t, false, hiring)\n\n\t// Set\n\tupdated := SetBoolField(cross(cur), AvailableForHiring, true)\n\tuassert.Equal(t, updated, false)\n\n\t// Update the key\n\tupdated = SetBoolField(cross(cur), AvailableForHiring, true)\n\tuassert.Equal(t, updated, true)\n\n\t// Get after setting\n\thiring = GetBoolField(charlie, AvailableForHiring, false)\n\tuassert.Equal(t, true, hiring)\n}\n\nfunc TestMultipleProfiles(cur realm, t *testing.T) {\n\t// Set profile for user1\n\ttesting.SetRealm(testing.NewUserRealm(user1))\n\tupdated := SetStringField(cross(cur), DisplayName, \"User One\")\n\tuassert.Equal(t, updated, false)\n\n\t// Set profile for user2\n\ttesting.SetRealm(testing.NewUserRealm(user2))\n\tupdated = SetStringField(cross(cur), DisplayName, \"User Two\")\n\tuassert.Equal(t, updated, false)\n\n\t// Get profiles\n\ttesting.SetRealm(testing.NewUserRealm(user1)) // Switch back to user1\n\tname1 := GetStringField(user1, DisplayName, \"anon\")\n\ttesting.SetRealm(testing.NewUserRealm(user2)) // Switch back to user2\n\tname2 := GetStringField(user2, DisplayName, \"anon\")\n\n\tuassert.Equal(t, \"User One\", name1)\n\tuassert.Equal(t, \"User Two\", name2)\n}\n\nfunc TestArbitraryStringField(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(user1))\n\n\t// Set arbitrary string field\n\tupdated := SetStringField(cross(cur), \"MyEmail\", \"my@email.com\")\n\tuassert.Equal(t, updated, false)\n\n\tval := GetStringField(user1, \"MyEmail\", \"\")\n\tuassert.Equal(t, val, \"my@email.com\")\n}\n\nfunc TestArbitraryIntField(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(user1))\n\n\t// Set arbitrary int field\n\tupdated := SetIntField(cross(cur), \"MyIncome\", 100_000)\n\tuassert.Equal(t, updated, false)\n\n\tval := GetIntField(user1, \"MyIncome\", 0)\n\tuassert.Equal(t, val, 100_000)\n}\n\nfunc TestArbitraryBoolField(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(user1))\n\n\t// Set arbitrary bool field\n\tupdated := SetBoolField(cross(cur), \"IsWinner\", true)\n\tuassert.Equal(t, updated, false)\n\n\tval := GetBoolField(user1, \"IsWinner\", false)\n\tuassert.Equal(t, val, true)\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"NEV9yVGMOUuHasoUQhkWQFzfRa4Bpr4GwAHaTLSdFBJqtrV2QzvoY5S/r4Srx13Vc0hdviKvi2Gn82+ZfMe1hA=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1g3lsfxhvaqgdv4ccemwpnms4fv6t3aq3p5z6u7","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":"events_test.gno","body":"package events\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\n// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\nvar (\n\tsuRealm          = testing.NewUserRealm(address(\"g125em6arxsnj49vx35f0n0z34putv5ty3376fg5\"))\n\tnow              = \"2009-02-13T23:31:30Z\" // time.Now() is hardcoded to this value in the gno test machine currently\n\tparsedTimeNow, _ = time.Parse(time.RFC3339, now)\n)\n\nfunc TestAddEvent(cur realm, t *testing.T) {\n\ttesting.SetRealm(suRealm)\n\n\te1Start := parsedTimeNow.Add(time.Hour * 24 * 5)\n\te1End := e1Start.Add(time.Hour * 4)\n\n\t_, err := AddEvent(cross(cur), \"Event 1\", \"this event is upcoming\", \"gno.land\", \"gnome land\", e1Start.Format(time.RFC3339), e1End.Format(time.RFC3339))\n\n\turequire.NoError(t, err)\n\tgot := renderHome(false)\n\n\tif !strings.Contains(got, \"Event 1\") {\n\t\tt.Fatalf(\"Expected to find Event 1 in render\")\n\t}\n\n\te2Start := parsedTimeNow.Add(-time.Hour * 24 * 5)\n\te2End := e2Start.Add(time.Hour * 4)\n\n\t_, err = AddEvent(cross(cur), \"Event 2\", \"this event is in the past\", \"gno.land\", \"gnome land\", e2Start.Format(time.RFC3339), e2End.Format(time.RFC3339))\n\turequire.NoError(t, err)\n\n\tgot = renderHome(false)\n\n\tupcomingPos := strings.Index(got, \"## Upcoming events\")\n\tpastPos := strings.Index(got, \"## Past events\")\n\n\te1Pos := strings.Index(got, \"Event 1\")\n\te2Pos := strings.Index(got, \"Event 2\")\n\n\t// expected index ordering: upcoming \u003c e1 \u003c past \u003c e2\n\tif e1Pos \u003c upcomingPos || e1Pos \u003e pastPos {\n\t\tt.Fatalf(\"Expected to find Event 1 in Upcoming events\")\n\t}\n\n\tif e2Pos \u003c upcomingPos || e2Pos \u003c pastPos || e2Pos \u003c e1Pos {\n\t\tt.Fatalf(\"Expected to find Event 2 on auth different pos\")\n\t}\n\n\t// larger index =\u003e smaller startTime (future =\u003e past)\n\tif events[0].startTime.Unix() \u003c events[1].startTime.Unix() {\n\t\tt.Fatalf(\"expected ordering to be different\")\n\t}\n}\n\nfunc TestAddEventErrors(cur realm, t *testing.T) {\n\ttesting.SetRealm(suRealm)\n\n\t_, err := AddEvent(cross(cur), \"\", \"sample desc\", \"gno.land\", \"gnome land\", \"2009-02-13T23:31:31Z\", \"2009-02-13T23:33:31Z\")\n\tuassert.ErrorIs(t, err, ErrEmptyName)\n\n\t_, err = AddEvent(cross(cur), \"sample name\", \"sample desc\", \"gno.land\", \"gnome land\", \"\", \"2009-02-13T23:33:31Z\")\n\tuassert.ErrorContains(t, err, ErrInvalidStartTime.Error())\n\n\t_, err = AddEvent(cross(cur), \"sample name\", \"sample desc\", \"gno.land\", \"gnome land\", \"2009-02-13T23:31:31Z\", \"\")\n\tuassert.ErrorContains(t, err, ErrInvalidEndTime.Error())\n\n\t_, err = AddEvent(cross(cur), \"sample name\", \"sample desc\", \"gno.land\", \"gnome land\", \"2009-02-13T23:31:31Z\", \"2009-02-13T23:30:31Z\")\n\tuassert.ErrorIs(t, err, ErrEndBeforeStart)\n\n\t_, err = AddEvent(cross(cur), \"sample name\", \"sample desc\", \"gno.land\", \"gnome land\", \"2009-02-13T23:31:31+06:00\", \"2009-02-13T23:33:31+02:00\")\n\tuassert.ErrorIs(t, err, ErrStartEndTimezonemMismatch)\n\n\ttooLongDesc := `Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean ma`\n\t_, err = AddEvent(cross(cur), \"sample name\", tooLongDesc, \"gno.land\", \"gnome land\", \"2009-02-13T23:31:31Z\", \"2009-02-13T23:33:31Z\")\n\tuassert.ErrorContains(t, err, ErrDescriptionTooLong.Error())\n}\n\nfunc TestDeleteEvent(cur realm, t *testing.T) {\n\ttesting.SetRealm(suRealm)\n\n\te1Start := parsedTimeNow.Add(time.Hour * 24 * 5)\n\te1End := e1Start.Add(time.Hour * 4)\n\n\tid, err := AddEvent(cross(cur), \"ToDelete\", \"description\", \"gno.land\", \"gnome land\", e1Start.Format(time.RFC3339), e1End.Format(time.RFC3339))\n\turequire.NoError(t, err)\n\n\tgot := renderHome(false)\n\n\tif !strings.Contains(got, \"ToDelete\") {\n\t\tt.Fatalf(\"Expected to find ToDelete event in render\")\n\t}\n\n\tDeleteEvent(cross(cur), id)\n\tgot = renderHome(false)\n\n\tif strings.Contains(got, \"ToDelete\") {\n\t\tt.Fatalf(\"Did not expect to find ToDelete event in render\")\n\t}\n}\n\nfunc TestEditEvent(cur realm, t *testing.T) {\n\ttesting.SetRealm(suRealm)\n\n\te1Start := parsedTimeNow.Add(time.Hour * 24 * 5)\n\te1End := e1Start.Add(time.Hour * 4)\n\tloc := \"gnome land\"\n\n\tid, err := AddEvent(cross(cur), \"ToDelete\", \"description\", \"gno.land\", loc, e1Start.Format(time.RFC3339), e1End.Format(time.RFC3339))\n\turequire.NoError(t, err)\n\n\tnewName := \"New Name\"\n\tnewDesc := \"Normal description\"\n\tnewLink := \"new Link\"\n\tnewST := e1Start.Add(time.Hour)\n\tnewET := newST.Add(time.Hour)\n\n\tEditEvent(cross(cur), id, newName, newDesc, newLink, \"\", newST.Format(time.RFC3339), newET.Format(time.RFC3339))\n\tedited, _, _ := GetEventByID(id)\n\n\t// Check updated values\n\tuassert.Equal(t, edited.name, newName)\n\tuassert.Equal(t, edited.description, newDesc)\n\tuassert.Equal(t, edited.link, newLink)\n\tuassert.True(t, edited.startTime.Equal(newST))\n\tuassert.True(t, edited.endTime.Equal(newET))\n\n\t// Check if the old values are the same\n\tuassert.Equal(t, edited.location, loc)\n}\n\nfunc TestInvalidEdit(cur realm, t *testing.T) {\n\ttesting.SetRealm(suRealm)\n\n\tuassert.AbortsWithMessage(t, cur, ErrNoSuchID.Error(), func() {\n\t\tEditEvent(cross(cur), \"123123\", \"\", \"\", \"\", \"\", \"\", \"\")\n\t})\n}\n\nfunc TestParseTimes(t *testing.T) {\n\t// times not provided\n\t// end time before start time\n\t// timezone Missmatch\n\n\t_, _, err := parseTimes(\"\", \"\")\n\tuassert.ErrorContains(t, err, ErrInvalidStartTime.Error())\n\n\t_, _, err = parseTimes(now, \"\")\n\tuassert.ErrorContains(t, err, ErrInvalidEndTime.Error())\n\n\t_, _, err = parseTimes(\"2009-02-13T23:30:30Z\", \"2009-02-13T21:30:30Z\")\n\tuassert.ErrorContains(t, err, ErrEndBeforeStart.Error())\n\n\t_, _, err = parseTimes(\"2009-02-10T23:30:30+02:00\", \"2009-02-13T21:30:33+05:00\")\n\tuassert.ErrorContains(t, err, ErrStartEndTimezonemMismatch.Error())\n}\n\nfunc TestRenderEventWidget(cur realm, t *testing.T) {\n\ttesting.SetRealm(suRealm)\n\n\t// No events yet\n\tevents = nil\n\tout, err := RenderEventWidget(1)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, out, \"No events.\")\n\n\t// Ordering \u0026 if requested amt is larger than the num of events that exist\n\te1Start := parsedTimeNow.Add(time.Hour * 24 * 5)\n\te1End := e1Start.Add(time.Hour * 4)\n\n\te2Start := parsedTimeNow.Add(time.Hour * 24 * 10) // event 2 is after event 1\n\te2End := e2Start.Add(time.Hour * 4)\n\n\t_, err = AddEvent(cross(cur), \"Event 1\", \"description\", \"gno.land\", \"loc\", e1Start.Format(time.RFC3339), e1End.Format(time.RFC3339))\n\turequire.NoError(t, err)\n\n\t_, err = AddEvent(cross(cur), \"Event 2\", \"description\", \"gno.land\", \"loc\", e2Start.Format(time.RFC3339), e2End.Format(time.RFC3339))\n\turequire.NoError(t, err)\n\n\t// Too many events (must be checked after adding events, otherwise\n\t// RenderEventWidget returns early with \"No events.\")\n\tout, err = RenderEventWidget(MaxWidgetSize + 1)\n\tuassert.ErrorIs(t, err, ErrMaxWidgetSize)\n\n\t// Too few events\n\tout, err = RenderEventWidget(0)\n\tuassert.ErrorIs(t, err, ErrMinWidgetSize)\n\n\tout, err = RenderEventWidget(MaxWidgetSize)\n\turequire.NoError(t, err)\n\n\tuniqueSequence := \"- [\" // sequence that is displayed once per each event as per the RenderEventWidget function\n\tuassert.Equal(t, 2, strings.Count(out, uniqueSequence))\n\n\tuassert.True(t, strings.Index(out, \"Event 1\") \u003e strings.Index(out, \"Event 2\"))\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\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"ct8c3BJtqaYfZNTwUJG68CPN0zuXz/KkDbRqb2Ru5+ARi5nlxZMNa+EVDaapclUP86n2mm/XhOWpQxTnuUAFQQ=="}],"memo":""}},{"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"},{"name":"security_patterns_test.gno","body":"package security_patterns\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/markdown/sanitize/v0\"\n)\n\nfunc TestSetMessageRequiresLiveAdmin(cur realm, t *testing.T) {\n\t// cross(cur) at the call site performs the realm crossing: PreviousRealm\n\t// inside SetMessage becomes the UserRealm set just above, so assertAdmin\n\t// can verify the caller's address.\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\tSetMessage(cross(cur), \"hello\")\n\tif Message() != \"hello\" {\n\t\tt.Fatalf(\"message was not updated\")\n\t}\n\n\ttesting.SetRealm(testing.NewUserRealm(address(\"g1juz2yxmdsa6audkp6ep9vfv80c8p5u76e03vvh\")))\n\tif rec := revive(func() { SetMessage(cross(cur), \"attacker\") }); rec == nil {\n\t\tt.Fatalf(\"expected non-admin caller to panic\")\n\t}\n\tif Message() != \"hello\" {\n\t\tt.Fatalf(\"non-admin caller changed message\")\n\t}\n}\n\nfunc TestRenderEscapesMessage(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\tSetMessage(cross(cur), \"[x](javascript:alert(1)) \u003e quote\")\n\n\tout := Render(\"\")\n\tif strings.Contains(out, \"[x](javascript\") {\n\t\tt.Fatalf(\"message rendered as a live markdown link: %s\", out)\n\t}\n\tif want := sanitize.InlineText(\"[x](javascript:alert(1)) \u003e quote\"); !strings.Contains(out, want) {\n\t\tt.Fatalf(\"message not escaped via sanitize.InlineText: %q not in %s\", want, out)\n\t}\n}\n\nfunc TestRenderPathUsesSafeCodeSpan(t *testing.T) {\n\t// A backtick in path must not close the code span early; InlineCode picks\n\t// a wider backtick fence, whereas a naive \"`\" + path + \"`\" would let the\n\t// user's backtick break out.\n\tpath := \"a`b`c\"\n\tout := Render(path)\n\tif want := sanitize.InlineCode(path); !strings.Contains(out, want) {\n\t\tt.Fatalf(\"path not rendered via a safe code span: %q not in %s\", want, out)\n\t}\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"P6DqNI29S298QCy8HB++0usj/4cphL0gFaVv9HsHEKMgBSDIqdvNfEd8SYuxDaNyRbzR4OOdOPYcELt1g5uoCg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1g3lsfxhvaqgdv4ccemwpnms4fv6t3aq3p5z6u7","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(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\") // 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":"admin_test.gno","body":"package blog\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/demo/blog\"\n\t\"gno.land/p/nt/bptree/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// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\n\n// clearState wipes the global state between test calls\nfunc clearState(t *testing.T) {\n\tt.Helper()\n\n\tb = \u0026blog.Blog{\n\t\tTitle:  \"Gno.land's blog\",\n\t\tPrefix: \"/r/gnoland/blog:\",\n\t}\n\tadminAddr = address(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\")\n\tinPause = false\n\tmoderatorList = bptree.NewBPTree32()\n\tcommenterList = bptree.NewBPTree32()\n}\n\nfunc TestBlog_AdminControls(cur realm, t *testing.T) {\n\tt.Run(\"non-admin call\", func(t *testing.T) {\n\t\tclearState(t)\n\n\t\tnonAdmin := testutils.TestAddress(\"bob\")\n\n\t\ttesting.SetOriginCaller(nonAdmin)\n\t\ttesting.SetRealm(testing.NewUserRealm(nonAdmin))\n\n\t\tuassert.AbortsWithMessage(t, cur, errNotAdmin.Error(), func() {\n\t\t\tAdminSetInPause(cross(cur), true)\n\t\t})\n\t})\n\n\tt.Run(\"pause toggled\", func(t *testing.T) {\n\t\tclearState(t)\n\n\t\ttesting.SetOriginCaller(adminAddr)\n\t\ttesting.SetRealm(testing.NewUserRealm(adminAddr))\n\n\t\tuassert.NotAborts(t, cur, func() {\n\t\t\tAdminSetInPause(cross(cur), true)\n\t\t})\n\n\t\tuassert.True(t, inPause)\n\t})\n\n\tt.Run(\"admin set\", func(t *testing.T) {\n\t\tclearState(t)\n\n\t\t// Set the new admin\n\t\tvar (\n\t\t\toldAdmin = adminAddr\n\t\t\tnewAdmin = testutils.TestAddress(\"alice\")\n\t\t)\n\n\t\ttesting.SetRealm(testing.NewUserRealm(adminAddr))\n\t\tAdminSetAdminAddr(cross(cur), newAdmin)\n\n\t\tuassert.Equal(t, adminAddr, newAdmin)\n\n\t\t// Make sure the old admin can't do anything\n\t\ttesting.SetOriginCaller(oldAdmin)\n\t\ttesting.SetRealm(testing.NewUserRealm(oldAdmin))\n\n\t\tuassert.AbortsWithMessage(t, cur, errNotAdmin.Error(), func() {\n\t\t\tAdminSetInPause(cross(cur), false)\n\t\t})\n\t})\n}\n\nfunc TestBlog_AddRemoveModerator(cur realm, t *testing.T) {\n\tclearState(t)\n\n\tmod := testutils.TestAddress(\"mod\")\n\n\t// Add the moderator\n\ttesting.SetOriginCaller(adminAddr)\n\ttesting.SetRealm(testing.NewUserRealm(adminAddr))\n\tAdminAddModerator(cross(cur), mod)\n\n\turequire.True(t, moderatorList.Has(mod.String()))\n\n\t// Remove the moderator\n\tAdminRemoveModerator(cross(cur), mod)\n\n\t// Make sure the moderator is disabled\n\tisMod := moderatorList.Get(mod.String())\n\tuassert.NotNil(t, isMod)\n\n\tuassert.False(t, isMod.(bool))\n}\n\nfunc TestBlog_AddCommenter(cur realm, t *testing.T) {\n\tclearState(t)\n\n\tvar (\n\t\tmod       = testutils.TestAddress(\"mod\")\n\t\tcommenter = testutils.TestAddress(\"comm\")\n\t\trand      = testutils.TestAddress(\"rand\")\n\t)\n\n\t// Appoint the moderator\n\ttesting.SetOriginCaller(adminAddr)\n\ttesting.SetRealm(testing.NewUserRealm(adminAddr))\n\tAdminAddModerator(cross(cur), mod)\n\n\t// Add a commenter as a mod\n\ttesting.SetOriginCaller(mod)\n\ttesting.SetRealm(testing.NewUserRealm(mod))\n\tModAddCommenter(cross(cur), commenter)\n\n\tuassert.True(t, commenterList.Has(commenter.String()))\n\n\t// Make sure a non-mod can't add commenters\n\ttesting.SetOriginCaller(rand)\n\ttesting.SetRealm(testing.NewUserRealm(rand))\n\n\tuassert.AbortsWithMessage(t, cur, errNotModerator.Error(), func() {\n\t\tModAddCommenter(cross(cur), testutils.TestAddress(\"evil\"))\n\t})\n\n\t// Remove a commenter\n\ttesting.SetOriginCaller(mod)\n\ttesting.SetRealm(testing.NewUserRealm(mod))\n\tModDelCommenter(cross(cur), commenter)\n\n\tactive := commenterList.Get(commenter.String())\n\tuassert.False(t, active.(bool))\n}\n\nfunc TestBlog_ManagePost(cur realm, t *testing.T) {\n\tclearState(t)\n\n\tvar (\n\t\tmod  = testutils.TestAddress(\"mod\")\n\t\tslug = \"slug\"\n\t)\n\n\t// Appoint the moderator\n\ttesting.SetOriginCaller(adminAddr)\n\ttesting.SetRealm(testing.NewUserRealm(adminAddr))\n\tAdminAddModerator(cross(cur), mod)\n\n\t// Add the post\n\ttesting.SetOriginCaller(mod)\n\ttesting.SetRealm(testing.NewUserRealm(mod))\n\tModAddPost(\n\t\tcross(cur),\n\t\tslug, \"title\", \"body\", \"2022-05-20T13:17:22Z\", \"moul\", \"tag\",\n\t)\n\n\t// Make sure the post is present\n\tuassert.NotNil(t, b.GetPost(slug))\n\n\t// Remove the post\n\tModRemovePost(cross(cur), slug)\n\tuassert.TypedNil(t, b.GetPost(slug))\n}\n\nfunc TestBlog_ManageComment(cur realm, t *testing.T) {\n\tclearState(t)\n\n\tvar (\n\t\tslug = \"slug\"\n\n\t\tmod       = testutils.TestAddress(\"mod\")\n\t\tcommenter = testutils.TestAddress(\"comm\")\n\t)\n\n\t// Appoint the moderator\n\ttesting.SetOriginCaller(adminAddr)\n\ttesting.SetRealm(testing.NewUserRealm(adminAddr))\n\tAdminAddModerator(cross(cur), mod)\n\n\t// Add a commenter as a mod\n\ttesting.SetOriginCaller(mod)\n\ttesting.SetRealm(testing.NewUserRealm(mod))\n\tModAddCommenter(cross(cur), commenter)\n\n\tuassert.True(t, commenterList.Has(commenter.String()))\n\n\t// Add the post\n\ttesting.SetOriginCaller(mod)\n\ttesting.SetRealm(testing.NewUserRealm(mod))\n\tModAddPost(\n\t\tcross(cur),\n\t\tslug, \"title\", \"body\", \"2022-05-20T13:17:22Z\", \"moul\", \"tag\",\n\t)\n\n\t// Make sure the post is present\n\tuassert.NotNil(t, b.GetPost(slug))\n\n\t// Add the comment\n\ttesting.SetOriginCaller(commenter)\n\ttesting.SetRealm(testing.NewUserRealm(commenter))\n\tuassert.NotAborts(t, cur, func() {\n\t\tAddComment(cross(cur), slug, \"comment\")\n\t})\n\n\t// Delete the comment\n\ttesting.SetOriginCaller(mod)\n\ttesting.SetRealm(testing.NewUserRealm(mod))\n\tuassert.NotAborts(t, cur, func() {\n\t\tModDelComment(cross(cur), slug, 0)\n\t})\n}\n"},{"name":"gnoblog.gno","body":"package blog\n\nimport (\n\t\"chain/runtime/unsafe\"\n\n\t\"gno.land/p/demo/blog\"\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":"gnoblog_test.gno","body":"package blog\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestPackage(cur realm, t *testing.T) {\n\tclearState(t)\n\n\ttesting.SetOriginCaller(adminAddr)\n\ttesting.SetRealm(testing.NewUserRealm(adminAddr))\n\n\t// by default, no posts.\n\t{\n\t\tgot := Render(\"\")\n\t\texpected := `\n# Gno.land's blog\n\nNo posts.\n`\n\t\tassertMDEquals(t, got, expected)\n\t}\n\n\t// create two posts, list post.\n\t{\n\t\tModAddPost(cross(cur), \"slug1\", \"title1\", \"body1\", \"2022-05-20T13:17:22Z\", \"moul\", \"tag1,tag2\")\n\t\tModAddPost(cross(cur), \"slug2\", \"title2\", \"body2\", \"2022-05-20T13:17:23Z\", \"moul\", \"tag1,tag3\")\n\t\tgot := Render(\"\")\n\t\texpected := `\n\t\t\t# Gno.land's blog\n\n\u003cgno-columns\u003e\n### [title2](/r/gnoland/blog:p/slug2)\n20 May 2022\n\n\u003cgno-columns-sep\u003e\n\n### [title1](/r/gnoland/blog:p/slug1)\n20 May 2022\n\n\u003cgno-columns-sep\u003e\n\u003c/gno-columns\u003e\n`\n\t\tassertMDEquals(t, got, expected)\n\t}\n\n\t// view post.\n\t{\n\t\tgot := Render(\"p/slug2\")\n\t\texpected := `\n\t\u003cmain class='gno-tmpl-page'\u003e\n\n# title2\n\nbody2\n\n---\n\nTags: [#tag1](/r/gnoland/blog:t/tag1) [#tag3](/r/gnoland/blog:t/tag3)\n\nWritten by moul on 20 May 2022\n\nPublished by g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh to Gno.land's blog\n\n---\n\u003cdetails\u003e\u003csummary\u003eComment section\u003c/summary\u003e\n\n\u003c/details\u003e\n\u003c/main\u003e\n\t\n\t\t`\n\t\tassertMDEquals(t, got, expected)\n\t}\n\n\t// list by tags.\n\t{\n\t\tgot := Render(\"t/invalid\")\n\t\texpected := \"# [Gno.land's blog](/r/gnoland/blog:) / t / invalid\\n\\nNo posts.\"\n\t\tassertMDEquals(t, got, expected)\n\n\t\tgot = Render(\"t/tag2\")\n\t\texpected = `\n# [Gno.land's blog](/r/gnoland/blog:) / t / tag2\n\n\n### [title1](/r/gnoland/blog:p/slug1)\n20 May 2022\n\t\t`\n\t\tassertMDEquals(t, got, expected)\n\t}\n\n\t// add comments.\n\t{\n\t\tAddComment(cross(cur), \"slug1\", \"comment1\")\n\t\tAddComment(cross(cur), \"slug2\", \"comment2\")\n\t\tAddComment(cross(cur), \"slug1\", \"comment3\")\n\t\tAddComment(cross(cur), \"slug2\", \"comment4\")\n\t\tAddComment(cross(cur), \"slug1\", \"comment5\")\n\t\tgot := Render(\"p/slug2\")\n\t\texpected := `\u003cmain class='gno-tmpl-page'\u003e\n\n# title2\n\nbody2\n\n---\n\nTags: [#tag1](/r/gnoland/blog:t/tag1) [#tag3](/r/gnoland/blog:t/tag3)\n\nWritten by moul on 20 May 2022\n\nPublished by g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh to Gno.land's blog\n\n---\n\u003cdetails\u003e\u003csummary\u003eComment section\u003c/summary\u003e\n\n\u003ch5\u003ecomment4\n\n\u003c/h5\u003e\u003ch6\u003eby g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh on 13 Feb 09 23:31 UTC\u003c/h6\u003e\n\n---\n\n\u003ch5\u003ecomment2\n\n\u003c/h5\u003e\u003ch6\u003eby g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh on 13 Feb 09 23:31 UTC\u003c/h6\u003e\n\n---\n\n\u003c/details\u003e\n\u003c/main\u003e\n\n\t\t`\n\t\tassertMDEquals(t, got, expected)\n\t}\n\n\t// edit post.\n\t{\n\t\toldTitle := \"title2\"\n\t\toldDate := \"2022-05-20T13:17:23Z\"\n\n\t\tModEditPost(cur, \"slug2\", oldTitle, \"body2++\", oldDate, \"manfred\", \"tag1,tag4\")\n\t\tgot := Render(\"p/slug2\")\n\t\texpected := `\u003cmain class='gno-tmpl-page'\u003e\n\n# title2\n\nbody2++\n\n---\n\nTags: [#tag1](/r/gnoland/blog:t/tag1) [#tag4](/r/gnoland/blog:t/tag4)\n\nWritten by manfred on 20 May 2022\n\nPublished by g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh to Gno.land's blog\n\n---\n\u003cdetails\u003e\u003csummary\u003eComment section\u003c/summary\u003e\n\n\u003ch5\u003ecomment4\n\n\u003c/h5\u003e\u003ch6\u003eby g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh on 13 Feb 09 23:31 UTC\u003c/h6\u003e\n\n---\n\n\u003ch5\u003ecomment2\n\n\u003c/h5\u003e\u003ch6\u003eby g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh on 13 Feb 09 23:31 UTC\u003c/h6\u003e\n\n---\n\n\u003c/details\u003e\n\u003c/main\u003e\n\n\t\t`\n\t\tassertMDEquals(t, got, expected)\n\n\t\thome := Render(\"\")\n\n\t\tif strings.Count(home, oldTitle) != 1 {\n\t\t\tt.Errorf(\"post not edited properly\")\n\t\t}\n\t\t// Edits work everything except title, slug, and publicationDate\n\t\t// Edits to the above will cause duplication on the blog home page\n\t}\n\t//\n\t{ // Test remove functionality\n\t\ttitle := \"example title\"\n\t\tslug := \"testSlug1\"\n\t\tModAddPost(cross(cur), slug, title, \"body1\", \"2022-05-25T13:17:22Z\", \"moul\", \"tag1,tag2\")\n\n\t\tgot := Render(\"\")\n\n\t\tif !strings.Contains(got, title) {\n\t\t\tt.Errorf(\"post was not added properly\")\n\t\t}\n\n\t\tpostRender := Render(\"p/\" + slug)\n\n\t\tif !strings.Contains(postRender, title) {\n\t\t\tt.Errorf(\"post not rendered properly\")\n\t\t}\n\n\t\tModRemovePost(cur, slug)\n\t\tgot = Render(\"\")\n\n\t\tif strings.Contains(got, title) {\n\t\t\tt.Errorf(\"post was not removed\")\n\t\t}\n\n\t\tpostRender = Render(\"p/\" + slug)\n\n\t\tassertMDEquals(t, postRender, \"404\")\n\t}\n\t//\n\t//\t// TODO: pagination.\n\t//\t// TODO: ?format=...\n\t//\n\t// all 404s\n\t{\n\t\tnotFoundPaths := []string{\n\t\t\t\"p/slug3\",\n\t\t\t\"p\",\n\t\t\t\"p/\",\n\t\t\t\"x/x\",\n\t\t\t\"t\",\n\t\t\t\"t/\",\n\t\t\t\"/\",\n\t\t\t\"p/slug1/\",\n\t\t}\n\t\tfor _, notFoundPath := range notFoundPaths {\n\t\t\tgot := Render(notFoundPath)\n\t\t\texpected := \"404\"\n\t\t\tif got != expected {\n\t\t\t\tt.Errorf(\"path %q: expected %q, got %q.\", notFoundPath, expected, got)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc assertMDEquals(t *testing.T, got, expected string) {\n\tt.Helper()\n\texpected = strings.TrimSpace(expected)\n\tgot = strings.TrimSpace(got)\n\tif expected != got {\n\t\tt.Errorf(\"invalid render output.\\nexpected %q.\\ngot      %q.\", expected, got)\n\t}\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"V1VhlXfoAzQjaxMOpt1iycvv3UFS08b7EK+oAewHon8CcpMGlbrBXHfhLfImERyXiyOZ1u1v5P1wRuSSUOkjYg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"boards2","path":"gno.land/r/gnoland/boards2/v1","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] 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/v1/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/v1/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/v1$source\u0026file=permissions.gno\n[gno.land/r/gnoland/boards2/v1/permissions]: https://gno.land/r/gnoland/boards2/v1/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]: https://gno.land/p/gnoland/boards\n[Permissions]: https://gno.land/p/gnoland/boards$source\u0026file=permissions.gno#L23\n"},{"name":"boards.gno","body":"package boards2\n\nimport (\n\t\"gno.land/p/gnoland/boards\"\n\t\"gno.land/p/gnoland/boards/exts/permissions\"\n\t\"gno.land/p/moul/realmpath\"\n\t\"gno.land/p/moul/txlink\"\n\t\"gno.land/p/nt/bptree/v0\"\n)\n\nconst (\n\trealmPkgPath = \"gno.land/r/gnoland/boards2/v1\"\n\tgRealmPath   = \"/r/gnoland/boards2/v1\"\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(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\") // GovDAO T1 multisig\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\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\"\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\"\n\t\"gno.land/p/moul/md\"\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/v1\"\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\t\"gno.land/p/gnoland/boards\"\n\thubexts \"gno.land/p/gnoland/boards/exts/hub\"\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\"\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\"\n\t\"gno.land/p/gnoland/boards/exts/permissions\"\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(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\"\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\"\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// 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\"\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\tboard := boards.New(id)\n\targs := boards.Args{caller, name, board.ID, listed, open}\n\tgPerms.WithPermission(caller, PermissionBoardCreate, args, func() {\n\t\tassertRealmIsNotLocked()\n\t\tassertBoardNameNotExists(name)\n\n\t\tboard.Name = name\n\t\tboard.Creator = caller\n\t\tboard.Meta = \u0026BoardMeta{\n\t\t\tHiddenThreads: boards.NewPostStorage(),\n\t\t}\n\n\t\tif open {\n\t\t\tboard.Permissions = createOpenBoardPermissions(caller)\n\t\t} else {\n\t\t\tboard.Permissions = createBasicBoardPermissions(caller)\n\t\t}\n\n\t\tif err := gBoards.Add(board); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t// Listed boards are also indexed separately for easier iteration and pagination\n\t\tif listed {\n\t\t\tgListedBoardsByID.Set(board.ID.Key(), board)\n\t\t}\n\n\t\tchain.Emit(\n\t\t\t\"BoardCreated\",\n\t\t\t\"caller\", caller.String(),\n\t\t\t\"boardID\", board.ID.String(),\n\t\t\t\"name\", name,\n\t\t)\n\t})\n\treturn board.ID\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\"\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\"\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\"\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\"\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\"\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\"\n\t\"gno.land/p/jeronimoalbi/mdform\"\n\t\"gno.land/p/jeronimoalbi/pager\"\n\t\"gno.land/p/leon/svgbtn\"\n\t\"gno.land/p/moul/md\"\n\t\"gno.land/p/moul/mdtable\"\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\tif gListedBoardsByID.Size() == 0 {\n\t\tres.Write(md.H3(\"Currently there are no boards\"))\n\t\tres.Write(\"Be the first to \" + md.Link(\"create a new board\", createBoardURI) + \"!\")\n\t\treturn\n\t}\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\"\n\t\"gno.land/p/jeronimoalbi/mdform\"\n\t\"gno.land/p/jeronimoalbi/pager\"\n\t\"gno.land/p/moul/md\"\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\"\n\t\"gno.land/p/jeronimoalbi/mdform\"\n\t\"gno.land/p/leon/svgbtn\"\n\t\"gno.land/p/moul/md\"\n\t\"gno.land/p/moul/mdtable\"\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\"\n\t\"gno.land/p/jeronimoalbi/mdform\"\n\t\"gno.land/p/jeronimoalbi/pager\"\n\t\"gno.land/p/leon/svgbtn\"\n\t\"gno.land/p/moul/md\"\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\"\n\t\"gno.land/p/jeronimoalbi/mdform\"\n\t\"gno.land/p/jeronimoalbi/pager\"\n\t\"gno.land/p/leon/svgbtn\"\n\t\"gno.land/p/moul/md\"\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\"\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\"\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"},{"name":"z_accept_invite_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_accept_invite_00_filetest\n\npackage z_accept_invite_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n)\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tboards2.RequestInvite(cross(cur), bid)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.AcceptInvite(cross(cur), bid, user)\n\n\tprintln(boards2.IsMember(bid, user))\n\tprintln()\n\tprintln(boards2.Render(\"test123/invites\"))\n}\n\n// Output:\n// true\n//\n// # test123 Invite Requests\n// ### Board has no invite requests\n"},{"name":"z_accept_invite_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_accept_invite_01_filetest\n\npackage z_accept_invite_01_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n)\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\t// Request an invite as a user that is not a member\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tboards2.RequestInvite(cross(cur), bid)\n\n\t// Add user as a member idependently of the invite request\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.InviteMember(cross(cur), bid, user, boards2.RoleGuest)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.AcceptInvite(cross(cur), bid, user)\n}\n\n// Error:\n// user is already a member\n"},{"name":"z_accept_invite_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_accept_invite_02_filetest\n\npackage z_accept_invite_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n)\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.AcceptInvite(cross(cur), bid, user)\n}\n\n// Error:\n// invite request not found\n"},{"name":"z_accept_invite_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_accept_invite_03_filetest\n\npackage z_accept_invite_03_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n)\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tboards2.RequestInvite(cross(cur), bid)\n}\n\nfunc main(cur realm) {\n\t// Caller is not a member and has no permission to invite\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tboards2.AcceptInvite(cross(cur), bid, user)\n}\n\n// Error:\n// unauthorized, user g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5 doesn't have the required permission\n"},{"name":"z_ban_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ban_00_filetest\n\npackage z_ban_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n)\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.Ban(cross(cur), bid, user, boards2.BanDay, \"Unpolite behavior\")\n\n\tprintln(boards2.IsBanned(bid, user))\n}\n\n// Output:\n// true\n"},{"name":"z_ban_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ban_01_filetest\n\npackage z_ban_01_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n)\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\t// Invite the user as a moderator\n\tboards2.InviteMember(cross(cur), bid, user, boards2.RoleModerator)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.Ban(cross(cur), bid, user, boards2.BanDay, \"Reason\")\n}\n\n// Error:\n// owner, admin and moderator banning is not allowed\n"},{"name":"z_ban_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ban_02_filetest\n\npackage z_ban_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n)\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Try to ban a user without banning permissions\n\tboards2.Ban(cross(cur), bid, \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\", boards2.BanDay, \"Reason\")\n}\n\n// Error:\n// unauthorized, user g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5 doesn't have the required permission\n"},{"name":"z_change_member_role_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_change_member_role_00_filetest\n\npackage z_change_member_role_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner   address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tmember  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tnewRole         = boards2.RoleOwner\n\tbid             = boards.ID(0) // Operate on realm DAO instead of individual boards\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.InviteMember(cross(cur), bid, member, boards2.RoleAdmin)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.ChangeMemberRole(cross(cur), bid, member, newRole)\n\n\t// Ensure that new role has been changed\n\tprintln(boards2.HasMemberRole(bid, member, newRole))\n}\n\n// Output:\n// true\n"},{"name":"z_change_member_role_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_change_member_role_01_filetest\n\npackage z_change_member_role_01_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner   address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tmember  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tnewRole         = boards2.RoleAdmin\n)\n\nvar bid boards.ID // Operate on board DAO\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"foo123\", false, false)\n\tboards2.InviteMember(cross(cur), bid, member, boards2.RoleGuest)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.ChangeMemberRole(cross(cur), bid, member, newRole)\n\n\t// Ensure that new role has been changed\n\tprintln(boards2.HasMemberRole(bid, member, newRole))\n}\n\n// Output:\n// true\n"},{"name":"z_change_member_role_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_change_member_role_02_filetest\n\npackage z_change_member_role_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner  address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\towner2 address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tadmin  address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n)\n\nvar bid boards.ID // Operate on board DAO\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\tboards2.InviteMember(cross(cur), bid, owner2, boards2.RoleOwner)\n\tboards2.InviteMember(cross(cur), bid, admin, boards2.RoleAdmin)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\n\tboards2.ChangeMemberRole(cross(cur), bid, owner2, boards2.RoleAdmin)\n}\n\n// Error:\n// admins are not allowed to remove the Owner role\n"},{"name":"z_change_member_role_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_change_member_role_03_filetest\n\npackage z_change_member_role_03_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner  address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tadmin  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tadmin2 address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n)\n\nvar bid boards.ID // Operate on board DAO\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\tboards2.InviteMember(cross(cur), bid, admin, boards2.RoleAdmin)\n\tboards2.InviteMember(cross(cur), bid, admin2, boards2.RoleAdmin)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\n\tboards2.ChangeMemberRole(cross(cur), bid, admin2, boards2.RoleOwner)\n}\n\n// Error:\n// admins are not allowed to promote members to Owner\n"},{"name":"z_change_member_role_04_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_change_member_role_04_filetest\n\npackage z_change_member_role_04_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner   address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tmember  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tbid             = boards.ID(0)                               // Operate on realm DAO members instead of individual boards\n\tnewRole         = boards2.RoleOwner\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.InviteMember(cross(cur), bid, member, boards2.RoleAdmin)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.ChangeMemberRole(cross(cur), bid, member, newRole) // Owner can promote other members to Owner\n\n\t// Ensure that new role has been changed to owner\n\tprintln(boards2.HasMemberRole(bid, member, newRole))\n}\n\n// Output:\n// true\n"},{"name":"z_change_member_role_05_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_change_member_role_05_filetest\n\npackage z_change_member_role_05_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tadmin address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar bid boards.ID // Operate on board DAO\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\tboards2.InviteMember(cross(cur), bid, admin, boards2.RoleGuest)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.ChangeMemberRole(cross(cur), bid, admin, boards.Role(\"foo\"))\n}\n\n// Error:\n// invalid role: foo\n"},{"name":"z_change_member_role_06_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_change_member_role_06_filetest\n\npackage z_change_member_role_06_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tadmin address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar bid boards.ID // Operate on board DAO\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\tboards2.InviteMember(cross(cur), bid, admin, boards2.RoleGuest)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.ChangeMemberRole(cross(cur), bid, \"foo\", boards2.RoleModerator)\n}\n\n// Error:\n// invalid member address: foo\n"},{"name":"z_change_member_role_07_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_change_member_role_07_filetest\n\npackage z_change_member_role_07_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.ChangeMemberRole(cross(cur), 0, \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\", boards2.RoleGuest)\n}\n\n// Error:\n// unauthorized, user g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj doesn't have the required permission\n"},{"name":"z_create_board_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_board_00_filetest\n\npackage z_create_board_00_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tbid := boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\tprintln(\"ID =\", bid)\n}\n\n// Output:\n// ID = 1\n"},{"name":"z_create_board_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_board_01_filetest\n\npackage z_create_board_01_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateBoard(cross(cur), \"\", false, false)\n}\n\n// Error:\n// board name is empty\n"},{"name":"z_create_board_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_board_02_filetest\n\npackage z_create_board_02_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tboardName         = \"test123\"\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.CreateBoard(cross(cur), boardName, false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateBoard(cross(cur), boardName, false, false)\n}\n\n// Error:\n// board already exists\n"},{"name":"z_create_board_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_board_03_filetest\n\npackage z_create_board_03_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateBoard(cross(cur), \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", false, false)\n}\n\n// Error:\n// addresses are not allowed as board name\n"},{"name":"z_create_board_04_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_board_04_filetest\n\npackage z_create_board_04_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc init(cur realm) {\n\t// uinit.RegisterUser is genesis-only since the security fix.\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), \"gnoland\", address(\"g1g3lsfxhvaqgdv4ccemwpnms4fv6t3aq3p5z6u7\"))\n\ttesting.SetHeight(123)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateBoard(cross(cur), \"gnoland\", false, false)\n}\n\n// Error:\n// board name is a user name registered to a different user\n"},{"name":"z_create_board_05_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_board_05_filetest\n\npackage z_create_board_05_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar name = strings.Repeat(\"X\", boards2.MaxBoardNameLength+1)\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateBoard(cross(cur), name, false, false)\n}\n\n// Error:\n// board name is too long, maximum allowed is 50 characters\n"},{"name":"z_create_board_06_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_board_06_filetest\n\npackage z_create_board_06_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner  address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tmember address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tname           = \"test123\"\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Operate on realm DAO members instead of individual boards\n\tboards2.InviteMember(cross(cur), 0, member, boards2.RoleOwner)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(member))\n\n\t// Create a board as an invited realm member\n\tbid := boards2.CreateBoard(cross(cur), name, false, false)\n\tprintln(\"ID =\", bid)\n}\n\n// Output:\n// ID = 1\n"},{"name":"z_create_board_07_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_board_07_filetest\n\npackage z_create_board_07_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\n// Error:\n// unauthorized, user g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj doesn't have the required permission\n"},{"name":"z_create_board_08_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_board_08_filetest\n\npackage z_create_board_08_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tname          = \"TestBoard\"\n)\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateBoard(cross(cur), name, false, false)\n\n\t// Unlisted board should not be rendered\n\tprintln(boards2.Render(\"\"))\n\n\t// Unlisted board can be rendered by path\n\tprintln(\"\\n==================\")\n\tprintln(boards2.Render(name))\n}\n\n// Output:\n// # Boards\n// [Create Board](/r/gnoland/boards2/v1:create-board) • [List Admin Users](/r/gnoland/boards2/v1:admin-users) • [Help](/r/gnoland/boards2/v1:help)\n//\n// ---\n// ### Currently there are no boards\n// Be the first to [create a new board](/r/gnoland/boards2/v1:create-board)!\n//\n// ==================\n// # [Boards](/r/gnoland/boards2/v1) › TestBoard\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) on 2009-02-13 11:31pm UTC, #1\n// ↳ [Create Thread](/r/gnoland/boards2/v1:TestBoard/create-thread) • [Request Invite](/r/gnoland/boards2/v1$help\u0026func=RequestInvite\u0026boardID=1) • [Manage Board](?menu=manageBoard)\n//\n// ---\n// ### This board doesn't have any threads\n// Do you want to [start a new conversation](/r/gnoland/boards2/v1:TestBoard/create-thread) in this board?\n"},{"name":"z_create_board_09_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_board_09_filetest\n\npackage z_create_board_09_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.CreateBoard(cross(cur), \"TEST123\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Should fail because board name already exists with a different casing\n\tboards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\n// Error:\n// board already exists\n"},{"name":"z_create_board_10_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_board_10_filetest\n\npackage z_create_board_10_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Should fail because board name has a space which is not allowed\n\tboards2.CreateBoard(cross(cur), \"test 123\", false, false)\n}\n\n// Error:\n// board name must start with a letter and have letters, numbers, \"-\" and \"_\"\n"},{"name":"z_create_reply_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_reply_00_filetest\n\npackage z_create_reply_00_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner   address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tpath            = \"test-board/1/2\"\n\tcomment         = \"Test comment\"\n)\n\nvar (\n\tbid boards.ID\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\trid := boards2.CreateReply(cross(cur), bid, tid, 0, comment)\n\n\t// Ensure that returned ID is right\n\tprintln(rid == 2)\n\n\t// Render content must contain the reply\n\tcontent := boards2.Render(path)\n\tprintln(strings.Contains(content, \"\\n\u003e \"+comment))\n}\n\n// Output:\n// true\n// true\n"},{"name":"z_create_reply_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_reply_01_filetest\n\npackage z_create_reply_01_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateReply(cross(cur), 404, 1, 0, \"comment\")\n}\n\n// Error:\n// board does not exist with ID: 404\n"},{"name":"z_create_reply_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_reply_02_filetest\n\npackage z_create_reply_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateReply(cross(cur), bid, 404, 0, \"comment\")\n}\n\n// Error:\n// thread does not exist with ID: 404\n"},{"name":"z_create_reply_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_reply_03_filetest\n\npackage z_create_reply_03_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateReply(cross(cur), bid, tid, 404, \"comment\")\n}\n\n// Error:\n// reply does not exist with ID: 404\n"},{"name":"z_create_reply_04_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_reply_04_filetest\n\npackage z_create_reply_04_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\n\t// Hide thread by flagging it so reply can't be submitted\n\tboards2.FlagThread(cross(cur), bid, tid, \"reason\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateReply(cross(cur), bid, tid, 0, \"Test reply\")\n}\n\n// Error:\n// thread is hidden\n"},{"name":"z_create_reply_05_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_reply_05_filetest\n\npackage z_create_reply_05_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid      boards.ID\n\ttid, rid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"reply1\")\n\n\t// Hide thread by flagging it so reply of a reply can't be submitted\n\tboards2.FlagThread(cross(cur), bid, tid, \"reason\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateReply(cross(cur), bid, tid, rid, \"reply1.1\")\n}\n\n// Error:\n// thread is hidden\n"},{"name":"z_create_reply_06_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_reply_06_filetest\n\npackage z_create_reply_06_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid      boards.ID\n\ttid, rid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"thread\", \"thread\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"reply1\")\n\n\t// Hide reply by flagging it so sub reply can't be submitted\n\tboards2.FlagReply(cross(cur), bid, tid, rid, \"reason\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateReply(cross(cur), bid, tid, rid, \"reply1.1\")\n}\n\n// Error:\n// replying to a hidden or frozen reply is not allowed\n"},{"name":"z_create_reply_07_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_reply_07_filetest\n\npackage z_create_reply_07_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar (\n\tbid boards.ID\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tboards2.CreateReply(cross(cur), bid, tid, 0, \"Test reply\")\n}\n\n// Error:\n// unauthorized, user g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj doesn't have the required permission\n"},{"name":"z_create_reply_08_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_reply_08_filetest\n\npackage z_create_reply_08_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateReply(cross(cur), bid, tid, 0, \"\")\n}\n\n// Error:\n// body is empty\n"},{"name":"z_create_reply_09_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_reply_09_filetest\n\npackage z_create_reply_09_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner   address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tpath            = \"test-board/1/2\"\n\tcomment         = \"Second comment\"\n)\n\nvar (\n\tbid      boards.ID\n\ttid, rid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"First comment\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\trid2 := boards2.CreateReply(cross(cur), bid, tid, rid, comment)\n\n\t// Ensure that returned ID is right\n\tprintln(rid2 == 3)\n\n\t// Render content must contain the sub-reply\n\tcontent := boards2.Render(path)\n\tprintln(strings.Contains(content, \"\\n\u003e \u003e \"+comment))\n}\n\n// Output:\n// true\n// true\n"},{"name":"z_create_reply_10_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_reply_10_filetest\n\npackage z_create_reply_10_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner   address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tcomment         = \"Second comment\"\n)\n\nvar (\n\tbid      boards.ID\n\ttid, rid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"Parent comment\")\n\n\t// Flag parent post so it's hidden\n\tboards2.FlagReply(cross(cur), bid, tid, rid, \"Reason\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateReply(cross(cur), bid, tid, rid, \"Sub comment\")\n}\n\n// Error:\n// replying to a hidden or frozen reply is not allowed\n"},{"name":"z_create_reply_11_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_reply_11_filetest\n\npackage z_create_reply_11_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"foo\", \"bar\")\n\tboards2.FreezeThread(cross(cur), bid, tid)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// cannot reply to a frozen thread\n\tboards2.CreateReply(cross(cur), bid, tid, 0, \"foobar\")\n}\n\n// Error:\n// thread is frozen\n"},{"name":"z_create_reply_12_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_reply_12_filetest\n\npackage z_create_reply_12_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateReply(cross(cur), bid, tid, 0, strings.Repeat(\"x\", boards2.MaxReplyLength+1))\n}\n\n// Error:\n// reply is too long, maximum allowed is 10000 characters\n"},{"name":"z_create_reply_13_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_reply_13_filetest\n\n// A reply may now contain Markdown block structure (here a blockquote).\n// The write-time blacklist used to reject it; now the reply body renders\n// inside a \u003cgno-foreign\u003e sandbox, so its structure is contained and\n// cannot hijack realm chrome.\npackage z_create_reply_13_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Previously rejected (\"headings, blockquotes ... not allowed\").\n\tboards2.CreateReply(cross(cur), bid, tid, 0, \"\u003e Markdown blockquote\")\n\n\t// The reply body is wrapped in a gno-foreign sandbox at render time.\n\tcontent := boards2.Render(\"test-board/1\")\n\tprintln(strings.Contains(content, \"Markdown blockquote\") \u0026\u0026 strings.Contains(content, \"\u003cgno-foreign\u003e\"))\n}\n\n// Output:\n// true\n"},{"name":"z_create_reply_14_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_reply_14_filetest\n\n// Open board: Test creating a new reply as a non member user\npackage z_create_reply_14_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"chain\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner   address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser    address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tcomment         = \"Test Comment\"\n)\n\nvar (\n\tbid boards.ID // Operate on board DAO\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, true)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Title\", \"Body\")\n\n\t// Make sure user account has the required amount of GNOT for open board actions\n\ttesting.IssueCoins(user, chain.Coins{{\"ugnot\", 3_000_000_000}})\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Non members should be able to add replies\n\tboards2.CreateReply(cross(cur), bid, tid, 0, comment)\n\n\t// Render content must contain the reply\n\tcontent := boards2.Render(\"test123/1\")\n\tprintln(strings.Contains(content, \"\\n\u003e \"+comment))\n}\n\n// Output:\n// true\n"},{"name":"z_create_reply_15_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_reply_15_filetest\n\n// Open board: Test creating a new reply as a non member user that has no GNOT\npackage z_create_reply_15_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner   address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser    address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tcomment         = \"Test Comment\"\n)\n\nvar (\n\tbid boards.ID // Operate on board DAO\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, true)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Title\", \"Body\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Non members should be able to add replies only if they have enough GNOT\n\tboards2.CreateReply(cross(cur), bid, tid, 0, comment)\n}\n\n// Error:\n// caller is not allowed to comment: account amount is lower than 3000 GNOT\n"},{"name":"z_create_reply_16_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_reply_16_filetest\n\n// A reply may now contain a \u003cgno-form\u003e. The write-time blacklist used to\n// reject it; now the reply body renders inside a \u003cgno-foreign\u003e sandbox\n// whose inner renderer does not load forms (gnoweb safe-mode omits the\n// raw HTML at render).\npackage z_create_reply_16_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar bid, tid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Previously rejected (\"forms are not allowed in replies\").\n\tboards2.CreateReply(cross(cur), bid, tid, 0, \"\u003cgno-form\u003e\u003cgno-select name=\\\"foo\\\" value=\\\"\\\" /\u003e\u003c/gno-form\u003e\")\n\n\t// Accepted; the body is wrapped in a gno-foreign sandbox.\n\tcontent := boards2.Render(\"test-board/1\")\n\tprintln(strings.Contains(content, \"\u003cgno-foreign\u003e\"))\n}\n\n// Output:\n// true\n"},{"name":"z_create_repost_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_repost_00_filetest\n\npackage z_create_repost_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tsrcBID boards.ID\n\tdstBID boards.ID\n\tsrcTID boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tsrcBID = boards2.CreateBoard(cross(cur), \"src-board\", false, false)\n\tdstBID = boards2.CreateBoard(cross(cur), \"dst-board\", false, false)\n\n\tsrcTID = boards2.CreateThread(cross(cur), srcBID, \"Foo\", \"bar\")\n\tboards2.FlagThread(cross(cur), srcBID, srcTID, \"idk\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Repost should fail if source thread is flagged\n\tboards2.CreateRepost(cross(cur), srcBID, srcTID, dstBID, \"foo\", \"bar\")\n}\n\n// Error:\n// thread is hidden\n"},{"name":"z_create_repost_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_repost_01_filetest\n\npackage z_create_repost_01_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tsrcBID boards.ID\n\tdstBID boards.ID\n\tsrcTID boards.ID = 1024\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tsrcBID = boards2.CreateBoard(cross(cur), \"src-board\", false, false)\n\tdstBID = boards2.CreateBoard(cross(cur), \"dst-board\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Repost should fail if source thread doesn't exist\n\tboards2.CreateRepost(cross(cur), srcBID, srcTID, dstBID, \"foo\", \"bar\")\n}\n\n// Error:\n// thread does not exist with ID: 1024\n"},{"name":"z_create_repost_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_repost_02_filetest\n\npackage z_create_repost_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar (\n\tsrcBID boards.ID\n\tdstBID boards.ID\n\tsrcTID boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tsrcBID = boards2.CreateBoard(cross(cur), \"src-board\", false, false)\n\tdstBID = boards2.CreateBoard(cross(cur), \"dst-board\", false, false)\n\n\tsrcTID = boards2.CreateThread(cross(cur), srcBID, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tboards2.CreateRepost(cross(cur), srcBID, srcTID, dstBID, \"foo\", \"bar\")\n}\n\n// Error:\n// unauthorized, user g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj doesn't have the required permission\n"},{"name":"z_create_repost_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_repost_03_filetest\n\npackage z_create_repost_03_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tsrcBID boards.ID\n\tdstBID boards.ID\n\tsrcTID boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tsrcBID = boards2.CreateBoard(cross(cur), \"src-board\", false, false)\n\tdstBID = boards2.CreateBoard(cross(cur), \"dst-board\", false, false)\n\n\tsrcTID = boards2.CreateThread(cross(cur), srcBID, \"original title\", \"original text\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Success case\n\ttID := boards2.CreateRepost(cross(cur), srcBID, srcTID, dstBID, \"repost title\", \"repost text\")\n\tp := ufmt.Sprintf(\"dst-board/%s\", tID)\n\tout := boards2.Render(p)\n\n\tprintln(strings.Contains(out, \"original text\"))\n\tprintln(strings.Contains(out, \"repost title\"))\n\tprintln(strings.Contains(out, \"repost text\"))\n}\n\n// Output:\n// true\n// true\n// true\n"},{"name":"z_create_repost_04_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_repost_04_filetest\n\npackage z_create_repost_04_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tsrcBID boards.ID\n\tdstBID boards.ID\n\tsrcTID boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Create a board with a thread\n\torigBID := boards2.CreateBoard(cross(cur), \"origin-board\", false, false)\n\torigTID := boards2.CreateThread(cross(cur), origBID, \"title\", \"text\")\n\n\t// Create a second board and repost a thread using an empty title\n\tsrcBID = boards2.CreateBoard(cross(cur), \"source-board\", false, false)\n\tsrcTID = boards2.CreateRepost(cross(cur), origBID, origTID, srcBID, \"original title\", \"original text\")\n\n\t// Create a third board to try reposting the repost\n\tdstBID = boards2.CreateBoard(cross(cur), \"destination-board\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateRepost(cross(cur), srcBID, srcTID, dstBID, \"repost title\", \"repost text\")\n}\n\n// Error:\n// reposting a thread that is a repost is not allowed\n"},{"name":"z_create_thread_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_thread_00_filetest\n\npackage z_create_thread_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\ttitle         = \"Test Thread\"\n\tbody          = \"Test body\"\n\tpath          = \"test-board/1\"\n)\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\ttid := boards2.CreateThread(cross(cur), bid, title, body)\n\n\t// Ensure that returned ID is right\n\tprintln(tid == 1)\n\n\t// Thread should not be frozen by default\n\tprintln(boards2.IsThreadFrozen(bid, tid))\n\n\t// Render content must contains thread's title and body\n\tprintln(boards2.Render(path))\n}\n\n// Output:\n// true\n// false\n// # [Boards](/r/gnoland/boards2/v1) › [test\\-board](/r/gnoland/boards2/v1:test-board)\n// ## Test Thread\n//\n// **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC\n//\n//\n// \u003cgno-foreign\u003e\n// Test body\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/flag) • [Repost](/r/gnoland/boards2/v1:test-board/1/repost) • [Comment](/r/gnoland/boards2/v1:test-board/1/reply) • [Edit](/r/gnoland/boards2/v1:test-board/1/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteThread\u0026boardID=1\u0026threadID=1)\n"},{"name":"z_create_thread_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_thread_01_filetest\n\npackage z_create_thread_01_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateThread(cross(cur), 404, \"Foo\", \"bar\")\n}\n\n// Error:\n// board does not exist with ID: 404\n"},{"name":"z_create_thread_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_thread_02_filetest\n\npackage z_create_thread_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tboards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\n// Error:\n// unauthorized, user g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj doesn't have the required permission\n"},{"name":"z_create_thread_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_thread_03_filetest\n\npackage z_create_thread_03_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateThread(cross(cur), bid, \"\", \"bar\")\n}\n\n// Error:\n// title is empty\n"},{"name":"z_create_thread_04_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_thread_04_filetest\n\npackage z_create_thread_04_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateThread(cross(cur), bid, \"Foo\", \"\")\n}\n\n// Error:\n// thread body is required\n"},{"name":"z_create_thread_05_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_thread_05_filetest\n\n// Open board: Test creating a new thread as a non member user\npackage z_create_thread_05_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\ttitle         = \"Test Thread\"\n\tbody          = \"Test body\"\n)\n\nvar bid boards.ID // Operate on board DAO\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, true)\n\n\t// Make sure user account has the required amount of GNOT for open board actions\n\ttesting.IssueCoins(user, chain.Coins{{\"ugnot\", 3_000_000_000}})\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Non members should be able to create threads\n\ttid := boards2.CreateThread(cross(cur), bid, title, body)\n\n\t// Ensure that returned ID is right\n\tprintln(tid == 1)\n\n\t// Render content must contains thread's title and body\n\tprintln(boards2.Render(\"test123/1\"))\n}\n\n// Output:\n// true\n// # [Boards](/r/gnoland/boards2/v1) › [test123](/r/gnoland/boards2/v1:test123)\n// ## Test Thread\n//\n// **[g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj](/u/g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj)** · 2009-02-13 11:31pm UTC\n//\n//\n// \u003cgno-foreign\u003e\n// Test body\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test123/1/flag) • [Repost](/r/gnoland/boards2/v1:test123/1/repost) • [Comment](/r/gnoland/boards2/v1:test123/1/reply) • [Edit](/r/gnoland/boards2/v1:test123/1/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteThread\u0026boardID=1\u0026threadID=1)\n"},{"name":"z_create_thread_06_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_create_thread_06_filetest\n\n// Open board: Test creating a new thread as a non member user that has no GNOT\npackage z_create_thread_06_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar bid boards.ID // Operate on board DAO\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, true)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Non members should be able to create threads only if they have enough GNOT\n\tboards2.CreateThread(cross(cur), bid, \"Title\", \"Body\")\n}\n\n// Error:\n// caller is not allowed to create threads: account amount is lower than 3000 GNOT\n"},{"name":"z_delete_reply_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_delete_reply_00_filetest\n\npackage z_delete_reply_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid      boards.ID\n\ttid, rid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"body\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.DeleteReply(cross(cur), bid, tid, rid)\n\n\t// Ensure reply doesn't exist\n\tprintln(boards2.Render(\"test-board/1/2\"))\n}\n\n// Output:\n// Reply not found\n"},{"name":"z_delete_reply_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_delete_reply_01_filetest\n\npackage z_delete_reply_01_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.DeleteReply(cross(cur), 404, 1, 1)\n}\n\n// Error:\n// board does not exist with ID: 404\n"},{"name":"z_delete_reply_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_delete_reply_02_filetest\n\npackage z_delete_reply_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.DeleteReply(cross(cur), bid, 404, 1)\n}\n\n// Error:\n// thread does not exist with ID: 404\n"},{"name":"z_delete_reply_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_delete_reply_03_filetest\n\npackage z_delete_reply_03_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.DeleteReply(cross(cur), bid, tid, 404)\n}\n\n// Error:\n// reply does not exist with ID: 404\n"},{"name":"z_delete_reply_04_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_delete_reply_04_filetest\n\npackage z_delete_reply_04_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid      boards.ID\n\ttid, rid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"Parent\")\n\tboards2.CreateReply(cross(cur), bid, tid, rid, \"Child reply\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.DeleteReply(cross(cur), bid, tid, rid)\n\n\t// Render content must contain the releted message instead of reply's body\n\tprintln(boards2.Render(\"test-board/1/2\"))\n}\n\n// Output:\n// ## Foo\n//\n// **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC\n//\n//\n// \u003cgno-foreign\u003e\n// bar\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/flag) • [Repost](/r/gnoland/boards2/v1:test-board/1/repost) • [Comment](/r/gnoland/boards2/v1:test-board/1/reply) [1] • [Edit](/r/gnoland/boards2/v1:test-board/1/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteThread\u0026boardID=1\u0026threadID=1) • [Show all Replies](/r/gnoland/boards2/v1:test-board/1)\n//\n//\n// \u003e\n// \u003e **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC [\\#2](/r/gnoland/boards2/v1:test-board/1/2)\n// \u003e\n// \u003e\n// \u003e \u003cgno-foreign\u003e\n// \u003e ⚠ This comment has been deleted\n// \u003e \u003c/gno-foreign\u003e\n// \u003e\n// \u003e\n// \u003e\n// \u003e ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/2/flag) • [Reply](/r/gnoland/boards2/v1:test-board/1/2/reply) [1] • [Edit](/r/gnoland/boards2/v1:test-board/1/2/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteReply\u0026boardID=1\u0026replyID=2\u0026threadID=1)\n//\n// ---\n// Sort by: [newest first](/r/gnoland/boards2/v1:test-board/1/2?order=desc)\n// \u003e\n// \u003e \u003e\n// \u003e \u003e **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC [\\#3](/r/gnoland/boards2/v1:test-board/1/3)\n// \u003e \u003e\n// \u003e \u003e\n// \u003e \u003e \u003cgno-foreign\u003e\n// \u003e \u003e Child reply\n// \u003e \u003e \u003c/gno-foreign\u003e\n// \u003e \u003e\n// \u003e \u003e\n// \u003e \u003e\n// \u003e \u003e ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/3/flag) • [Reply](/r/gnoland/boards2/v1:test-board/1/3/reply) • [Edit](/r/gnoland/boards2/v1:test-board/1/3/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteReply\u0026boardID=1\u0026replyID=3\u0026threadID=1)\n"},{"name":"z_delete_reply_05_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_delete_reply_05_filetest\n\npackage z_delete_reply_05_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar (\n\tbid      boards.ID\n\ttid, rid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"body\")\n}\n\nfunc main(cur realm) {\n\t// Call using a user that has not permission to delete replies\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tboards2.DeleteReply(cross(cur), bid, tid, rid)\n}\n\n// Error:\n// unauthorized, user g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj doesn't have the required permission\n"},{"name":"z_delete_reply_06_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_delete_reply_06_filetest\n\npackage z_delete_reply_06_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner  address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tmember address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar (\n\tbid      boards.ID\n\ttid, rid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"body\")\n\n\t// Invite a member using a role with permission to delete replies\n\tboards2.InviteMember(cross(cur), bid, member, boards2.RoleAdmin)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(member))\n\n\tboards2.DeleteReply(cross(cur), bid, tid, rid)\n\n\t// Ensure reply doesn't exist\n\tprintln(boards2.Render(\"test-board/1/2\"))\n}\n\n// Output:\n// Reply not found\n"},{"name":"z_delete_reply_07_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_delete_reply_07_filetest\n\n// Open board: Test deleting a reply as the non member user that created it\npackage z_delete_reply_07_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar (\n\tbid      boards.ID // Operate on board DAO\n\ttid, rid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, true)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Title\", \"Body\")\n\n\t// Make sure user account has the required amount of GNOT for open board actions\n\ttesting.IssueCoins(user, chain.Coins{{\"ugnot\", 3_000_000_000}})\n\n\t// Create a new reply as a non member user\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"Comment\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Delete the reply as the non member user that created it\n\tboards2.DeleteReply(cross(cur), bid, tid, rid)\n\n\t// Ensure reply doesn't exist\n\tprintln(rid == 2)\n\tprintln(boards2.Render(\"test123/1/2\"))\n}\n\n// Output:\n// true\n// Reply not found\n"},{"name":"z_delete_reply_08_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_delete_reply_08_filetest\n\n// Open board: Test deleting a reply of another non member user\npackage z_delete_reply_08_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tuser2 address = \"g125t352u4pmdrr57emc4pe04y40sknr5ztng5mt\"\n)\n\nvar (\n\tbid      boards.ID // Operate on board DAO\n\ttid, rid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, true)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Title\", \"Body\")\n\n\t// Make sure user account has the required amount of GNOT for open board actions\n\ttesting.IssueCoins(user, chain.Coins{{\"ugnot\", 3_000_000_000}})\n\n\t// Create a new reply as a non member user\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"Comment\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user2))\n\n\t// Try to delete the reply of another non member user\n\tboards2.DeleteReply(cross(cur), bid, tid, rid)\n}\n\n// Error:\n// unauthorized, user g125t352u4pmdrr57emc4pe04y40sknr5ztng5mt doesn't have the required permission\n"},{"name":"z_delete_reply_09_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_delete_reply_09_filetest\n\n// Hard-deleting a childless DIRECT thread reply removes it from the thread's\n// direct-children list (not just the flat AllReplies index), so the threaded\n// view doesn't render a ghost comment and the reply count stays accurate.\npackage z_delete_reply_09_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\ttid boards.ID\n\trb  boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"OP body\")\n\tboards2.CreateReply(cross(cur), bid, tid, 0, \"reply-A\")      // #2, direct, leaf\n\trb = boards2.CreateReply(cross(cur), bid, tid, 0, \"reply-B\") // #3, direct, leaf\n\tboards2.CreateReply(cross(cur), bid, tid, 0, \"reply-C\")      // #4, direct, leaf\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.DeleteReply(cross(cur), bid, tid, rb) // hard delete the leaf\n\n\tout := boards2.Render(\"test-board/1\")\n\t// A and C remain; B must be fully gone (no ghost) from the threaded view.\n\tok := strings.Contains(out, \"reply-A\") \u0026\u0026\n\t\tstrings.Contains(out, \"reply-C\") \u0026\u0026\n\t\t!strings.Contains(out, \"reply-B\")\n\tprintln(ok)\n}\n\n// Output:\n// true\n"},{"name":"z_delete_thread_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_delete_thread_00_filetest\n\npackage z_delete_thread_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\ttitle         = \"Test Thread\"\n\tbody          = \"Test body\"\n)\n\nvar (\n\tbid boards.ID\n\tpid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\tpid = boards2.CreateThread(cross(cur), bid, title, body)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.DeleteThread(cross(cur), bid, pid)\n\n\t// Ensure thread doesn't exist\n\tprintln(boards2.Render(\"test-board/1\"))\n}\n\n// Output:\n// Thread not found\n"},{"name":"z_delete_thread_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_delete_thread_01_filetest\n\npackage z_delete_thread_01_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.DeleteThread(cross(cur), 404, 1)\n}\n\n// Error:\n// board does not exist with ID: 404\n"},{"name":"z_delete_thread_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_delete_thread_02_filetest\n\npackage z_delete_thread_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.DeleteThread(cross(cur), bid, 404)\n}\n\n// Error:\n// thread does not exist with ID: 404\n"},{"name":"z_delete_thread_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_delete_thread_03_filetest\n\npackage z_delete_thread_03_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar (\n\tbid boards.ID\n\tpid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\tpid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\t// Call using a user that has not permission to delete threads\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tboards2.DeleteThread(cross(cur), bid, pid)\n}\n\n// Error:\n// unauthorized, user g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj doesn't have the required permission\n"},{"name":"z_delete_thread_04_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_delete_thread_04_filetest\n\npackage z_delete_thread_04_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner  address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tmember address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar (\n\tbid boards.ID\n\tpid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\tpid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\n\t// Invite a member using a role with permission to delete threads\n\tboards2.InviteMember(cross(cur), bid, member, boards2.RoleAdmin)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(member))\n\n\tboards2.DeleteThread(cross(cur), bid, pid)\n\n\t// Ensure thread doesn't exist\n\tprintln(boards2.Render(\"test-board/1\"))\n}\n\n// Output:\n// Thread not found\n"},{"name":"z_delete_thread_05_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_delete_thread_05_filetest\n\n// Open board: Test deleting a thread as the non member user that created it\npackage z_delete_thread_05_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar (\n\tbid boards.ID // Operate on board DAO\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, true)\n\n\t// Make sure user account has the required amount of GNOT for open board actions\n\ttesting.IssueCoins(user, chain.Coins{{\"ugnot\", 3_000_000_000}})\n\n\t// Create a new reply as a non member user\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttid = boards2.CreateThread(cross(cur), bid, \"Title\", \"Body\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Delete the thread as the non member user that created it\n\tboards2.DeleteThread(cross(cur), bid, tid)\n\n\t// Ensure reply doesn't exist\n\tprintln(tid == 1)\n\tprintln(boards2.Render(\"test123/1\"))\n}\n\n// Output:\n// true\n// Thread not found\n"},{"name":"z_delete_thread_06_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_delete_thread_06_filetest\n\n// Open board: Test deleting a reply of another non member user\npackage z_delete_thread_06_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tuser2 address = \"g125t352u4pmdrr57emc4pe04y40sknr5ztng5mt\"\n)\n\nvar (\n\tbid boards.ID // Operate on board DAO\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, true)\n\n\t// Make sure user account has the required amount of GNOT for open board actions\n\ttesting.IssueCoins(user, chain.Coins{{\"ugnot\", 3_000_000_000}})\n\n\t// Create a new reply as a non member user\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttid = boards2.CreateThread(cross(cur), bid, \"Title\", \"Body\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user2))\n\n\t// Try to delete the thread of another non member user\n\tboards2.DeleteThread(cross(cur), bid, tid)\n}\n\n// Error:\n// unauthorized, user g125t352u4pmdrr57emc4pe04y40sknr5ztng5mt doesn't have the required permission\n"},{"name":"z_edit_reply_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_edit_reply_00_filetest\n\npackage z_edit_reply_00_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tbody          = \"Test reply\"\n\tpath          = \"test-board/1/2\"\n)\n\nvar (\n\tbid      boards.ID\n\ttid, rid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"body\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.EditReply(cross(cur), bid, tid, rid, body)\n\n\t// Render content must contain the modified reply\n\tcontent := boards2.Render(path)\n\tprintln(strings.Contains(content, \"\\n\u003e \"+body))\n}\n\n// Output:\n// true\n"},{"name":"z_edit_reply_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_edit_reply_01_filetest\n\npackage z_edit_reply_01_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tbody          = \"Test reply\"\n\tpath          = \"test-board/1/2\"\n)\n\nvar (\n\tbid      boards.ID\n\ttid, rid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\n\t// Create a reply and a sub reply\n\tparentRID := boards2.CreateReply(cross(cur), bid, tid, 0, \"Parent\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, parentRID, \"Child\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.EditReply(cross(cur), bid, tid, rid, body)\n\n\t// Render content must contain the modified reply\n\tcontent := boards2.Render(path)\n\tprintln(strings.Contains(content, \"\\n\u003e \u003e \"+body))\n}\n\n// Output:\n// true\n"},{"name":"z_edit_reply_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_edit_reply_02_filetest\n\npackage z_edit_reply_02_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.EditReply(cross(cur), 404, 1, 0, \"body\")\n}\n\n// Error:\n// board does not exist with ID: 404\n"},{"name":"z_edit_reply_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_edit_reply_03_filetest\n\npackage z_edit_reply_03_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.EditReply(cross(cur), bid, 404, 0, \"body\")\n}\n\n// Error:\n// thread does not exist with ID: 404\n"},{"name":"z_edit_reply_04_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_edit_reply_04_filetest\n\npackage z_edit_reply_04_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.EditReply(cross(cur), bid, tid, 404, \"body\")\n}\n\n// Error:\n// reply does not exist with ID: 404\n"},{"name":"z_edit_reply_05_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_edit_reply_05_filetest\n\npackage z_edit_reply_05_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar (\n\tbid      boards.ID\n\ttid, rid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"body\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tboards2.EditReply(cross(cur), bid, tid, rid, \"new body\")\n}\n\n// Error:\n// only the reply creator is allowed to edit it\n"},{"name":"z_edit_reply_06_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_edit_reply_06_filetest\n\npackage z_edit_reply_06_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar (\n\tbid      boards.ID\n\ttid, rid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"body\")\n\n\t// Flag the reply so it's hidden\n\tboards2.FlagReply(cross(cur), bid, tid, rid, \"reason\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.EditReply(cross(cur), bid, tid, rid, \"body\")\n}\n\n// Error:\n// reply is hidden\n"},{"name":"z_edit_reply_07_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_edit_reply_07_filetest\n\npackage z_edit_reply_07_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid      boards.ID\n\ttid, rid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"body\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.EditReply(cross(cur), bid, tid, rid, \"\")\n}\n\n// Error:\n// body is empty\n"},{"name":"z_edit_reply_08_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_edit_reply_08_filetest\n\n// Editing a reply to contain a \u003cgno-form\u003e is now accepted: the\n// write-time blacklist relaxation applies to edits too (EditReply shares\n// the validator). The body renders inside a \u003cgno-foreign\u003e sandbox.\npackage z_edit_reply_08_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar bid, tid, rid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"body\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Previously rejected on edit (\"forms are not allowed in replies\").\n\tboards2.EditReply(cross(cur), bid, tid, rid, \"\u003cgno-form\u003e\u003cgno-select name=\\\"foo\\\" value=\\\"\\\" /\u003e\u003c/gno-form\u003e\")\n\n\tcontent := boards2.Render(\"test-board/1\")\n\tprintln(strings.Contains(content, \"\u003cgno-foreign\u003e\"))\n}\n\n// Output:\n// true\n"},{"name":"z_edit_thread_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_edit_thread_00_filetest\n\npackage z_edit_thread_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\ttitle         = \"Test Thread\"\n\tbody          = \"Test body\"\n\tpath          = \"test-board/1\"\n)\n\nvar (\n\tbid boards.ID\n\tpid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\tpid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.EditThread(cross(cur), bid, pid, title, body)\n\n\tprintln(boards2.Render(path))\n}\n\n// Output:\n// # [Boards](/r/gnoland/boards2/v1) › [test\\-board](/r/gnoland/boards2/v1:test-board)\n// ## Test Thread\n//\n// **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC\n//\n//\n// \u003cgno-foreign\u003e\n// Test body\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/flag) • [Repost](/r/gnoland/boards2/v1:test-board/1/repost) • [Comment](/r/gnoland/boards2/v1:test-board/1/reply) • [Edit](/r/gnoland/boards2/v1:test-board/1/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteThread\u0026boardID=1\u0026threadID=1)\n"},{"name":"z_edit_thread_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_edit_thread_01_filetest\n\npackage z_edit_thread_01_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\tpid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\tpid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.EditThread(cross(cur), bid, pid, \"\", \"bar\")\n}\n\n// Error:\n// title is empty\n"},{"name":"z_edit_thread_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_edit_thread_02_filetest\n\npackage z_edit_thread_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\tpid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\tpid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.EditThread(cross(cur), bid, pid, \"Foo\", \"\")\n}\n\n// Error:\n// body is empty\n"},{"name":"z_edit_thread_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_edit_thread_03_filetest\n\npackage z_edit_thread_03_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.EditThread(cross(cur), 404, 1, \"Foo\", \"bar\")\n}\n\n// Error:\n// board does not exist with ID: 404\n"},{"name":"z_edit_thread_04_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_edit_thread_04_filetest\n\npackage z_edit_thread_04_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\tpid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\tpid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.EditThread(cross(cur), bid, pid, \"Foo\", \"\")\n}\n\n// Error:\n// body is empty\n"},{"name":"z_edit_thread_05_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_edit_thread_05_filetest\n\npackage z_edit_thread_05_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar (\n\tbid boards.ID\n\tpid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\tpid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tboards2.EditThread(cross(cur), bid, pid, \"Foo\", \"bar\")\n}\n\n// Error:\n// unauthorized, user g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj doesn't have the required permission\n"},{"name":"z_edit_thread_06_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_edit_thread_06_filetest\n\npackage z_edit_thread_06_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tadmin address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\ttitle         = \"Test Thread\"\n\tbody          = \"Test body\"\n\tpath          = \"test-board/1\"\n)\n\nvar (\n\tbid boards.ID\n\tpid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\tpid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\n\t// Invite a member using a role with permission to edit threads\n\tboards2.InviteMember(cross(cur), bid, admin, boards2.RoleAdmin)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\n\tboards2.EditThread(cross(cur), bid, pid, title, body)\n\n\tprintln(boards2.Render(path))\n}\n\n// Output:\n// # [Boards](/r/gnoland/boards2/v1) › [test\\-board](/r/gnoland/boards2/v1:test-board)\n// ## Test Thread\n//\n// **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC\n//\n//\n// \u003cgno-foreign\u003e\n// Test body\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/flag) • [Repost](/r/gnoland/boards2/v1:test-board/1/repost) • [Comment](/r/gnoland/boards2/v1:test-board/1/reply) • [Edit](/r/gnoland/boards2/v1:test-board/1/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteThread\u0026boardID=1\u0026threadID=1)\n"},{"name":"z_edit_thread_07_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_edit_thread_07_filetest\n\npackage z_edit_thread_07_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid   boards.ID\n\tpid   boards.ID\n\ttitle = strings.Repeat(\"X\", boards2.MaxThreadTitleLength+1)\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\tpid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.EditThread(cross(cur), bid, pid, title, \"bar\")\n}\n\n// Error:\n// title is too long, maximum allowed is 100 characters\n"},{"name":"z_flag_reply_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_reply_00_filetest\n\npackage z_flag_reply_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid      boards.ID\n\trid, tid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"body\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.FlagReply(cross(cur), bid, tid, rid, \"Reason\")\n\n\t// Render content must contain a message about the hidden reply\n\tprintln(boards2.Render(\"test-board/1/2\"))\n}\n\n// Output:\n// ## Foo\n//\n// **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC\n//\n//\n// \u003cgno-foreign\u003e\n// bar\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/flag) • [Repost](/r/gnoland/boards2/v1:test-board/1/repost) • [Comment](/r/gnoland/boards2/v1:test-board/1/reply) [1] • [Edit](/r/gnoland/boards2/v1:test-board/1/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteThread\u0026boardID=1\u0026threadID=1) • [Show all Replies](/r/gnoland/boards2/v1:test-board/1)\n//\n//\n// \u003e\n// \u003e **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC [\\#2](/r/gnoland/boards2/v1:test-board/1/2)\n// \u003e ⚠ Reply is hidden as it has been flagged as [inappropriate](/r/gnoland/boards2/v1:test-board/1/2/flagging-reasons)\n"},{"name":"z_flag_reply_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_reply_01_filetest\n\npackage z_flag_reply_01_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.FlagReply(cross(cur), 404, 1, 1, \"Reason\")\n}\n\n// Error:\n// board does not exist with ID: 404\n"},{"name":"z_flag_reply_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_reply_02_filetest\n\npackage z_flag_reply_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.FlagReply(cross(cur), bid, 404, 1, \"Reason\")\n}\n\n// Error:\n// thread does not exist with ID: 404\n"},{"name":"z_flag_reply_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_reply_03_filetest\n\npackage z_flag_reply_03_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.FlagReply(cross(cur), bid, tid, 404, \"Reason\")\n}\n\n// Error:\n// reply does not exist with ID: 404\n"},{"name":"z_flag_reply_04_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_reply_04_filetest\n\npackage z_flag_reply_04_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid      boards.ID\n\trid, tid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"body\")\n\tboards2.FlagReply(cross(cur), bid, tid, rid, \"Reason\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.FlagReply(cross(cur), bid, tid, rid, \"Reason\")\n}\n\n// Error:\n// flagging hidden comments or replies is not allowed\n"},{"name":"z_flag_reply_05_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_reply_05_filetest\n\npackage z_flag_reply_05_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar (\n\tbid      boards.ID\n\trid, tid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"body\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tboards2.FlagReply(cross(cur), bid, tid, rid, \"Reason\")\n}\n\n// Error:\n// unauthorized, user g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj doesn't have the required permission\n"},{"name":"z_flag_reply_06_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_reply_06_filetest\n\npackage z_flag_reply_06_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tmoderator address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar (\n\tbid      boards.ID\n\trid, tid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"body\")\n\n\t// Invite a member using a role with permission to flag replies\n\tboards2.InviteMember(cross(cur), bid, moderator, boards2.RoleModerator)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(moderator))\n\n\tboards2.FlagReply(cross(cur), bid, tid, rid, \"Reason\")\n\n\t// Render content must contain a message about the hidden reply\n\tprintln(boards2.Render(\"test-board/1/2\"))\n}\n\n// Output:\n// ## Foo\n//\n// **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC\n//\n//\n// \u003cgno-foreign\u003e\n// bar\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/flag) • [Repost](/r/gnoland/boards2/v1:test-board/1/repost) • [Comment](/r/gnoland/boards2/v1:test-board/1/reply) [1] • [Edit](/r/gnoland/boards2/v1:test-board/1/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteThread\u0026boardID=1\u0026threadID=1) • [Show all Replies](/r/gnoland/boards2/v1:test-board/1)\n//\n//\n// \u003e\n// \u003e **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC [\\#2](/r/gnoland/boards2/v1:test-board/1/2)\n// \u003e ⚠ Reply is hidden as it has been flagged as [inappropriate](/r/gnoland/boards2/v1:test-board/1/2/flagging-reasons)\n"},{"name":"z_flag_reply_07_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_reply_07_filetest\n\npackage z_flag_reply_07_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tmoderator address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar (\n\tbid      boards.ID\n\trid, tid boards.ID\n)\n\nfunc init(cur realm) {\n\t// Created a board with flagging threshold greater than 1\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\tboards2.SetFlaggingThreshold(cross(cur), bid, 2)\n\n\t// Create a reply so the realm owner can flag and hide it with a single flag\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"body\")\n\t// Also freeze board to make sure that realm owner can still flag the reply\n\tboards2.FreezeBoard(cross(cur), bid)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.FlagReply(cross(cur), bid, tid, rid, \"Reason\")\n\n\t// Render content must contain a message about the hidden reply\n\tprintln(boards2.Render(\"test-board/1/2\"))\n}\n\n// Output:\n// ## Foo\n//\n// **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC\n//\n//\n// \u003cgno-foreign\u003e\n// bar\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/flag) • [Repost](/r/gnoland/boards2/v1:test-board/1/repost) • [Show all Replies](/r/gnoland/boards2/v1:test-board/1)\n//\n//\n// \u003e\n// \u003e **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC [\\#2](/r/gnoland/boards2/v1:test-board/1/2)\n// \u003e ⚠ Reply is hidden as it has been flagged as [inappropriate](/r/gnoland/boards2/v1:test-board/1/2/flagging-reasons)\n"},{"name":"z_flag_reply_08_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_reply_08_filetest\n\npackage z_flag_reply_08_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid      boards.ID\n\trid, tid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"body\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.FlagReply(cross(cur), bid, tid, rid, \"\")\n}\n\n// Error:\n// flagging reason is required\n"},{"name":"z_flag_reply_09_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_reply_09_filetest\n\n// A flag reason is user-supplied (only trimmed at write). The flagging-reasons\n// table must escape it so a reason can't inject markdown (links/images) or HTML\n// into the view other moderators see.\npackage z_flag_reply_09_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid      boards.ID\n\trid, tid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"body\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.FlagReply(cross(cur), bid, tid, rid, \"![pwn](https://evil/x.png) [click](https://evil)\")\n\n\tout := boards2.Render(\"test-board/1/2/flagging-reasons\")\n\t// Reason text is shown but escaped — no live markdown image/link syntax.\n\tok := strings.Contains(out, \"pwn\") \u0026\u0026\n\t\t!strings.Contains(out, \"![pwn]\") \u0026\u0026\n\t\t!strings.Contains(out, \"](https://evil)\")\n\tprintln(ok)\n}\n\n// Output:\n// true\n"},{"name":"z_flag_thread_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_thread_00_filetest\n\npackage z_flag_thread_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tmoderator address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar (\n\tbid boards.ID\n\tpid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\n\t// Invite a moderator to the new board\n\tboards2.InviteMember(cross(cur), bid, moderator, boards2.RoleModerator)\n\n\t// Create a new thread as a moderator\n\tpid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Flag thread as owner\n\tboards2.FlagThread(cross(cur), bid, pid, \"Reason\")\n\n\t// Ensure thread is not listed\n\tprintln(boards2.Render(\"test-board\"))\n}\n\n// Output:\n// # [Boards](/r/gnoland/boards2/v1) › test-board\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) on 2009-02-13 11:31pm UTC, #1\n// ↳ [Create Thread](/r/gnoland/boards2/v1:test-board/create-thread) • [Request Invite](/r/gnoland/boards2/v1$help\u0026func=RequestInvite\u0026boardID=1) • [Manage Board](?menu=manageBoard)\n//\n// ---\n// ### This board doesn't have any threads\n// Do you want to [start a new conversation](/r/gnoland/boards2/v1:test-board/create-thread) in this board?\n"},{"name":"z_flag_thread_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_thread_01_filetest\n\npackage z_flag_thread_01_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.FlagThread(cross(cur), 404, 1, \"Reason\")\n}\n\n// Error:\n// board does not exist with ID: 404\n"},{"name":"z_flag_thread_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_thread_02_filetest\n\npackage z_flag_thread_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar (\n\tbid boards.ID\n\tpid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\tpid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\t// Make the next call as an uninvited user\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tboards2.FlagThread(cross(cur), bid, pid, \"Reason\")\n}\n\n// Error:\n// unauthorized, user g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj doesn't have the required permission\n"},{"name":"z_flag_thread_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_thread_03_filetest\n\npackage z_flag_thread_03_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.FlagThread(cross(cur), bid, 404, \"Reason\")\n}\n\n// Error:\n// thread not found\n"},{"name":"z_flag_thread_04_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_thread_04_filetest\n\npackage z_flag_thread_04_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\tpid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\tpid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\tboards2.FlagThread(cross(cur), bid, pid, \"Reason\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.FlagThread(cross(cur), bid, pid, \"Reason\")\n}\n\n// Error:\n// flagging hidden threads is not allowed\n"},{"name":"z_flag_thread_05_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_thread_05_filetest\n\npackage z_flag_thread_05_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tmoderator address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar (\n\tbid boards.ID\n\tpid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\tpid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\n\t// Invite a member using a role with permission to flag threads\n\tboards2.InviteMember(cross(cur), bid, moderator, boards2.RoleModerator)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(moderator))\n\n\t// Flag thread as moderator\n\tboards2.FlagThread(cross(cur), bid, pid, \"Reason\")\n\n\t// Ensure that original thread content not visible\n\tprintln(boards2.Render(\"test-board/1\"))\n}\n\n// Output:\n// ⚠ Thread has been flagged as [inappropriate](/r/gnoland/boards2/v1:test-board/1/flagging-reasons)\n"},{"name":"z_flag_thread_06_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_thread_06_filetest\n\npackage z_flag_thread_06_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tmoderator address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar (\n\tbid boards.ID\n\tpid boards.ID\n)\n\nfunc init(cur realm) {\n\t// Created a board with a specific flagging threshold\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\tboards2.SetFlaggingThreshold(cross(cur), bid, 2)\n\n\t// Invite a moderator to the new board\n\tboards2.InviteMember(cross(cur), bid, moderator, boards2.RoleModerator)\n\n\t// Create a new thread and flag it as a moderator\n\ttesting.SetRealm(testing.NewUserRealm(moderator))\n\tpid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\tboards2.FlagThread(cross(cur), bid, pid, \"Reason\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(moderator))\n\n\tboards2.FlagThread(cross(cur), bid, pid, \"Reason\")\n}\n\n// Error:\n// post has been already flagged by g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\n"},{"name":"z_flag_thread_07_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_thread_07_filetest\n\npackage z_flag_thread_07_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\tpid boards.ID\n)\n\nfunc init(cur realm) {\n\t// Created a board with flagging threshold greater than 1\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\tboards2.SetFlaggingThreshold(cross(cur), bid, 2)\n\n\t// Create a thread so the realm owner can flag and hide it with a single flag\n\tpid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n\t// Also freeze board to make sure that realm owner can still flag the thread\n\tboards2.FreezeBoard(cross(cur), bid)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.FlagThread(cross(cur), bid, pid, \"Reason\")\n\n\t// Ensure that original thread content not visible\n\tprintln(boards2.Render(\"test-board/1\"))\n}\n\n// Output:\n// ⚠ Thread has been flagged as [inappropriate](/r/gnoland/boards2/v1:test-board/1/flagging-reasons)\n"},{"name":"z_flag_thread_08_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_flag_thread_08_filetest\n\npackage z_flag_thread_08_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\tpid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\tpid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.FlagThread(cross(cur), bid, pid, \"\")\n}\n\n// Error:\n// flagging reason is required\n"},{"name":"z_freeze_board_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_freeze_board_00_filetest\n\npackage z_freeze_board_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.FreezeBoard(cross(cur), bid)\n\n\tprintln(boards2.IsBoardFrozen(bid))\n}\n\n// Output:\n// true\n"},{"name":"z_freeze_board_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_freeze_board_01_filetest\n\npackage z_freeze_board_01_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\tboards2.FreezeBoard(cross(cur), bid)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.FreezeBoard(cross(cur), bid)\n}\n\n// Error:\n// board is frozen\n"},{"name":"z_freeze_thread_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_freeze_thread_00_filetest\n\npackage z_freeze_thread_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"foo\", \"bar\")\n\n\tboards2.FreezeBoard(cross(cur), bid)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Attempt to freeze a thread on frozen board\n\tboards2.FreezeThread(cross(cur), bid, tid)\n}\n\n// Error:\n// board is frozen\n"},{"name":"z_freeze_thread_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_freeze_thread_01_filetest\n\npackage z_freeze_thread_01_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"foo\", \"bar\")\n\n\tboards2.FreezeThread(cross(cur), bid, tid)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Attempt to freeze a frozen thread\n\tboards2.FreezeThread(cross(cur), bid, tid)\n}\n\n// Error:\n// thread is frozen\n"},{"name":"z_freeze_thread_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_freeze_thread_02_filetest\n\npackage z_freeze_thread_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"foo\", \"bar\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.FreezeThread(cross(cur), bid, tid)\n\n\tprintln(boards2.IsThreadFrozen(bid, tid))\n}\n\n// Output:\n// true\n"},{"name":"z_get_board_id_from_name_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_get_board_id_from_name_00_filetest\n\npackage z_get_board_id_from_name_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tname          = \"test123\"\n)\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), name, false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tbid2, found := boards2.GetBoardIDFromName(cross(cur), name)\n\n\tprintln(found)\n\tprintln(bid2 == bid)\n}\n\n// Output:\n// true\n// true\n"},{"name":"z_get_board_id_from_name_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_get_board_id_from_name_01_filetest\n\npackage z_get_board_id_from_name_01_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tbid, found := boards2.GetBoardIDFromName(cross(cur), \"foobar\")\n\n\tprintln(found)\n\tprintln(bid == 0)\n}\n\n// Output:\n// false\n// true\n"},{"name":"z_hub_0_a_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_0_a_filetest\n\n// Test default board values\npackage z_hub_0_a_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar boardID boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\nfunc main(cur realm) {\n\tboard, found := boards2.GetBoard(uint64(boardID))\n\tif !found {\n\t\treturn\n\t}\n\n\tprintln(board.ID())\n\tprintln(board.Name())\n\tprintln(board.Aliases())\n\tprintln(board.Readonly())\n\tprintln(board.ThreadCount())\n\tprintln(board.MemberCount())\n\tprintln(board.Creator())\n\tprintln(board.CreatedAt())\n\tprintln(board.UpdatedAt())\n}\n\n// Output:\n// 1\n// test123\n// (nil []string)\n// false\n// 0\n// 1\n// g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\n// 1234567890\n// 0\n"},{"name":"z_hub_0_b_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_0_b_filetest\n\n// Test non default board values\npackage z_hub_0_b_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar boardID boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\t// Invite member\n\tboards2.InviteMember(cross(cur), boardID, \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\", \"admin\")\n\n\t// Rename board\n\tboards2.RenameBoard(cross(cur), \"test123\", \"foo123\")\n\n\t// Create a thread\n\tboards2.CreateThread(cross(cur), boardID, \"Title\", \"Body\")\n\n\t// Freeze board\n\tboards2.FreezeBoard(cross(cur), boardID)\n}\n\nfunc main(cur realm) {\n\tboard, found := boards2.GetBoard(uint64(boardID))\n\tif !found {\n\t\treturn\n\t}\n\n\tprintln(board.ID())\n\tprintln(board.Name())\n\tprintln(board.Aliases())\n\tprintln(board.Readonly())\n\tprintln(board.ThreadCount())\n\tprintln(board.MemberCount())\n\tprintln(board.Creator())\n\tprintln(board.CreatedAt())\n\tprintln(board.UpdatedAt())\n}\n\n// Output:\n// 1\n// foo123\n// slice[(\"test123\" string)]\n// true\n// 1\n// 2\n// g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\n// 1234567890\n// 1234567890\n"},{"name":"z_hub_0_c_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_0_c_filetest\n\n// Test that reads are open to any caller\npackage z_hub_0_c_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar boardID boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboardID = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\nfunc main(cur realm) {\n\t// The read API performs no caller authorization: an EOA and a realm\n\t// outside the Boards2 namespace must both be able to read.\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\t_, found := boards2.GetBoard(uint64(boardID))\n\tprintln(\"user realm:\", found)\n\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/unrelated/caller\"))\n\t_, found = boards2.GetBoard(uint64(boardID))\n\tprintln(\"unrelated realm:\", found)\n\n\tprintln(\"threads:\", len(boards2.GetThreads(uint64(boardID), 0, 10)))\n\tprintln(\"members:\", len(boards2.GetMembers(uint64(boardID), 0, 10)))\n}\n\n// Output:\n// user realm: true\n// unrelated realm: true\n// threads: 0\n// members: 1\n"},{"name":"z_hub_1_a_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_1_a_filetest\n\n// Test default thread values\npackage z_hub_1_a_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar (\n\tboardID  boards.ID\n\tthreadID boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID = boards2.CreateBoard(cross(cur), \"origin123\", false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"Title\", \"Body\")\n}\n\nfunc main(cur realm) {\n\tthread, found := boards2.GetThread(uint64(boardID), uint64(threadID))\n\tif !found {\n\t\treturn\n\t}\n\n\tprintln(thread.ID())\n\tprintln(thread.OriginalBoardID())\n\tprintln(thread.OriginalThreadID())\n\tprintln(thread.BoardID())\n\tprintln(thread.Title())\n\tprintln(thread.Body())\n\tprintln(thread.Hidden())\n\tprintln(thread.Readonly())\n\tprintln(thread.CommentCount())\n\tprintln(thread.RepostCount())\n\tprintln(thread.FlagCount())\n\tprintln(thread.Creator())\n\tprintln(thread.CreatedAt())\n\tprintln(thread.UpdatedAt())\n}\n\n// Output:\n// 1\n// 0\n// 0\n// 1\n// Title\n// Body\n// false\n// false\n// 0\n// 0\n// 0\n// g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\n// 1234567890\n// 0\n"},{"name":"z_hub_1_b_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_1_b_filetest\n\n// Test non default thread values\npackage z_hub_1_b_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar (\n\tboardID  boards.ID\n\tthreadID boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"Title\", \"Body\")\n\n\t// Create another board and repost thread\n\tdstBoardID := boards2.CreateBoard(cross(cur), \"destination123\", false, false)\n\tboards2.CreateRepost(cross(cur), boardID, threadID, dstBoardID, \"Title\", \"Body\")\n\n\t// Edit thread\n\tboards2.EditThread(cross(cur), boardID, threadID, \"Foo\", \"Bar\")\n\n\t// Add a comment to the thread\n\tboards2.CreateReply(cross(cur), boardID, threadID, 0, \"Comment\")\n\n\t// Freeze thread\n\tboards2.FreezeThread(cross(cur), boardID, threadID)\n\n\t// Flag thread\n\tboards2.FlagThread(cross(cur), boardID, threadID, \"Reason\")\n}\n\nfunc main(cur realm) {\n\tthread, found := boards2.GetThread(uint64(boardID), uint64(threadID))\n\tif !found {\n\t\treturn\n\t}\n\n\tprintln(thread.ID())\n\tprintln(thread.OriginalBoardID())  // Only reposts have an original board ID\n\tprintln(thread.OriginalThreadID()) // Only reposts have an original thread ID\n\tprintln(thread.BoardID())\n\tprintln(thread.Title())\n\tprintln(thread.Body())\n\tprintln(thread.Hidden())\n\tprintln(thread.Readonly())\n\tprintln(thread.CommentCount())\n\tprintln(thread.RepostCount())\n\tprintln(thread.FlagCount())\n\tprintln(thread.Creator())\n\tprintln(thread.CreatedAt())\n\tprintln(thread.UpdatedAt())\n}\n\n// Output:\n// 1\n// 0\n// 0\n// 1\n// Foo\n// Bar\n// true\n// true\n// 1\n// 1\n// 1\n// g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\n// 1234567890\n// 1234567890\n"},{"name":"z_hub_1_c_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_1_c_filetest\n\n// Test non default reposted thread values\npackage z_hub_1_c_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar (\n\tboardID  boards.ID\n\tthreadID boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tsrcBoardID := boards2.CreateBoard(cross(cur), \"origin123\", false, false)\n\n\t// Create two threads where the second is the one to repost\n\tboards2.CreateThread(cross(cur), srcBoardID, \"Title1\", \"Body1\")\n\tsrcThreadID := boards2.CreateThread(cross(cur), srcBoardID, \"Title2\", \"Body2\") // ID = 2\n\n\t// Create repost\n\tboardID = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\tthreadID = boards2.CreateRepost(cross(cur), srcBoardID, srcThreadID, boardID, \"Title\", \"Body\")\n\n\t// Edit repost\n\tboards2.EditThread(cross(cur), boardID, threadID, \"Foo\", \"Bar\")\n\n\t// Add a comment to the repost\n\tboards2.CreateReply(cross(cur), boardID, threadID, 0, \"Comment\")\n\n\t// Freeze repost\n\tboards2.FreezeThread(cross(cur), boardID, threadID)\n\n\t// Flag repost\n\tboards2.FlagThread(cross(cur), boardID, threadID, \"Reason\")\n}\n\nfunc main(cur realm) {\n\tthread, found := boards2.GetThread(uint64(boardID), uint64(threadID))\n\tif !found {\n\t\treturn\n\t}\n\n\tprintln(thread.ID())\n\tprintln(thread.OriginalBoardID())\n\tprintln(thread.OriginalThreadID())\n\tprintln(thread.BoardID())\n\tprintln(thread.Title())\n\tprintln(thread.Body())\n\tprintln(thread.Hidden())\n\tprintln(thread.Readonly())\n\tprintln(thread.CommentCount())\n\tprintln(thread.RepostCount()) // Reposts can't be reposted, so count must be 0\n\tprintln(thread.FlagCount())\n\tprintln(thread.Creator())\n\tprintln(thread.CreatedAt())\n\tprintln(thread.UpdatedAt())\n}\n\n// Output:\n// 1\n// 1\n// 2\n// 2\n// Foo\n// Bar\n// true\n// true\n// 1\n// 0\n// 1\n// g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\n// 1234567890\n// 1234567890\n"},{"name":"z_hub_2_a_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_2_a_filetest\n\n// Test getting boards when no boards exist\npackage z_hub_2_a_filetest\n\nimport (\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nfunc main(cur realm) {\n\tboards := boards2.GetBoards(0, boards2.BoardCount())\n\tprintln(len(boards))\n}\n\n// Output:\n// 0\n"},{"name":"z_hub_2_b_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_2_b_filetest\n\n// Test getting boards\npackage z_hub_2_b_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboards2.CreateBoard(cross(cur), \"aaa123\", false, false)\n\tboards2.CreateBoard(cross(cur), \"bbb123\", false, false)\n\tboards2.CreateBoard(cross(cur), \"ccc123\", false, false)\n}\n\nfunc main(cur realm) {\n\tboards := boards2.GetBoards(0, boards2.BoardCount())\n\n\tfor _, b := range boards {\n\t\tprintln(b.ID(), b.Name())\n\t}\n}\n\n// Output:\n// 1 aaa123\n// 2 bbb123\n// 3 ccc123\n"},{"name":"z_hub_3_a_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_3_a_filetest\n\n// Test getting threads from an empty board\npackage z_hub_3_a_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar boardID boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\nfunc main(cur realm) {\n\tboards := boards2.GetThreads(uint64(boardID), 0, boards2.BoardCount())\n\tprintln(len(boards))\n}\n\n// Output:\n// 0\n"},{"name":"z_hub_3_b_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_3_b_filetest\n\n// Test getting threads from a board\npackage z_hub_3_b_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar board boards2.Board\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID := boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\t// Create a couple of board threads\n\tboards2.CreateThread(cross(cur), boardID, \"First\", \"Body\")\n\tboards2.CreateThread(cross(cur), boardID, \"Second\", \"Body\")\n\tboards2.CreateThread(cross(cur), boardID, \"Third\", \"Body\")\n\n\t// Get readonly board\n\tboard, _ = boards2.GetBoard(uint64(boardID))\n}\n\nfunc main(cur realm) {\n\tthreads := boards2.GetThreads(board.ID(), 0, board.ThreadCount())\n\n\tfor _, t := range threads {\n\t\tprintln(t.ID(), t.Title())\n\t}\n}\n\n// Output:\n// 1 First\n// 2 Second\n// 3 Third\n"},{"name":"z_hub_4_a_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_4_a_filetest\n\n// Test getting board members\npackage z_hub_4_a_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar board boards2.Board\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID := boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\t// Invite board members\n\tboards2.InviteMember(cross(cur), boardID, \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", \"owner\")\n\tboards2.InviteMember(cross(cur), boardID, \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\", \"admin\")\n\n\t// Get readonly board\n\tboard, _ = boards2.GetBoard(uint64(boardID))\n}\n\nfunc main(cur realm) {\n\tmembers := boards2.GetMembers(board.ID(), 0, board.MemberCount())\n\n\tfor _, m := range members {\n\t\tprintln(m.Address(), m.Roles())\n\t}\n}\n\n// Output:\n// g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 slice[(\"owner\" string)]\n// g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh slice[(\"owner\" string)]\n// g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj slice[(\"admin\" string)]\n"},{"name":"z_hub_4_b_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_4_b_filetest\n\n// Test getting the realm admin users using a zero board ID\npackage z_hub_4_b_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\n\t// Invite a realm member, which requires a zero board ID\n\tboards2.InviteMember(cross(cur), 0, \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\", \"admin\")\n}\n\nfunc main(cur realm) {\n\t// A zero board ID must list the realm admin users instead of returning\n\t// nothing, matching how IsMember and the members page resolve it.\n\tmembers := boards2.GetMembers(0, 0, 10)\n\n\tfor _, m := range members {\n\t\tprintln(m.Address(), m.Roles())\n\t}\n}\n\n// Output:\n// g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 slice[(\"admin\" string)]\n// g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh slice[(\"owner\" string)]\n"},{"name":"z_hub_5_a_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_5_a_filetest\n\n// Test getting reposts from a thread without reposts\npackage z_hub_5_a_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar thread boards2.Thread\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID := boards2.CreateBoard(cross(cur), \"aaa123\", false, false)\n\tthreadID := boards2.CreateThread(cross(cur), boardID, \"Title\", \"Body\")\n\n\t// Get readonly thread\n\tthread, _ = boards2.GetThread(uint64(boardID), uint64(threadID))\n}\n\nfunc main(cur realm) {\n\treposts := boards2.GetReposts(thread.BoardID(), thread.ID(), 0, thread.RepostCount())\n\tprintln(len(reposts))\n}\n\n// Output:\n// 0\n"},{"name":"z_hub_5_b_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_5_b_filetest\n\n// Test getting reposts of a thread\npackage z_hub_5_b_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar thread boards2.Thread\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID := boards2.CreateBoard(cross(cur), \"aaa123\", false, false)\n\tthreadID := boards2.CreateThread(cross(cur), boardID, \"Title\", \"Body\")\n\n\t// Create first repost\n\tdstBoardID := boards2.CreateBoard(cross(cur), \"bbb123\", false, false)\n\tboards2.CreateRepost(cross(cur), boardID, threadID, dstBoardID, \"First\", \"Body\")\n\n\t// Create second repost\n\tdstBoardID = boards2.CreateBoard(cross(cur), \"ccc123\", false, false)\n\tboards2.CreateRepost(cross(cur), boardID, threadID, dstBoardID, \"Second\", \"Body\")\n\n\t// Get readonly thread\n\tthread, _ = boards2.GetThread(uint64(boardID), uint64(threadID))\n}\n\nfunc main(cur realm) {\n\treposts := boards2.GetReposts(thread.BoardID(), thread.ID(), 0, thread.RepostCount())\n\n\tfor _, t := range reposts {\n\t\tprintln(t.ID(), t.Title())\n\t}\n}\n\n// Output:\n// 1 First\n// 1 Second\n"},{"name":"z_hub_6_a_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_6_a_filetest\n\n// Test getting flags from an unflagged thread\npackage z_hub_6_a_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar (\n\tboardID  boards.ID\n\tthreadID boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"Title\", \"Body\")\n}\n\nfunc main(cur realm) {\n\tflags := boards2.GetFlags(uint64(boardID), uint64(threadID), 0, 0, 1)\n\tprintln(len(flags))\n}\n\n// Output:\n// 0\n"},{"name":"z_hub_6_b_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_6_b_filetest\n\n// Test getting flags from an unflagged comment\npackage z_hub_6_b_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar (\n\tboardID   boards.ID\n\tthreadID  boards.ID\n\tcommentID boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"Title\", \"Body\")\n\tcommentID = boards2.CreateReply(cross(cur), boardID, threadID, 0, \"Comment\")\n}\n\nfunc main(cur realm) {\n\tflags := boards2.GetFlags(uint64(boardID), uint64(threadID), uint64(commentID), 0, 1)\n\tprintln(len(flags))\n}\n\n// Output:\n// 0\n"},{"name":"z_hub_6_c_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_6_c_filetest\n\n// Test getting flags from a thread\npackage z_hub_6_c_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tadmin             = \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"\n\tmoderator         = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\"\n)\n\nvar thread boards2.Thread\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboardID := boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\tthreadID := boards2.CreateThread(cross(cur), boardID, \"Title\", \"Body\")\n\n\t// Invite members\n\tboards2.InviteMember(cross(cur), boardID, admin, \"admin\")\n\tboards2.InviteMember(cross(cur), boardID, moderator, \"moderator\")\n\n\t// Update flagging threshold to two flags\n\tboards2.SetFlaggingThreshold(cross(cur), boardID, 2)\n\n\t// Add first flag\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\tboards2.FlagThread(cross(cur), boardID, threadID, \"Reason 1\")\n\n\t// Add second flag\n\ttesting.SetRealm(testing.NewUserRealm(moderator))\n\tboards2.FlagThread(cross(cur), boardID, threadID, \"Reason 2\")\n\n\t// Get readonly thread\n\tthread, _ = boards2.GetThread(uint64(boardID), uint64(threadID))\n}\n\nfunc main(cur realm) {\n\tflags := boards2.GetFlags(thread.BoardID(), thread.ID(), 0, 0, thread.FlagCount())\n\n\tfor _, f := range flags {\n\t\tprintln(f.User(), f.Reason())\n\t}\n}\n\n// Output:\n// g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 Reason 1\n// g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj Reason 2\n"},{"name":"z_hub_6_d_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_6_d_filetest\n\n// Test getting flags from a comment\npackage z_hub_6_d_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tadmin             = \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"\n\tmoderator         = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\"\n)\n\nvar comment boards2.Comment\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboardID := boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\tthreadID := boards2.CreateThread(cross(cur), boardID, \"Title\", \"Body\")\n\tcommentID := boards2.CreateReply(cross(cur), boardID, threadID, 0, \"Comment\")\n\n\t// Invite member\n\tboards2.InviteMember(cross(cur), boardID, admin, \"admin\")\n\tboards2.InviteMember(cross(cur), boardID, moderator, \"moderator\")\n\n\t// Update flagging threshold to two flags\n\tboards2.SetFlaggingThreshold(cross(cur), boardID, 2)\n\n\t// Add first flag\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\tboards2.FlagReply(cross(cur), boardID, threadID, commentID, \"Reason 1\")\n\n\t// Add second flag\n\ttesting.SetRealm(testing.NewUserRealm(moderator))\n\tboards2.FlagReply(cross(cur), boardID, threadID, commentID, \"Reason 2\")\n\n\t// Get readonly comment\n\tcomment, _ = boards2.GetComment(uint64(boardID), uint64(threadID), uint64(commentID))\n}\n\nfunc main(cur realm) {\n\tflags := boards2.GetFlags(comment.BoardID(), comment.ThreadID(), comment.ID(), 0, comment.FlagCount())\n\n\tfor _, f := range flags {\n\t\tprintln(f.User(), f.Reason())\n\t}\n}\n\n// Output:\n// g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 Reason 1\n// g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj Reason 2\n"},{"name":"z_hub_6_e_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_6_e_filetest\n\n// Test getting flags from a nested reply\npackage z_hub_6_e_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tadmin             = \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"\n\tmoderator         = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\"\n)\n\nvar (\n\tboardID  boards.ID\n\tthreadID boards.ID\n\treplyID  boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboardID = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"Title\", \"Body\")\n\tcommentID := boards2.CreateReply(cross(cur), boardID, threadID, 0, \"Comment\")\n\treplyID = boards2.CreateReply(cross(cur), boardID, threadID, commentID, \"Reply\")\n\n\t// Invite members\n\tboards2.InviteMember(cross(cur), boardID, admin, \"admin\")\n\tboards2.InviteMember(cross(cur), boardID, moderator, \"moderator\")\n\n\t// Update flagging threshold to two flags\n\tboards2.SetFlaggingThreshold(cross(cur), boardID, 2)\n\n\t// Flag the nested reply\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\tboards2.FlagReply(cross(cur), boardID, threadID, replyID, \"Reason 1\")\n\n\ttesting.SetRealm(testing.NewUserRealm(moderator))\n\tboards2.FlagReply(cross(cur), boardID, threadID, replyID, \"Reason 2\")\n}\n\nfunc main(cur realm) {\n\tflags := boards2.GetFlags(uint64(boardID), uint64(threadID), uint64(replyID), 0, 10)\n\n\tfor _, f := range flags {\n\t\tprintln(f.User(), f.Reason())\n\t}\n}\n\n// Output:\n// g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 Reason 1\n// g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj Reason 2\n"},{"name":"z_hub_7_a_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_7_a_filetest\n\n// Test getting comments from a thread without comments\npackage z_hub_7_a_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar thread boards2.Thread\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID := boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\tthreadID := boards2.CreateThread(cross(cur), boardID, \"Title\", \"Body\")\n\n\t// Get readonly thread\n\tthread, _ = boards2.GetThread(uint64(boardID), uint64(threadID))\n}\n\nfunc main(cur realm) {\n\tcomments := boards2.GetComments(thread.BoardID(), thread.ID(), 0, thread.CommentCount())\n\tprintln(len(comments))\n}\n\n// Output:\n// 0\n"},{"name":"z_hub_7_b_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_7_b_filetest\n\n// Test getting comments from a thread\npackage z_hub_7_b_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar thread boards2.Thread\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID := boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\tthreadID := boards2.CreateThread(cross(cur), boardID, \"Title\", \"Body\")\n\tcommentID := boards2.CreateReply(cross(cur), boardID, threadID, 0, \"Comment 1\")\n\n\t// Create another comment\n\tboards2.CreateReply(cross(cur), boardID, threadID, 0, \"Comment 2\")\n\n\t// Add a reply (it should not be included in the output)\n\tboards2.CreateReply(cross(cur), boardID, threadID, commentID, \"Reply\")\n\n\t// Get readonly thread\n\tthread, _ = boards2.GetThread(uint64(boardID), uint64(threadID))\n}\n\nfunc main(cur realm) {\n\tcomments := boards2.GetComments(thread.BoardID(), thread.ID(), 0, thread.CommentCount())\n\n\tfor _, c := range comments {\n\t\tprintln(c.ID(), c.Body())\n\t}\n}\n\n// Output:\n// 2 Comment 1\n// 3 Comment 2\n"},{"name":"z_hub_8_a_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_8_a_filetest\n\n// Test getting replies from a comment without replies\npackage z_hub_8_a_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar comment boards2.Comment\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID := boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\tthreadID := boards2.CreateThread(cross(cur), boardID, \"Title\", \"Body\")\n\tcommentID := boards2.CreateReply(cross(cur), boardID, threadID, 0, \"Comment\")\n\n\t// Get readonly comment\n\tcomment, _ = boards2.GetComment(uint64(boardID), uint64(threadID), uint64(commentID))\n}\n\nfunc main(cur realm) {\n\treplies := boards2.GetReplies(comment.BoardID(), comment.ThreadID(), comment.ID(), 0, comment.ReplyCount())\n\tprintln(len(replies))\n}\n\n// Output:\n// 0\n"},{"name":"z_hub_8_b_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_8_b_filetest\n\n// Test getting replies from a comment\npackage z_hub_8_b_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar comment boards2.Comment\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID := boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\tthreadID := boards2.CreateThread(cross(cur), boardID, \"Title\", \"Body\")\n\tcommentID := boards2.CreateReply(cross(cur), boardID, threadID, 0, \"Comment\")\n\n\t// Create replies\n\tboards2.CreateReply(cross(cur), boardID, threadID, commentID, \"Reply 1\")\n\tsubCommentID := boards2.CreateReply(cross(cur), boardID, threadID, commentID, \"Reply 2\")\n\n\t// Add a sub-reply (it should not be included in the output)\n\tboards2.CreateReply(cross(cur), boardID, threadID, subCommentID, \"Reply 3\")\n\n\t// Get readonly comment\n\tcomment, _ = boards2.GetComment(uint64(boardID), uint64(threadID), uint64(commentID))\n}\n\nfunc main(cur realm) {\n\treplies := boards2.GetReplies(comment.BoardID(), comment.ThreadID(), comment.ID(), 0, comment.ReplyCount())\n\n\tfor _, r := range replies {\n\t\tprintln(r.ID(), r.Body())\n\t}\n}\n\n// Output:\n// 3 Reply 1\n// 4 Reply 2\n"},{"name":"z_hub_8_c_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_8_c_filetest\n\n// Test getting replies from a nested reply\npackage z_hub_8_c_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar (\n\tboardID  boards.ID\n\tthreadID boards.ID\n\treplyID  boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"Title\", \"Body\")\n\tcommentID := boards2.CreateReply(cross(cur), boardID, threadID, 0, \"Comment\")\n\treplyID = boards2.CreateReply(cross(cur), boardID, threadID, commentID, \"Reply\")\n\n\t// Create sub-replies of the nested reply\n\tboards2.CreateReply(cross(cur), boardID, threadID, replyID, \"Sub-reply 1\")\n\tboards2.CreateReply(cross(cur), boardID, threadID, replyID, \"Sub-reply 2\")\n}\n\nfunc main(cur realm) {\n\treplies := boards2.GetReplies(uint64(boardID), uint64(threadID), uint64(replyID), 0, 10)\n\n\tfor _, r := range replies {\n\t\tprintln(r.ID(), r.Body())\n\t}\n}\n\n// Output:\n// 4 Sub-reply 1\n// 5 Sub-reply 2\n"},{"name":"z_hub_9_a_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_9_a_filetest\n\n// Test default thread comment values\npackage z_hub_9_a_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar (\n\tboardID   boards.ID\n\tthreadID  boards.ID\n\tcommentID boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID = boards2.CreateBoard(cross(cur), \"origin123\", false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"Title\", \"Body\")\n\tcommentID = boards2.CreateReply(cross(cur), boardID, threadID, 0, \"Comment\")\n}\n\nfunc main(cur realm) {\n\tcomment, found := boards2.GetComment(uint64(boardID), uint64(threadID), uint64(commentID))\n\tif !found {\n\t\treturn\n\t}\n\n\tprintln(comment.ID())\n\tprintln(comment.BoardID())\n\tprintln(comment.ThreadID())\n\tprintln(comment.ParentID())\n\tprintln(comment.Body())\n\tprintln(comment.Hidden())\n\tprintln(comment.ReplyCount())\n\tprintln(comment.FlagCount())\n\tprintln(comment.Creator())\n\tprintln(comment.CreatedAt())\n\tprintln(comment.UpdatedAt())\n}\n\n// Output:\n// 2\n// 1\n// 1\n// 1\n// Comment\n// false\n// 0\n// 0\n// g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\n// 1234567890\n// 0\n"},{"name":"z_hub_9_b_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_9_b_filetest\n\n// Test non default thread comment values\npackage z_hub_9_b_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar (\n\tboardID   boards.ID\n\tthreadID  boards.ID\n\tcommentID boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID = boards2.CreateBoard(cross(cur), \"origin123\", false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"Title\", \"Body\")\n\tcommentID = boards2.CreateReply(cross(cur), boardID, threadID, 0, \"Comment\")\n\n\t// Edit comment\n\tboards2.EditReply(cross(cur), boardID, threadID, commentID, \"Test comment\")\n\n\t// Create a comment reply\n\tboards2.CreateReply(cross(cur), boardID, threadID, commentID, \"Reply\")\n\n\t// Flag comment\n\tboards2.FlagReply(cross(cur), boardID, threadID, commentID, \"Reason\")\n}\n\nfunc main(cur realm) {\n\tcomment, found := boards2.GetComment(uint64(boardID), uint64(threadID), uint64(commentID))\n\tif !found {\n\t\treturn\n\t}\n\n\tprintln(comment.ID())\n\tprintln(comment.BoardID())\n\tprintln(comment.ThreadID())\n\tprintln(comment.ParentID())\n\tprintln(comment.Body())\n\tprintln(comment.Hidden())\n\tprintln(comment.ReplyCount())\n\tprintln(comment.FlagCount())\n\tprintln(comment.Creator())\n\tprintln(comment.CreatedAt())\n\tprintln(comment.UpdatedAt())\n}\n\n// Output:\n// 2\n// 1\n// 1\n// 1\n// Test comment\n// true\n// 1\n// 1\n// g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\n// 1234567890\n// 1234567890\n"},{"name":"z_hub_9_c_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_hub_9_c_filetest\n\n// Test getting a nested reply by ID\npackage z_hub_9_c_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nvar (\n\tboardID  boards.ID\n\tthreadID boards.ID\n\treplyID  boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"))\n\tboardID = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"Title\", \"Body\")\n\tcommentID := boards2.CreateReply(cross(cur), boardID, threadID, 0, \"Comment\")\n\n\t// Reply to the comment, so the reply is not a top level comment\n\treplyID = boards2.CreateReply(cross(cur), boardID, threadID, commentID, \"Reply\")\n}\n\nfunc main(cur realm) {\n\treply, found := boards2.GetComment(uint64(boardID), uint64(threadID), uint64(replyID))\n\tprintln(found)\n\tprintln(reply.ID())\n\tprintln(reply.ParentID())\n\tprintln(reply.Body())\n}\n\n// Output:\n// true\n// 3\n// 2\n// Reply\n"},{"name":"z_invite_member_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_invite_member_00_filetest\n\npackage z_invite_member_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tbid           = boards.ID(0)                               // Operate on realm DAO instead of individual boards\n\trole          = boards2.RoleOwner\n)\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.InviteMember(cross(cur), bid, user, role)\n\n\t// Check that user is invited\n\tprintln(boards2.HasMemberRole(bid, user, role))\n}\n\n// Output:\n// true\n"},{"name":"z_invite_member_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_invite_member_01_filetest\n\npackage z_invite_member_01_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tadmin address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tuser  address = \"g1w4ek2u33ta047h6lta047h6lta047h6ldvdwpn\"\n)\n\nvar bid boards.ID // Operate on board DAO\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\t// Add an admin member\n\tboards2.InviteMember(cross(cur), bid, admin, boards2.RoleAdmin)\n}\n\nfunc main(cur realm) {\n\t// Next call will be done by the admin member\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\n\tboards2.InviteMember(cross(cur), bid, user, boards2.RoleOwner)\n}\n\n// Error:\n// only owners are allowed to invite other owners\n"},{"name":"z_invite_member_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_invite_member_02_filetest\n\npackage z_invite_member_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tadmin address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tuser  address = \"g1w4ek2u33ta047h6lta047h6lta047h6ldvdwpn\"\n\trole          = boards2.RoleAdmin\n)\n\nvar bid boards.ID // Operate on board DAO\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\t// Add an admin member\n\tboards2.InviteMember(cross(cur), bid, admin, boards2.RoleAdmin)\n}\n\nfunc main(cur realm) {\n\t// Next call will be done by the admin member\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\n\tboards2.InviteMember(cross(cur), bid, user, role)\n\n\t// Check that user is invited\n\tprintln(boards2.HasMemberRole(bid, user, role))\n}\n\n// Output:\n// true\n"},{"name":"z_invite_member_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_invite_member_03_filetest\n\npackage z_invite_member_03_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.InviteMember(cross(cur), 0, user, boards.Role(\"foobar\")) // Operate on realm DAO instead of individual boards\n}\n\n// Error:\n// invalid role: foobar\n"},{"name":"z_invite_member_04_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_invite_member_04_filetest\n\npackage z_invite_member_04_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\trole          = boards2.RoleOwner\n)\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"foo123\", false, false) // Operate on board DAO members\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.InviteMember(cross(cur), bid, user, role)\n\n\t// Check that user is invited\n\tprintln(boards2.HasMemberRole(0, user, role)) // Operate on realm DAO\n\tprintln(boards2.HasMemberRole(bid, user, role))\n}\n\n// Output:\n// false\n// true\n"},{"name":"z_invite_member_05_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_invite_member_05_filetest\n\npackage z_invite_member_05_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tbid           = boards.ID(0)                               // Operate on realm DAO instead of individual boards\n\trole          = boards2.RoleOwner\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.InviteMember(cross(cur), bid, user, role)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.InviteMember(cross(cur), bid, user, role)\n}\n\n// Error:\n// user is already a member: g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\n"},{"name":"z_invite_member_06_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_invite_member_06_filetest\n\npackage z_invite_member_06_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.InviteMember(cross(cur), 0, \"g1w4ek2u33ta047h6lta047h6lta047h6ldvdwpn\", boards2.RoleGuest)\n}\n\n// Error:\n// unauthorized, user g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj doesn't have the required permission\n"},{"name":"z_is_banned_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_is_banned_00_filetest\n\npackage z_is_banned_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\nfunc main() {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tprintln(boards2.IsBanned(bid, \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"))\n}\n\n// Output:\n// false\n"},{"name":"z_is_banned_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_is_banned_01_filetest\n\npackage z_is_banned_01_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n)\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\tboards2.Ban(cross(cur), bid, user, boards2.BanDay, \"Reason\")\n}\n\nfunc main() {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tprintln(boards2.IsBanned(bid, user))\n}\n\n// Output:\n// true\n"},{"name":"z_is_member_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_is_member_00_filetest\n\npackage z_is_member_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner  address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tmember address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\trole           = boards2.RoleGuest\n)\n\nvar bid boards.ID // Operate on board DAO\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\tboards2.InviteMember(cross(cur), bid, member, role)\n}\n\nfunc main() {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tprintln(boards2.HasMemberRole(bid, member, role))\n\tprintln(boards2.HasMemberRole(bid, member, \"invalid\"))\n\tprintln(boards2.IsMember(bid, member))\n}\n\n// Output:\n// true\n// false\n// true\n"},{"name":"z_is_member_01_filetest.gno","body":"package main\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tbid           = boards.ID(0)                               // Operate on realm DAO instead of individual boards\n\trole          = boards2.RoleGuest\n)\n\nfunc main() {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tprintln(boards2.HasMemberRole(bid, user, role))\n\tprintln(boards2.IsMember(bid, user))\n}\n\n// Output:\n// false\n// false\n"},{"name":"z_lock_realm_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_lock_realm_00_filetest\n\npackage z_lock_realm_00_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.LockRealm(cross(cur), false)\n\n\tprintln(boards2.IsRealmLocked())\n\tprintln(boards2.AreRealmMembersLocked())\n}\n\n// Output:\n// true\n// false\n"},{"name":"z_lock_realm_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_lock_realm_01_filetest\n\npackage z_lock_realm_01_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.LockRealm(cross(cur), false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Should fail because realm is already locked\n\tboards2.LockRealm(cross(cur), false)\n}\n\n// Error:\n// realm is locked\n"},{"name":"z_lock_realm_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_lock_realm_02_filetest\n\npackage z_lock_realm_02_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\nfunc main(cur realm) {\n\t// Call realm with a user that has not permission to lock the realm\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.LockRealm(cross(cur), false)\n}\n\n// Error:\n// unauthorized, user g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj doesn't have the required permission\n"},{"name":"z_lock_realm_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_lock_realm_03_filetest\n\npackage z_lock_realm_03_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.LockRealm(cross(cur), true)\n\n\tprintln(boards2.IsRealmLocked())\n\tprintln(boards2.AreRealmMembersLocked())\n}\n\n// Output:\n// true\n// true\n"},{"name":"z_lock_realm_04_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_lock_realm_04_filetest\n\npackage z_lock_realm_04_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.LockRealm(cross(cur), true)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Should fail because realm is already locked\n\tboards2.LockRealm(cross(cur), true)\n}\n\n// Error:\n// realm and members are locked\n"},{"name":"z_lock_realm_05_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_lock_realm_05_filetest\n\npackage z_lock_realm_05_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc init(cur realm) {\n\t// Lock the realm without locking realm members\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.LockRealm(cross(cur), false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.LockRealm(cross(cur), true)\n\n\tprintln(boards2.IsRealmLocked())\n\tprintln(boards2.AreRealmMembersLocked())\n}\n\n// Output:\n// true\n// true\n"},{"name":"z_remove_member_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_remove_member_00_filetest\n\npackage z_remove_member_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar bid boards.ID // Operate on board DAO\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\tboards2.InviteMember(cross(cur), bid, user, boards2.RoleGuest)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.RemoveMember(cross(cur), bid, user)\n\n\t// Check that user is not a member\n\tprintln(boards2.IsMember(bid, user))\n}\n\n// Output:\n// false\n"},{"name":"z_remove_member_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_remove_member_01_filetest\n\npackage z_remove_member_01_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.RemoveMember(cross(cur), 0, \"g1w4ek2u33ta047h6lta047h6lta047h6ldvdwpn\") // Operate on realm DAO instead of individual boards\n}\n\n// Error:\n// unauthorized, user g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj doesn't have the required permission\n"},{"name":"z_remove_member_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_remove_member_02_filetest\n\npackage z_remove_member_02_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.RemoveMember(cross(cur), 0, \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\") // Operate on realm DAO instead of individual boards\n}\n\n// Error:\n// member not found\n"},{"name":"z_remove_member_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_remove_member_03_filetest\n\npackage z_remove_member_03_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n)\n\nvar bid boards.ID // Operate on board DAO\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\tboards2.InviteMember(cross(cur), bid, user, boards2.RoleGuest)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Users must be able to remove themselves without permissions\n\tboards2.RemoveMember(cross(cur), bid, user)\n\n\t// Check that user is not a member\n\tprintln(boards2.IsMember(bid, user))\n}\n\n// Output:\n// false\n"},{"name":"z_rename_board_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_rename_board_00_filetest\n\npackage z_rename_board_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner   address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tname            = \"foo123\"\n\tnewName         = \"bar123\"\n)\n\nvar bid boards.ID // Operate on board DAO\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), name, false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.RenameBoard(cross(cur), name, newName)\n\n\t// Ensure board is renamed by the default board owner\n\tbid2, _ := boards2.GetBoardIDFromName(cross(cur), newName)\n\tprintln(\"IDs match =\", bid == bid2)\n}\n\n// Output:\n// IDs match = true\n"},{"name":"z_rename_board_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_rename_board_01_filetest\n\npackage z_rename_board_01_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tname          = \"foo123\"\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.CreateBoard(cross(cur), name, false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.RenameBoard(cross(cur), name, \"\")\n}\n\n// Error:\n// board name is empty\n"},{"name":"z_rename_board_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_rename_board_02_filetest\n\npackage z_rename_board_02_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tname          = \"foo123\"\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.CreateBoard(cross(cur), name, false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.RenameBoard(cross(cur), name, name)\n}\n\n// Error:\n// board already exists\n"},{"name":"z_rename_board_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_rename_board_03_filetest\n\npackage z_rename_board_03_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.RenameBoard(cross(cur), \"unexisting\", \"foo\")\n}\n\n// Error:\n// board does not exist with name: unexisting\n"},{"name":"z_rename_board_04_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_rename_board_04_filetest\n\npackage z_rename_board_04_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tname          = \"foo123\"\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.CreateBoard(cross(cur), name, false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.RenameBoard(cross(cur), name, \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n}\n\n// Error:\n// addresses are not allowed as board name\n"},{"name":"z_rename_board_05_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_rename_board_05_filetest\n\npackage z_rename_board_05_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner   address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tmember  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tname            = \"foo123\"\n\tnewName         = \"barbaz123\"\n)\n\nvar bid boards.ID // Operate on board DAO\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tbid = boards2.CreateBoard(cross(cur), name, false, false)\n\tboards2.InviteMember(cross(cur), bid, member, boards2.RoleOwner)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(member))\n\n\tboards2.RenameBoard(cross(cur), name, newName)\n\n\t// Ensure board is renamed by another board owner\n\tbid2, _ := boards2.GetBoardIDFromName(cross(cur), newName)\n\tprintln(\"IDs match =\", bid == bid2)\n}\n\n// Output:\n// IDs match = true\n"},{"name":"z_rename_board_06_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_rename_board_06_filetest\n\npackage z_rename_board_06_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nconst (\n\towner   address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tmember  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tmember2 address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n\tname            = \"foo123\"\n\tnewName         = \"barbaz123\"\n)\n\nvar bid boards.ID // Operate on board DAO\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), name, false, false)\n\tboards2.InviteMember(cross(cur), bid, member, boards2.RoleOwner)\n\n\t// Test1 is the boards owner and its address has a user already registered\n\t// so a new member must register a user with the new board name.\n\t// uinit.RegisterUser is genesis-only since the security fix.\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), newName, member)\n\ttesting.SetHeight(123)\n\n\t// Invite a new member that doesn't own the user that matches the new board name\n\tboards2.InviteMember(cross(cur), bid, member2, boards2.RoleOwner)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(member2))\n\n\tboards2.RenameBoard(cross(cur), name, newName)\n}\n\n// Error:\n// board name is a user name registered to a different user\n"},{"name":"z_rename_board_07_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_rename_board_07_filetest\n\npackage z_rename_board_07_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tname          = \"foo123\"\n)\n\nvar newName string\n\nfunc init(cur realm) {\n\tnewName = strings.Repeat(\"A\", boards2.MaxBoardNameLength+1)\n\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.CreateBoard(cross(cur), name, false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.RenameBoard(cross(cur), name, newName)\n}\n\n// Error:\n// board name is too long, maximum allowed is 50 characters\n"},{"name":"z_rename_board_08_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_rename_board_08_filetest\n\npackage z_rename_board_08_filetest\n\n// SEND: 1000000ugnot\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n\tuinit \"gno.land/r/sys/users/init\"\n)\n\nconst (\n\towner   address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tmember  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tmember2 address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n\tname            = \"foo123\"\n\tnewName         = \"barbaz123\"\n)\n\nvar bid boards.ID // Operate on board DAO\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), name, false, false)\n\tboards2.InviteMember(cross(cur), bid, member, boards2.RoleOwner)\n\n\t// Test1 is the boards owner and its address has a user already registered\n\t// so a new member must register a user with the new board name.\n\t// uinit.RegisterUser is genesis-only since the security fix.\n\ttesting.SetHeight(0)\n\tuinit.RegisterUser(cross(cur), newName, member)\n\ttesting.SetHeight(123)\n\n\t// Invite a new member that doesn't own the user that matches the new board name\n\tboards2.InviteMember(cross(cur), bid, member2, boards2.RoleOwner)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(member2))\n\n\tboards2.RenameBoard(cross(cur), name, newName)\n}\n\n// Error:\n// board name is a user name registered to a different user\n"},{"name":"z_rename_board_09_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_rename_board_09_filetest\n\npackage z_rename_board_09_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tname          = \"foo123\"\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.CreateBoard(cross(cur), name, false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tboards2.RenameBoard(cross(cur), name, \"barbaz\")\n}\n\n// Error:\n// unauthorized, user g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj doesn't have the required permission\n"},{"name":"z_request_invite_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_request_invite_00_filetest\n\npackage z_request_invite_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"))\n\n\tboards2.RequestInvite(cross(cur), bid)\n\n\tprintln(boards2.Render(\"test123/invites\"))\n}\n\n// Output:\n// # test123 Invite Requests\n// ### These users have requested to be invited to the board\n// | User | Request Date | Actions |\n// | --- | --- | --- |\n// | [g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5](/u/g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5) | 2009-02-13 11:31pm UTC | [accept](/r/gnoland/boards2/v1$help\u0026func=AcceptInvite\u0026boardID=1\u0026user=g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5) • [revoke](/r/gnoland/boards2/v1$help\u0026func=RevokeInvite\u0026boardID=1\u0026user=g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5) |\n"},{"name":"z_request_invite_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_request_invite_01_filetest\n\npackage z_request_invite_01_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\n\tboards2.RequestInvite(cross(cur), bid)\n}\n\n// Error:\n// caller must be user\n"},{"name":"z_request_invite_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_request_invite_02_filetest\n\npackage z_request_invite_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.RequestInvite(cross(cur), bid)\n}\n\n// Error:\n// caller is already a member\n"},{"name":"z_request_invite_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_request_invite_03_filetest\n\npackage z_request_invite_03_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n)\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tboards2.RequestInvite(cross(cur), bid)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tboards2.RequestInvite(cross(cur), bid)\n}\n\n// Error:\n// invite request already exists\n"},{"name":"z_request_invite_04_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_request_invite_04_filetest\n\npackage z_request_invite_04_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n)\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tboards2.RequestInvite(cross(cur), 404)\n}\n\n// Error:\n// board does not exist with ID: 404\n"},{"name":"z_revoke_invite_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_revoke_invite_00_filetest\n\npackage z_revoke_invite_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n)\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tboards2.RequestInvite(cross(cur), bid)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.RevokeInvite(cross(cur), bid, user)\n\n\tprintln(boards2.IsMember(bid, user))\n\tprintln()\n\tprintln(boards2.Render(\"test123/invites\"))\n}\n\n// Output:\n// false\n//\n// # test123 Invite Requests\n// ### Board has no invite requests\n"},{"name":"z_revoke_invite_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_revoke_invite_01_filetest\n\npackage z_revoke_invite_01_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n)\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.RevokeInvite(cross(cur), bid, user)\n}\n\n// Error:\n// invite request not found\n"},{"name":"z_revoke_invite_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_revoke_invite_02_filetest\n\npackage z_revoke_invite_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n)\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tboards2.RequestInvite(cross(cur), bid)\n}\n\nfunc main(cur realm) {\n\t// Caller is not a member and has no permission to revoke invites\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tboards2.RevokeInvite(cross(cur), bid, user)\n}\n\n// Error:\n// unauthorized, user g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5 doesn't have the required permission\n"},{"name":"z_set_flagging_threshold_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_set_flagging_threshold_00_filetest\n\npackage z_set_flagging_threshold_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.SetFlaggingThreshold(cross(cur), bid, 4)\n\n\t// Ensure that flagging threshold changed\n\tprintln(boards2.GetFlaggingThreshold(bid))\n}\n\n// Output:\n// 4\n"},{"name":"z_set_flagging_threshold_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_set_flagging_threshold_01_filetest\n\npackage z_set_flagging_threshold_01_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address   = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tbid   boards.ID = 404\n)\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.SetFlaggingThreshold(cross(cur), bid, 1)\n}\n\n// Error:\n// board does not exist with ID: 404\n"},{"name":"z_set_flagging_threshold_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_set_flagging_threshold_02_filetest\n\npackage z_set_flagging_threshold_02_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.SetFlaggingThreshold(cross(cur), 1, 0)\n}\n\n// Error:\n// invalid flagging threshold\n"},{"name":"z_set_permissions_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_set_permissions_00_filetest\n\npackage z_set_permissions_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\t\"gno.land/p/gnoland/boards/exts/permissions\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tbid           = boards.ID(0) // Operate on realm instead of individual boards\n)\n\nvar perms boards.Permissions\n\nfunc init() {\n\t// Create a new permissions instance without users\n\tperms = permissions.New()\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.SetPermissions(cross(cur), bid, perms)\n\n\t// Owner that setted new permissions is not a member of the new permissions\n\tprintln(boards2.IsMember(bid, owner))\n}\n\n// Output:\n// false\n"},{"name":"z_set_permissions_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_set_permissions_01_filetest\n\npackage z_set_permissions_01_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\t\"gno.land/p/gnoland/boards/exts/permissions\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\tuser address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\tbid          = boards.ID(0)                               // Operate on realm instead of individual boards\n)\n\nvar perms boards.Permissions\n\nfunc init() {\n\t// Create a new permissions instance\n\tperms = permissions.New()\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tboards2.SetPermissions(cross(cur), bid, perms)\n}\n\n// Error:\n// unauthorized, user g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj doesn't have the required permission\n"},{"name":"z_set_permissions_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_set_permissions_02_filetest\n\npackage z_set_permissions_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\t\"gno.land/p/gnoland/boards/exts/permissions\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tperms boards.Permissions\n\tbid   boards.ID\n)\n\nfunc init(cur realm) {\n\t// Create a new permissions instance without users\n\tperms = permissions.New()\n\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"foobar\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.SetPermissions(cross(cur), bid, perms)\n\n\t// Owner that setted new board permissions is not a member of the new permissions\n\tprintln(boards2.IsMember(bid, owner))\n}\n\n// Output:\n// false\n"},{"name":"z_set_realm_notice_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_set_realm_notice_00_filetest\n\npackage z_set_realm_notice_00_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.SetRealmNotice(cross(cur), \"This is a test realm message\")\n\n\tprintln(boards2.Notice)\n}\n\n// Output:\n// This is a test realm message\n"},{"name":"z_set_realm_notice_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_set_realm_notice_01_filetest\n\npackage z_set_realm_notice_01_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc init(cur realm) {\n\t// Set an initial message so it can be cleared\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.SetRealmNotice(cross(cur), \"This is a test realm message\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.SetRealmNotice(cross(cur), \"\")\n\n\tprintln(boards2.Notice == \"\")\n}\n\n// Output:\n// true\n"},{"name":"z_set_realm_notice_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_set_realm_notice_02_filetest\n\npackage z_set_realm_notice_02_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\nfunc main(cur realm) {\n\t// Call realm with a user that has not permission to set realm notice\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.SetRealmNotice(cross(cur), \"Foo\")\n}\n\n// Error:\n// unauthorized, user g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj doesn't have the required permission\n"},{"name":"z_set_realm_notice_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_set_realm_notice_03_filetest\n\npackage z_set_realm_notice_03_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.SetRealmNotice(cross(cur), \"This is a test realm message\")\n\n\tprintln(boards2.Render(\"\"))\n}\n\n// Output:\n//\n// \u003e \\[!INFO\\] Notice\n// \u003e This is a test realm message\n//\n// # Boards\n// [Create Board](/r/gnoland/boards2/v1:create-board) • [List Admin Users](/r/gnoland/boards2/v1:admin-users) • [Help](/r/gnoland/boards2/v1:help)\n//\n// ---\n// ### Currently there are no boards\n// Be the first to [create a new board](/r/gnoland/boards2/v1:create-board)!\n"},{"name":"z_set_required_account_amount_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_set_required_account_amount_00_filetest\n\npackage z_set_required_account_amount_00_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.SetRequiredAccountAmount(cross(cur), 1_000_000)\n\n\tprintln(boards2.RequiredAccountAmount)\n}\n\n// Output:\n// 1000000\n"},{"name":"z_set_required_account_amount_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_set_required_account_amount_01_filetest\n\npackage z_set_required_account_amount_01_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.SetRequiredAccountAmount(cross(cur), 0) // Disable\n\n\tprintln(boards2.RequiredAccountAmount)\n}\n\n// Output:\n// 0\n"},{"name":"z_set_required_account_amount_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_set_required_account_amount_02_filetest\n\npackage z_set_required_account_amount_02_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\" // @test2\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.SetRequiredAccountAmount(cross(cur), 1_000_000)\n}\n\n// Error:\n// unauthorized, user g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj doesn't have the required permission\n"},{"name":"z_ui_admin_users_00_filetest.gno","body":"// Render realm admin users view.\npackage main\n\nimport (\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nfunc main() {\n\tprintln(boards2.Render(\"admin-users\"))\n}\n\n// Output:\n// # Admin Users\n// ### These are the admin users of the realm\n// | Member | Role | Actions |\n// | --- | --- | --- |\n// | [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) | owner | [remove](/r/gnoland/boards2/v1$help\u0026func=RemoveMember\u0026boardID=0\u0026member=g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) • [change role](/r/gnoland/boards2/v1$help\u0026func=ChangeMemberRole\u0026boardID=0\u0026member=g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\u0026role=) |\n"},{"name":"z_ui_board_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_board_00_filetest\n\n// Render default board view.\npackage z_ui_board_00_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tboardName         = \"TestBoard\"\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Create a board and then add 3 threads\n\tboardID := boards2.CreateBoard(cross(cur), boardName, false, false)\n\n\t// Create thread \"A\" with a single comment\n\tthreadID := boards2.CreateThread(cross(cur), boardID, \"A\", \"Body\")\n\tboards2.CreateReply(cross(cur), boardID, threadID, 0, \"Body\")\n\n\t// The other 2 threads are created without comments\n\tboards2.CreateThread(cross(cur), boardID, \"B\", \"Body\")\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"C\", \"Body\")\n\n\t// Repost thread \"C\" into a different board\n\tdstBoardID := boards2.CreateBoard(cross(cur), \"Bar\", false, false)\n\tboards2.CreateRepost(cross(cur), boardID, threadID, dstBoardID, \"Title\", \"Body\")\n}\n\nfunc main() {\n\tprintln(boards2.Render(boardName))\n}\n\n// Output:\n// # [Boards](/r/gnoland/boards2/v1) › TestBoard\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) on 2009-02-13 11:31pm UTC, #1\n// ↳ [Create Thread](/r/gnoland/boards2/v1:TestBoard/create-thread) • [Request Invite](/r/gnoland/boards2/v1$help\u0026func=RequestInvite\u0026boardID=1) • [Manage Board](?menu=manageBoard)\n//\n// ---\n// Sort by: [newest first](/r/gnoland/boards2/v1:TestBoard?order=desc)\n//\n// ###### [A](/r/gnoland/boards2/v1:TestBoard/1)\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) `owner` on 2009-02-13 11:31pm UTC\n// **1 replies • 0 reposts**\n//\n// ###### [B](/r/gnoland/boards2/v1:TestBoard/3)\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) `owner` on 2009-02-13 11:31pm UTC\n// **0 replies • 0 reposts**\n//\n// ###### [C](/r/gnoland/boards2/v1:TestBoard/4)\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) `owner` on 2009-02-13 11:31pm UTC\n// **0 replies • 1 reposts**\n"},{"name":"z_ui_board_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_board_01_filetest\n\n// Render board sorting threads from newest to oldest.\npackage z_ui_board_01_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tboardName         = \"TestBoard\"\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Create a board and then add 3 threads\n\tboardID := boards2.CreateBoard(cross(cur), boardName, false, false)\n\n\tboards2.CreateThread(cross(cur), boardID, \"A\", \"Body\")\n\tboards2.CreateThread(cross(cur), boardID, \"B\", \"Body\")\n\tboards2.CreateThread(cross(cur), boardID, \"C\", \"Body\")\n}\n\nfunc main() {\n\tpath := boardName + \"?order=desc\"\n\tprintln(boards2.Render(path))\n}\n\n// Output:\n// # [Boards](/r/gnoland/boards2/v1) › TestBoard\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) on 2009-02-13 11:31pm UTC, #1\n// ↳ [Create Thread](/r/gnoland/boards2/v1:TestBoard/create-thread) • [Request Invite](/r/gnoland/boards2/v1$help\u0026func=RequestInvite\u0026boardID=1) • [Manage Board](?menu=manageBoard)\n//\n// ---\n// Sort by: [oldest first](/r/gnoland/boards2/v1:TestBoard?order=asc)\n//\n// ###### [C](/r/gnoland/boards2/v1:TestBoard/3)\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) `owner` on 2009-02-13 11:31pm UTC\n// **0 replies • 0 reposts**\n//\n// ###### [B](/r/gnoland/boards2/v1:TestBoard/2)\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) `owner` on 2009-02-13 11:31pm UTC\n// **0 replies • 0 reposts**\n//\n// ###### [A](/r/gnoland/boards2/v1:TestBoard/1)\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) `owner` on 2009-02-13 11:31pm UTC\n// **0 replies • 0 reposts**\n"},{"name":"z_ui_board_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_board_02_filetest\n\n// Render board view with the manage board menu expanded.\npackage z_ui_board_02_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tboardName         = \"TestBoard\"\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Create a board and a thread\n\tboardID := boards2.CreateBoard(cross(cur), boardName, false, false)\n\tboards2.CreateThread(cross(cur), boardID, \"A\", \"Body\")\n}\n\nfunc main() {\n\tpath := boardName + \"?menu=manageBoard\"\n\tprintln(boards2.Render(path))\n}\n\n// Output:\n// # [Boards](/r/gnoland/boards2/v1) › TestBoard\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) on 2009-02-13 11:31pm UTC, #1\n// ↳ [Create Thread](/r/gnoland/boards2/v1:TestBoard/create-thread) • [Request Invite](/r/gnoland/boards2/v1$help\u0026func=RequestInvite\u0026boardID=1) • **Manage Board**\n// └─ [Invite Member](/r/gnoland/boards2/v1:TestBoard/invite-member) • [List Invite Requests](/r/gnoland/boards2/v1:TestBoard/invites) • [List Members](/r/gnoland/boards2/v1:TestBoard/members) • [List Banned Users](/r/gnoland/boards2/v1:TestBoard/banned-users) • [Freeze Board](/r/gnoland/boards2/v1$help\u0026func=FreezeBoard\u0026boardID=1)\n//\n// ---\n// Sort by: [newest first](/r/gnoland/boards2/v1:TestBoard?menu=manageBoard\u0026order=desc)\n//\n// ###### [A](/r/gnoland/boards2/v1:TestBoard/1)\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) `owner` on 2009-02-13 11:31pm UTC\n// **0 replies • 0 reposts**\n"},{"name":"z_ui_board_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_board_03_filetest\n\n// Render readonly board.\npackage z_ui_board_03_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tboardName         = \"TestBoard\"\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Create a readonly board and then add a thread\n\tboardID := boards2.CreateBoard(cross(cur), boardName, false, false)\n\tboards2.CreateThread(cross(cur), boardID, \"A\", \"Body\")\n\tboards2.FreezeBoard(cross(cur), boardID)\n}\n\nfunc main() {\n\tprintln(boards2.Render(boardName))\n}\n\n// Output:\n// # [Boards](/r/gnoland/boards2/v1) › TestBoard\n// \u003e [!WARNING] Info\n// \u003e Creating new threads and commenting are disabled within this board\n//\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) on 2009-02-13 11:31pm UTC, #1\n// [List Members](/r/gnoland/boards2/v1:TestBoard/members) • [Unfreeze Board](/r/gnoland/boards2/v1$help\u0026func=UnfreezeBoard\u0026boardID=1\u0026replyID=\u0026threadID=)\n//\n// ---\n// Sort by: [newest first](/r/gnoland/boards2/v1:TestBoard?order=desc)\n//\n// ###### [A](/r/gnoland/boards2/v1:TestBoard/1)\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) `owner` on 2009-02-13 11:31pm UTC\n// **0 replies • 0 reposts**\n"},{"name":"z_ui_board_04_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_board_04_filetest\n\n// Render default board view when there are no threads.\npackage z_ui_board_04_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tboardName         = \"TestBoard\"\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateBoard(cross(cur), boardName, false, false)\n}\n\nfunc main() {\n\tprintln(boards2.Render(boardName))\n}\n\n// Output:\n// # [Boards](/r/gnoland/boards2/v1) › TestBoard\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) on 2009-02-13 11:31pm UTC, #1\n// ↳ [Create Thread](/r/gnoland/boards2/v1:TestBoard/create-thread) • [Request Invite](/r/gnoland/boards2/v1$help\u0026func=RequestInvite\u0026boardID=1) • [Manage Board](?menu=manageBoard)\n//\n// ---\n// ### This board doesn't have any threads\n// Do you want to [start a new conversation](/r/gnoland/boards2/v1:TestBoard/create-thread) in this board?\n"},{"name":"z_ui_board_05_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_board_05_filetest\n\n// An invalid ?page= (out of range, zero, negative, or non-numeric) clamps to\n// the last valid page instead of aborting the render or echoing a broken\n// \"page N of M\" picker (see newClampedPager). Notably a NEGATIVE page is not\n// rejected by pager.New, so it must be caught by the clamp.\npackage z_ui_board_05_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tboardName         = \"test-board\"\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboardID := boards2.CreateBoard(cross(cur), boardName, false, false)\n\t// pageSizeDefault is 6, so 7 threads span 2 pages; the last page is 2.\n\tfor i := 0; i \u003c 7; i++ {\n\t\tboards2.CreateThread(cross(cur), boardID, \"T\", \"Body\")\n\t}\n}\n\nfunc main() {\n\t// Each value is invalid: too high, zero, negative, non-numeric. All must\n\t// clamp to the last page (\"page 2 of 2\"); if any slipped through, the\n\t// picker would echo the bad number (e.g. \"page -5 of 2\") and this fails.\n\tok := true\n\tfor _, q := range []string{\"?page=99\", \"?page=0\", \"?page=-5\", \"?page=abc\"} {\n\t\tif !strings.Contains(boards2.Render(boardName+q), \"page 2 of 2\") {\n\t\t\tok = false\n\t\t}\n\t}\n\tprintln(ok)\n}\n\n// Output:\n// true\n"},{"name":"z_ui_board_members_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_board_members_00_filetest\n\n// Render board members view.\npackage z_ui_board_members_00_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tboardName         = \"BoardName\"\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateBoard(cross(cur), boardName, false, false)\n}\n\nfunc main() {\n\tpath := boardName + \"/members\"\n\tprintln(boards2.Render(path))\n}\n\n// Output:\n// # BoardName Members\n// ### These are the board members\n// | Member | Role | Actions |\n// | --- | --- | --- |\n// | [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) | owner | [remove](/r/gnoland/boards2/v1$help\u0026func=RemoveMember\u0026boardID=1\u0026member=g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) • [change role](/r/gnoland/boards2/v1$help\u0026func=ChangeMemberRole\u0026boardID=1\u0026member=g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\u0026role=) |\n"},{"name":"z_ui_home_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_home_00_filetest\n\n// Render default realm view.\n// Default realm view must render the list of listed boards.\npackage z_ui_home_00_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Create board \"AAA\" with a single thread\n\tboardID := boards2.CreateBoard(cross(cur), \"AAA\", true, false)\n\tboards2.CreateThread(cross(cur), boardID, \"Foo\", \"Bar\")\n\n\t// Create 2 more boards\n\tboards2.CreateBoard(cross(cur), \"BBB\", true, false)\n\tboards2.CreateBoard(cross(cur), \"CCC\", true, false)\n\tboards2.CreateBoard(cross(cur), \"DDD\", false, false) // \u003c-- Unlisted board\n}\n\nfunc main() {\n\tprintln(boards2.Render(\"\"))\n}\n\n// Output:\n// # Boards\n// [Create Board](/r/gnoland/boards2/v1:create-board) • [List Admin Users](/r/gnoland/boards2/v1:admin-users) • [Help](/r/gnoland/boards2/v1:help)\n//\n// ---\n// Sort by: [newest first](/r/gnoland/boards2/v1:?order=desc)\n//\n// ###### [AAA](/r/gnoland/boards2/v1:AAA)\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) on 2009-02-13 11:31pm UTC, #1\n// **1 threads**\n//\n// ###### [BBB](/r/gnoland/boards2/v1:BBB)\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) on 2009-02-13 11:31pm UTC, #2\n// **0 threads**\n//\n// ###### [CCC](/r/gnoland/boards2/v1:CCC)\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) on 2009-02-13 11:31pm UTC, #3\n// **0 threads**\n"},{"name":"z_ui_home_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_home_01_filetest\n\n// Render boards sorted from newest to oldest.\npackage z_ui_home_01_filetest\n\nimport (\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.CreateBoard(cross(cur), \"AAA\", true, false)\n\tboards2.CreateBoard(cross(cur), \"BBB\", true, false)\n\tboards2.CreateBoard(cross(cur), \"CCC\", true, false)\n}\n\nfunc main() {\n\tprintln(boards2.Render(\"?order=desc\"))\n}\n\n// Output:\n// # Boards\n// [Create Board](/r/gnoland/boards2/v1:create-board) • [List Admin Users](/r/gnoland/boards2/v1:admin-users) • [Help](/r/gnoland/boards2/v1:help)\n//\n// ---\n// Sort by: [oldest first](/r/gnoland/boards2/v1:?order=asc)\n//\n// ###### [CCC](/r/gnoland/boards2/v1:CCC)\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) on 2009-02-13 11:31pm UTC, #3\n// **0 threads**\n//\n// ###### [BBB](/r/gnoland/boards2/v1:BBB)\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) on 2009-02-13 11:31pm UTC, #2\n// **0 threads**\n//\n// ###### [AAA](/r/gnoland/boards2/v1:AAA)\n// Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) on 2009-02-13 11:31pm UTC, #1\n// **0 threads**\n"},{"name":"z_ui_home_02_filetest.gno","body":"// Render default realm view when there are no boards.\npackage main\n\nimport (\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nfunc main() {\n\tprintln(boards2.Render(\"\"))\n}\n\n// Output:\n// # Boards\n// [Create Board](/r/gnoland/boards2/v1:create-board) • [List Admin Users](/r/gnoland/boards2/v1:admin-users) • [Help](/r/gnoland/boards2/v1:help)\n//\n// ---\n// ### Currently there are no boards\n// Be the first to [create a new board](/r/gnoland/boards2/v1:create-board)!\n"},{"name":"z_ui_reply_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_reply_00_filetest\n\n// Render comment/reply view.\npackage z_ui_reply_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tboardName         = \"test-board\"\n)\n\nvar (\n\tthreadID boards.ID\n\treplyID  boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Create a board and a thread\n\tboardID := boards2.CreateBoard(cross(cur), boardName, false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"Foo\", \"Body\")\n\n\t// Create two comments and a reply to a comment\n\tboards2.CreateReply(cross(cur), boardID, threadID, 0, \"First comment\")\n\n\treplyID = boards2.CreateReply(cross(cur), boardID, threadID, 0, \"Second comment\")\n\tboards2.CreateReply(cross(cur), boardID, threadID, replyID, \"Third comment\")\n}\n\nfunc main() {\n\tpath := boardName + \"/\" + threadID.String() + \"/\" + replyID.String()\n\tprintln(boards2.Render(path))\n}\n\n// Output:\n// ## Foo\n//\n// **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC\n//\n//\n// \u003cgno-foreign\u003e\n// Body\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/flag) • [Repost](/r/gnoland/boards2/v1:test-board/1/repost) • [Comment](/r/gnoland/boards2/v1:test-board/1/reply) [2] • [Edit](/r/gnoland/boards2/v1:test-board/1/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteThread\u0026boardID=1\u0026threadID=1) • [Show all Replies](/r/gnoland/boards2/v1:test-board/1)\n//\n//\n// \u003e\n// \u003e **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC [\\#3](/r/gnoland/boards2/v1:test-board/1/3)\n// \u003e\n// \u003e\n// \u003e \u003cgno-foreign\u003e\n// \u003e Second comment\n// \u003e \u003c/gno-foreign\u003e\n// \u003e\n// \u003e\n// \u003e\n// \u003e ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/3/flag) • [Reply](/r/gnoland/boards2/v1:test-board/1/3/reply) [1] • [Edit](/r/gnoland/boards2/v1:test-board/1/3/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteReply\u0026boardID=1\u0026replyID=3\u0026threadID=1)\n//\n// ---\n// Sort by: [newest first](/r/gnoland/boards2/v1:test-board/1/3?order=desc)\n// \u003e\n// \u003e \u003e\n// \u003e \u003e **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC [\\#4](/r/gnoland/boards2/v1:test-board/1/4)\n// \u003e \u003e\n// \u003e \u003e\n// \u003e \u003e \u003cgno-foreign\u003e\n// \u003e \u003e Third comment\n// \u003e \u003e \u003c/gno-foreign\u003e\n// \u003e \u003e\n// \u003e \u003e\n// \u003e \u003e\n// \u003e \u003e ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/4/flag) • [Reply](/r/gnoland/boards2/v1:test-board/1/4/reply) • [Edit](/r/gnoland/boards2/v1:test-board/1/4/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteReply\u0026boardID=1\u0026replyID=4\u0026threadID=1)\n"},{"name":"z_ui_reply_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_reply_01_filetest\n\n// Render comment/reply view of a deleted comment.\npackage z_ui_reply_01_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tboardName         = \"test-board\"\n)\n\nvar (\n\tthreadID boards.ID\n\treplyID  boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Create a board and a thread\n\tboardID := boards2.CreateBoard(cross(cur), boardName, false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"Foo\", \"Body\")\n\n\t// Create a comments with a reply\n\treplyID = boards2.CreateReply(cross(cur), boardID, threadID, 0, \"Second comment\")\n\tboards2.CreateReply(cross(cur), boardID, threadID, replyID, \"Third comment\")\n\n\t// Delete the comment\n\tboards2.DeleteReply(cross(cur), boardID, threadID, replyID)\n}\n\nfunc main() {\n\tpath := boardName + \"/\" + threadID.String() + \"/\" + replyID.String()\n\tprintln(boards2.Render(path))\n}\n\n// Output:\n// ## Foo\n//\n// **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC\n//\n//\n// \u003cgno-foreign\u003e\n// Body\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/flag) • [Repost](/r/gnoland/boards2/v1:test-board/1/repost) • [Comment](/r/gnoland/boards2/v1:test-board/1/reply) [1] • [Edit](/r/gnoland/boards2/v1:test-board/1/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteThread\u0026boardID=1\u0026threadID=1) • [Show all Replies](/r/gnoland/boards2/v1:test-board/1)\n//\n//\n// \u003e\n// \u003e **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC [\\#2](/r/gnoland/boards2/v1:test-board/1/2)\n// \u003e\n// \u003e\n// \u003e \u003cgno-foreign\u003e\n// \u003e ⚠ This comment has been deleted\n// \u003e \u003c/gno-foreign\u003e\n// \u003e\n// \u003e\n// \u003e\n// \u003e ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/2/flag) • [Reply](/r/gnoland/boards2/v1:test-board/1/2/reply) [1] • [Edit](/r/gnoland/boards2/v1:test-board/1/2/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteReply\u0026boardID=1\u0026replyID=2\u0026threadID=1)\n//\n// ---\n// Sort by: [newest first](/r/gnoland/boards2/v1:test-board/1/2?order=desc)\n// \u003e\n// \u003e \u003e\n// \u003e \u003e **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC [\\#3](/r/gnoland/boards2/v1:test-board/1/3)\n// \u003e \u003e\n// \u003e \u003e\n// \u003e \u003e \u003cgno-foreign\u003e\n// \u003e \u003e Third comment\n// \u003e \u003e \u003c/gno-foreign\u003e\n// \u003e \u003e\n// \u003e \u003e\n// \u003e \u003e\n// \u003e \u003e ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/3/flag) • [Reply](/r/gnoland/boards2/v1:test-board/1/3/reply) • [Edit](/r/gnoland/boards2/v1:test-board/1/3/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteReply\u0026boardID=1\u0026replyID=3\u0026threadID=1)\n"},{"name":"z_ui_reply_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_reply_02_filetest\n\n// Render comment/reply view of a flagged comment.\npackage z_ui_reply_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tboardName         = \"test-board\"\n)\n\nvar (\n\tthreadID boards.ID\n\treplyID  boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Create a board and a thread\n\tboardID := boards2.CreateBoard(cross(cur), boardName, false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"Foo\", \"Body\")\n\n\t// Create a comments with a reply\n\treplyID = boards2.CreateReply(cross(cur), boardID, threadID, 0, \"Second comment\")\n\tboards2.CreateReply(cross(cur), boardID, threadID, replyID, \"Third comment\")\n\n\t// Flag the comment\n\tboards2.FlagReply(cross(cur), boardID, threadID, replyID, \"Reason\")\n}\n\nfunc main() {\n\tpath := boardName + \"/\" + threadID.String() + \"/\" + replyID.String()\n\tprintln(boards2.Render(path))\n}\n\n// Output:\n// ## Foo\n//\n// **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC\n//\n//\n// \u003cgno-foreign\u003e\n// Body\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/flag) • [Repost](/r/gnoland/boards2/v1:test-board/1/repost) • [Comment](/r/gnoland/boards2/v1:test-board/1/reply) [1] • [Edit](/r/gnoland/boards2/v1:test-board/1/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteThread\u0026boardID=1\u0026threadID=1) • [Show all Replies](/r/gnoland/boards2/v1:test-board/1)\n//\n//\n// \u003e\n// \u003e **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC [\\#2](/r/gnoland/boards2/v1:test-board/1/2)\n// \u003e ⚠ Reply is hidden as it has been flagged as [inappropriate](/r/gnoland/boards2/v1:test-board/1/2/flagging-reasons)\n//\n// ---\n// Sort by: [newest first](/r/gnoland/boards2/v1:test-board/1/2?order=desc)\n// \u003e\n// \u003e \u003e\n// \u003e \u003e **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC [\\#3](/r/gnoland/boards2/v1:test-board/1/3)\n// \u003e \u003e\n// \u003e \u003e\n// \u003e \u003e \u003cgno-foreign\u003e\n// \u003e \u003e Third comment\n// \u003e \u003e \u003c/gno-foreign\u003e\n// \u003e \u003e\n// \u003e \u003e\n// \u003e \u003e\n// \u003e \u003e ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/3/flag) • [Reply](/r/gnoland/boards2/v1:test-board/1/3/reply) • [Edit](/r/gnoland/boards2/v1:test-board/1/3/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteReply\u0026boardID=1\u0026replyID=3\u0026threadID=1)\n"},{"name":"z_ui_reply_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_reply_03_filetest\n\n// Render the \"reply to a comment\" form: the parent-comment preview is now\n// shown inside a labeled \u003cgno-foreign\u003e sandbox (was md.Blockquote, which\n// gave no sandboxing).\npackage z_ui_reply_03_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tboardName         = \"test-board\"\n)\n\nvar (\n\tthreadID boards.ID\n\treplyID  boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboardID := boards2.CreateBoard(cross(cur), boardName, false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"Foo\", \"Body\")\n\treplyID = boards2.CreateReply(cross(cur), boardID, threadID, 0, \"Parent comment body\")\n}\n\nfunc main() {\n\t// The \".../{reply}/reply\" route renders the parent-preview branch.\n\tpath := boardName + \"/\" + threadID.String() + \"/\" + replyID.String() + \"/reply\"\n\tcontent := boards2.Render(path)\n\tprintln(strings.Contains(content, \"Replying to a comment posted by\") \u0026\u0026\n\t\tstrings.Contains(content, `\u003cgno-foreign label=\"Quoted comment\"\u003e`) \u0026\u0026\n\t\tstrings.Contains(content, \"Parent comment body\"))\n}\n\n// Output:\n// true\n"},{"name":"z_ui_reply_04_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_reply_04_filetest\n\n// Re-rooting at a depth-2 reply renders its parent as context with a\n// \"Continue this thread →\" drill-up link (the parent is itself a reply with\n// children), instead of a \"View Thread\" jump to the thread root.\npackage z_ui_reply_04_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid := boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid := boards2.CreateThread(cross(cur), bid, \"Foo\", \"OP body\")\n\taid := boards2.CreateReply(cross(cur), bid, tid, 0, \"comment A\") // #2, parent = thread\n\tboards2.CreateReply(cross(cur), bid, tid, aid, \"reply B\")        // #3, parent = A\n}\n\nfunc main(cur realm) {\n\t// Re-root at reply #3 (B); its parent #2 (A) renders as context and, being\n\t// a reply with children, links \"Continue this thread →\" (to A's re-root).\n\tout := boards2.Render(\"test-board/1/3\")\n\tok := strings.Contains(out, \"Continue this thread →\") \u0026\u0026\n\t\tstrings.Contains(out, \"/r/gnoland/boards2/v1:test-board/1/2\") // → A's re-root, not the thread root\n\tprintln(ok)\n}\n\n// Output:\n// true\n"},{"name":"z_ui_thread_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_thread_00_filetest\n\n// Render default thread view.\npackage z_ui_thread_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tboardName         = \"test-board\"\n)\n\nvar threadID boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Create a board and a thread\n\tboardID := boards2.CreateBoard(cross(cur), boardName, false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"Foo\", \"Body\")\n\n\t// Create two comments and a reply to a comment\n\tboards2.CreateReply(cross(cur), boardID, threadID, 0, \"First comment\")\n\n\treplyID := boards2.CreateReply(cross(cur), boardID, threadID, 0, \"Second comment\")\n\tboards2.CreateReply(cross(cur), boardID, threadID, replyID, \"Third comment\")\n}\n\nfunc main() {\n\tpath := boardName + \"/\" + threadID.String()\n\tprintln(boards2.Render(path))\n}\n\n// Output:\n// # [Boards](/r/gnoland/boards2/v1) › [test\\-board](/r/gnoland/boards2/v1:test-board)\n// ## Foo\n//\n// **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC\n//\n//\n// \u003cgno-foreign\u003e\n// Body\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/flag) • [Repost](/r/gnoland/boards2/v1:test-board/1/repost) • [Comment](/r/gnoland/boards2/v1:test-board/1/reply) [2] • [Edit](/r/gnoland/boards2/v1:test-board/1/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteThread\u0026boardID=1\u0026threadID=1)\n//\n// ---\n// Sort by: [newest first](/r/gnoland/boards2/v1:test-board/1?order=desc)\n//\n// \u003e\n// \u003e **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC [\\#2](/r/gnoland/boards2/v1:test-board/1/2)\n// \u003e\n// \u003e\n// \u003e \u003cgno-foreign\u003e\n// \u003e First comment\n// \u003e \u003c/gno-foreign\u003e\n// \u003e\n// \u003e\n// \u003e\n// \u003e ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/2/flag) • [Reply](/r/gnoland/boards2/v1:test-board/1/2/reply) • [Edit](/r/gnoland/boards2/v1:test-board/1/2/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteReply\u0026boardID=1\u0026replyID=2\u0026threadID=1)\n//\n// \u003e\n// \u003e **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC [\\#3](/r/gnoland/boards2/v1:test-board/1/3)\n// \u003e\n// \u003e\n// \u003e \u003cgno-foreign\u003e\n// \u003e Second comment\n// \u003e \u003c/gno-foreign\u003e\n// \u003e\n// \u003e\n// \u003e\n// \u003e ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/3/flag) • [Reply](/r/gnoland/boards2/v1:test-board/1/3/reply) [1] • [Edit](/r/gnoland/boards2/v1:test-board/1/3/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteReply\u0026boardID=1\u0026replyID=3\u0026threadID=1)\n// \u003e\n// \u003e \u003e\n// \u003e \u003e **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC [\\#4](/r/gnoland/boards2/v1:test-board/1/4)\n// \u003e \u003e\n// \u003e \u003e\n// \u003e \u003e \u003cgno-foreign\u003e\n// \u003e \u003e Third comment\n// \u003e \u003e \u003c/gno-foreign\u003e\n// \u003e \u003e\n// \u003e \u003e\n// \u003e \u003e\n// \u003e \u003e ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/4/flag) • [Reply](/r/gnoland/boards2/v1:test-board/1/4/reply) • [Edit](/r/gnoland/boards2/v1:test-board/1/4/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteReply\u0026boardID=1\u0026replyID=4\u0026threadID=1)\n"},{"name":"z_ui_thread_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_thread_01_filetest\n\n// Render thread sorting comments from newest to oldest.\npackage z_ui_thread_01_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tboardName         = \"test-board\"\n)\n\nvar threadID boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Create a board and a thread\n\tboardID := boards2.CreateBoard(cross(cur), boardName, false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"Foo\", \"Body\")\n\n\t// Create two comments and a reply to a comment\n\tboards2.CreateReply(cross(cur), boardID, threadID, 0, \"First comment\")\n\n\treplyID := boards2.CreateReply(cross(cur), boardID, threadID, 0, \"Second comment\")\n\tboards2.CreateReply(cross(cur), boardID, threadID, replyID, \"Third comment\")\n}\n\nfunc main() {\n\tpath := boardName + \"/\" + threadID.String() + \"?order=desc\"\n\tprintln(boards2.Render(path))\n}\n\n// Output:\n// # [Boards](/r/gnoland/boards2/v1) › [test\\-board](/r/gnoland/boards2/v1:test-board)\n// ## Foo\n//\n// **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC\n//\n//\n// \u003cgno-foreign\u003e\n// Body\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/flag) • [Repost](/r/gnoland/boards2/v1:test-board/1/repost) • [Comment](/r/gnoland/boards2/v1:test-board/1/reply) [2] • [Edit](/r/gnoland/boards2/v1:test-board/1/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteThread\u0026boardID=1\u0026threadID=1)\n//\n// ---\n// Sort by: [oldest first](/r/gnoland/boards2/v1:test-board/1?order=asc)\n//\n// \u003e\n// \u003e **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC [\\#3](/r/gnoland/boards2/v1:test-board/1/3)\n// \u003e\n// \u003e\n// \u003e \u003cgno-foreign\u003e\n// \u003e Second comment\n// \u003e \u003c/gno-foreign\u003e\n// \u003e\n// \u003e\n// \u003e\n// \u003e ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/3/flag) • [Reply](/r/gnoland/boards2/v1:test-board/1/3/reply) [1] • [Edit](/r/gnoland/boards2/v1:test-board/1/3/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteReply\u0026boardID=1\u0026replyID=3\u0026threadID=1)\n// \u003e\n// \u003e \u003e\n// \u003e \u003e **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC [\\#4](/r/gnoland/boards2/v1:test-board/1/4)\n// \u003e \u003e\n// \u003e \u003e\n// \u003e \u003e \u003cgno-foreign\u003e\n// \u003e \u003e Third comment\n// \u003e \u003e \u003c/gno-foreign\u003e\n// \u003e \u003e\n// \u003e \u003e\n// \u003e \u003e\n// \u003e \u003e ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/4/flag) • [Reply](/r/gnoland/boards2/v1:test-board/1/4/reply) • [Edit](/r/gnoland/boards2/v1:test-board/1/4/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteReply\u0026boardID=1\u0026replyID=4\u0026threadID=1)\n//\n// \u003e\n// \u003e **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC [\\#2](/r/gnoland/boards2/v1:test-board/1/2)\n// \u003e\n// \u003e\n// \u003e \u003cgno-foreign\u003e\n// \u003e First comment\n// \u003e \u003c/gno-foreign\u003e\n// \u003e\n// \u003e\n// \u003e\n// \u003e ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/2/flag) • [Reply](/r/gnoland/boards2/v1:test-board/1/2/reply) • [Edit](/r/gnoland/boards2/v1:test-board/1/2/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteReply\u0026boardID=1\u0026replyID=2\u0026threadID=1)\n"},{"name":"z_ui_thread_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_thread_02_filetest\n\n// Render both original thread and thread repost view.\npackage z_ui_thread_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner        address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tsrcBoardName         = \"test-board\"\n\tdstBoardName         = \"test-board-2\"\n)\n\nvar (\n\tthreadID       boards.ID\n\trepostThreadID boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Create a board and a thread\n\tboardID := boards2.CreateBoard(cross(cur), srcBoardName, false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"Foo\", \"Body\")\n\n\t// Repost thread into a different board\n\tdstBoardID := boards2.CreateBoard(cross(cur), dstBoardName, false, false)\n\trepostThreadID = boards2.CreateRepost(cross(cur), boardID, threadID, dstBoardID, \"Bar\", \"Body2\")\n}\n\nfunc main() {\n\tpath := srcBoardName + \"/\" + threadID.String()\n\tprintln(boards2.Render(path))\n\n\tprintln(\"\u003e\u003e\u003e\u003c\u003c\u003c\\n\")\n\n\tpath = dstBoardName + \"/\" + repostThreadID.String()\n\tprintln(boards2.Render(path))\n}\n\n// Output:\n// # [Boards](/r/gnoland/boards2/v1) › [test\\-board](/r/gnoland/boards2/v1:test-board)\n// ## Foo\n//\n// **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC\n//\n//\n// \u003cgno-foreign\u003e\n// Body\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/flag) • [Repost](/r/gnoland/boards2/v1:test-board/1/repost) [1] • [Comment](/r/gnoland/boards2/v1:test-board/1/reply) • [Edit](/r/gnoland/boards2/v1:test-board/1/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteThread\u0026boardID=1\u0026threadID=1)\n//\n// \u003e\u003e\u003e\u003c\u003c\u003c\n//\n// # [Boards](/r/gnoland/boards2/v1) › [test\\-board\\-2](/r/gnoland/boards2/v1:test-board-2)\n// ## Bar\n//\n// **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC\n// \u003e [!INFO]- Thread Repost\n// \u003e Original thread is [Foo](/r/gnoland/boards2/v1:test-board/1)\n// \u003e Created by [g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh) on 2009-02-13 11:31pm UTC\n//\n//\n//\n// \u003cgno-foreign\u003e\n// Body2\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// \u003e\n// \u003e\n// \u003e \u003cgno-foreign\u003e\n// \u003e Body\n// \u003e \u003c/gno-foreign\u003e\n// \u003e\n// \u003e\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test-board-2/1/flag) • [Repost](/r/gnoland/boards2/v1:test-board-2/1/repost) • [Comment](/r/gnoland/boards2/v1:test-board-2/1/reply) • [Edit](/r/gnoland/boards2/v1:test-board-2/1/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteThread\u0026boardID=2\u0026threadID=1)\n"},{"name":"z_ui_thread_03_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_thread_03_filetest\n\n// Render thread from a readonly board.\n// Rendered thread action links should be limited to readonly actions.\npackage z_ui_thread_03_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tboardName         = \"test-board\"\n)\n\nvar threadID boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Create a readonly board and then add a thread\n\tboardID := boards2.CreateBoard(cross(cur), boardName, false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"Foo\", \"Body\")\n\tboards2.FreezeBoard(cross(cur), boardID)\n}\n\nfunc main() {\n\tpath := boardName + \"/\" + threadID.String()\n\tprintln(boards2.Render(path))\n}\n\n// Output:\n// # [Boards](/r/gnoland/boards2/v1) › [test\\-board](/r/gnoland/boards2/v1:test-board)\n// ## Foo\n//\n// **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC\n//\n//\n// \u003cgno-foreign\u003e\n// Body\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/flag) • [Repost](/r/gnoland/boards2/v1:test-board/1/repost)\n"},{"name":"z_ui_thread_04_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_thread_04_filetest\n\n// Render thread repost of a deleted thread.\npackage z_ui_thread_04_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner        address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tsrcBoardName         = \"test-board\"\n\tdstBoardName         = \"test-board-2\"\n)\n\nvar repostThreadID boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Create a board and a thread\n\tboardID := boards2.CreateBoard(cross(cur), srcBoardName, false, false)\n\tthreadID := boards2.CreateThread(cross(cur), boardID, \"Foo\", \"Body\")\n\n\t// Repost thread into a different board\n\tdstBoardID := boards2.CreateBoard(cross(cur), dstBoardName, false, false)\n\trepostThreadID = boards2.CreateRepost(cross(cur), boardID, threadID, dstBoardID, \"Bar\", \"Body2\")\n\n\t// Remove the original thread\n\tboards2.DeleteThread(cross(cur), boardID, threadID)\n}\n\nfunc main() {\n\tpath := dstBoardName + \"/\" + repostThreadID.String()\n\tprintln(boards2.Render(path))\n}\n\n// Output:\n// # [Boards](/r/gnoland/boards2/v1) › [test\\-board\\-2](/r/gnoland/boards2/v1:test-board-2)\n// ## Bar\n//\n// **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC\n//\n//\n// \u003cgno-foreign\u003e\n// Body2\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// \u003e ⚠ Source post has been deleted\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test-board-2/1/flag) • [Repost](/r/gnoland/boards2/v1:test-board-2/1/repost) • [Comment](/r/gnoland/boards2/v1:test-board-2/1/reply) • [Edit](/r/gnoland/boards2/v1:test-board-2/1/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteThread\u0026boardID=2\u0026threadID=1)\n"},{"name":"z_ui_thread_05_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_thread_05_filetest\n\n// Render thread which has been flagged.\npackage z_ui_thread_05_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tboardName         = \"BoardName\"\n)\n\nvar threadID boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Create a readonly board and then add a thread\n\tboardID := boards2.CreateBoard(cross(cur), boardName, false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"Foo\", \"Body\")\n\n\t// Flag the thread\n\tboards2.SetFlaggingThreshold(cross(cur), boardID, 1)\n\tboards2.FlagThread(cross(cur), boardID, threadID, \"Reason\")\n}\n\nfunc main() {\n\tpath := boardName + \"/\" + threadID.String()\n\tprintln(boards2.Render(path))\n}\n\n// Output:\n// ⚠ Thread has been flagged as [inappropriate](/r/gnoland/boards2/v1:BoardName/1/flagging-reasons)\n"},{"name":"z_ui_thread_06_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_thread_06_filetest\n\n// Render thread repost of a flagged thread.\npackage z_ui_thread_06_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner        address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tsrcBoardName         = \"test-board\"\n\tdstBoardName         = \"test-board-2\"\n)\n\nvar repostThreadID boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Create a board and a thread\n\tboardID := boards2.CreateBoard(cross(cur), srcBoardName, false, false)\n\tthreadID := boards2.CreateThread(cross(cur), boardID, \"Foo\", \"Body\")\n\n\t// Repost thread into a different board\n\tdstBoardID := boards2.CreateBoard(cross(cur), dstBoardName, false, false)\n\trepostThreadID = boards2.CreateRepost(cross(cur), boardID, threadID, dstBoardID, \"Bar\", \"Body2\")\n\n\t// Flag original thread\n\tboards2.SetFlaggingThreshold(cross(cur), boardID, 1)\n\tboards2.FlagThread(cross(cur), boardID, threadID, \"Reason\")\n}\n\nfunc main() {\n\tpath := dstBoardName + \"/\" + repostThreadID.String()\n\tprintln(boards2.Render(path))\n}\n\n// Output:\n// # [Boards](/r/gnoland/boards2/v1) › [test\\-board\\-2](/r/gnoland/boards2/v1:test-board-2)\n// ## Bar\n//\n// **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC\n//\n//\n// \u003cgno-foreign\u003e\n// Body2\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// \u003e ⚠ Source post has been flagged as inappropriate\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test-board-2/1/flag) • [Repost](/r/gnoland/boards2/v1:test-board-2/1/repost) • [Comment](/r/gnoland/boards2/v1:test-board-2/1/reply) • [Edit](/r/gnoland/boards2/v1:test-board-2/1/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteThread\u0026boardID=2\u0026threadID=1)\n"},{"name":"z_ui_thread_07_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_thread_07_filetest\n\n// Render thread with a title that contains Markdown\npackage z_ui_thread_07_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner     address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tboardName         = \"test-board\"\n)\n\nvar threadID boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\t// Create a board and a thread\n\tboardID := boards2.CreateBoard(cross(cur), boardName, false, false)\n\tthreadID = boards2.CreateThread(cross(cur), boardID, \"[Foo](https://foo.com)\", \"Body\")\n}\n\nfunc main() {\n\tpath := boardName + \"/\" + threadID.String()\n\tprintln(boards2.Render(path))\n}\n\n// Output:\n// # [Boards](/r/gnoland/boards2/v1) › [test\\-board](/r/gnoland/boards2/v1:test-board)\n// ## \\[Foo\\]\\(https://foo\\.com\\)\n//\n// **[g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh](/u/g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh)** `owner` · 2009-02-13 11:31pm UTC\n//\n//\n// \u003cgno-foreign\u003e\n// Body\n// \u003c/gno-foreign\u003e\n//\n//\n//\n// ↳ [Flag](/r/gnoland/boards2/v1:test-board/1/flag) • [Repost](/r/gnoland/boards2/v1:test-board/1/repost) • [Comment](/r/gnoland/boards2/v1:test-board/1/reply) • [Edit](/r/gnoland/boards2/v1:test-board/1/edit) • [Delete](/r/gnoland/boards2/v1$help\u0026func=DeleteThread\u0026boardID=1\u0026threadID=1)\n"},{"name":"z_ui_thread_08_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_thread_08_filetest\n\n// A thread large enough to exceed the foreign-block render budget\n// degrades gracefully: rendering stops before gnoweb's per-render\n// foreign-block cap would blank comments, and a \"More replies — view\n// full thread\" notice is shown instead (see maxRenderedBodies). The\n// reply count and assertion are derived from MaxBlocksPerRender so this\n// stays a truncation test if the cap changes.\npackage z_ui_thread_08_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\t\"gno.land/p/nt/markdown/foreign/v0\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"OP body\")\n\n\t// One top-level comment with many direct sub-replies (sub-replies\n\t// are not paginated, so they consume the shared render budget).\n\t// Create MaxBlocksPerRender of them — strictly more than the budget\n\t// (cap minus a margin) — so rendering must truncate.\n\trid := boards2.CreateReply(cross(cur), bid, tid, 0, \"top comment\")\n\tfor i := 0; i \u003c foreign.MaxBlocksPerRender(); i++ {\n\t\tboards2.CreateReply(cross(cur), bid, tid, rid, \"sub reply\")\n\t}\n}\n\nfunc main(cur realm) {\n\tcontent := boards2.Render(\"test-board/1\")\n\tn := strings.Count(content, \"\u003cgno-foreign\u003e\")\n\t// The top comment's many sub-replies are capped inline at pageSizeReplies\n\t// (so n stays well under the foreign-block budget); the rest are reachable\n\t// via the comment's paginated re-rooted view (\"View all N replies\").\n\tcapped := n \u003e 0 \u0026\u0026 n \u003c foreign.MaxBlocksPerRender()/4\n\tprintln(capped \u0026\u0026 strings.Contains(content, \"View all 256 replies\"))\n}\n\n// Output:\n// true\n"},{"name":"z_ui_thread_09_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_thread_09_filetest\n\n// The flat \"all comments\" view (?flat=1) paginates ThreadMeta.AllReplies so\n// every comment is reachable, unlike the recursive threaded view which\n// truncates a large thread. Each flat page renders one \u003cgno-foreign\u003e block\n// per comment, bounded by pageSizeFlat (50). With 60 comments the flat view\n// spans 2 pages; the last comment is reachable via newest-first (desc page 1)\n// and via page 2.\npackage z_ui_thread_09_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"OP body\")\n\t// pageSizeFlat is 50, so 60 comments span 2 flat pages.\n\tfor i := 0; i \u003c 60; i++ {\n\t\tboards2.CreateReply(cross(cur), bid, tid, 0, ufmt.Sprintf(\"comment-%d\", i))\n\t}\n}\n\nfunc main(cur realm) {\n\tp1 := boards2.Render(\"test-board/1?flat=1\")              // oldest first, page 1\n\tdesc := boards2.Render(\"test-board/1?flat=1\u0026order=desc\") // newest first, page 1\n\tp2 := boards2.Render(\"test-board/1?flat=1\u0026page=2\")       // oldest first, page 2\n\n\tok := strings.Contains(p1, \"All 60 comments\") \u0026\u0026\n\t\tstrings.Contains(p1, \"page 1 of 2\") \u0026\u0026\n\t\tstrings.Contains(p1, \"comment-0\") \u0026\u0026 // first comment is on page 1\n\t\t!strings.Contains(p1, \"comment-59\") \u0026\u0026 // last comment is NOT on oldest-first page 1\n\t\tstrings.Contains(desc, \"comment-59\") \u0026\u0026 // last comment reachable newest-first\n\t\tstrings.Contains(p2, \"comment-59\") \u0026\u0026 // and on the last page\n\t\tstrings.Contains(p2, \"page 2 of 2\")\n\tprintln(ok)\n}\n\n// Output:\n// true\n"},{"name":"z_ui_thread_10_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_thread_10_filetest\n\n// No post or comment renders more than pageSizeReplies (10) direct children\n// inline. A comment with more shows the cap inline plus a \"View all N replies\"\n// link to its re-rooted view, which paginates the children on its own ?page=\n// (a distinct path from the thread, so no pager collision).\npackage z_ui_thread_10_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid := boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid := boards2.CreateThread(cross(cur), bid, \"Foo\", \"OP body\")\n\tcid := boards2.CreateReply(cross(cur), bid, tid, 0, \"parent comment\") // reply #2\n\t// 12 direct children under the comment — past the inline cap of 10.\n\tfor i := 0; i \u003c 12; i++ {\n\t\tboards2.CreateReply(cross(cur), bid, tid, cid, ufmt.Sprintf(\"child-%d\", i))\n\t}\n}\n\nfunc main(cur realm) {\n\tthread := boards2.Render(\"test-board/1\")           // threaded view\n\treroot := boards2.Render(\"test-board/1/2\")         // re-root at the comment, page 1\n\treroot2 := boards2.Render(\"test-board/1/2?page=2\") // re-root, page 2\n\tthreadDesc := boards2.Render(\"test-board/1?order=desc\")\n\n\tok := strings.Contains(thread, \"View all 12 replies\") \u0026\u0026 // breadth cap inline + link\n\t\tstrings.Contains(reroot, \"page 1 of 2\") \u0026\u0026 // re-root paginates the children\n\t\tstrings.Contains(reroot2, \"page 2 of 2\") \u0026\u0026 // and advances to the tail\n\t\t// In a desc thread the \"View all\" link carries the order so the\n\t\t// re-root opens newest-first too; in the default (asc) view it doesn't.\n\t\tstrings.Contains(threadDesc, \"/r/gnoland/boards2/v1:test-board/1/2?order=desc\") \u0026\u0026\n\t\t!strings.Contains(thread, \"test-board/1/2?order=desc\")\n\tprintln(ok)\n}\n\n// Output:\n// true\n"},{"name":"z_ui_thread_11_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_thread_11_filetest\n\n// A comment's inline children follow the page's ?order: newest-first when the\n// thread is sorted desc, oldest-first otherwise — not always oldest-first.\npackage z_ui_thread_11_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/ufmt/v0\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid := boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid := boards2.CreateThread(cross(cur), bid, \"Foo\", \"OP body\")\n\tcid := boards2.CreateReply(cross(cur), bid, tid, 0, \"parent\") // #2\n\tfor i := 0; i \u003c 3; i++ {\n\t\tboards2.CreateReply(cross(cur), bid, tid, cid, ufmt.Sprintf(\"child-%d\", i)) // #3,#4,#5\n\t}\n}\n\nfunc main(cur realm) {\n\tdesc := boards2.Render(\"test-board/1?order=desc\")\n\tasc := boards2.Render(\"test-board/1\") // default = oldest first\n\n\t// desc view: the comment's children render newest-first (child-2 before child-0).\n\tdescOK := strings.Index(desc, \"child-2\") \u003c strings.Index(desc, \"child-0\")\n\t// asc view: oldest-first (child-0 before child-2).\n\tascOK := strings.Index(asc, \"child-0\") \u003c strings.Index(asc, \"child-2\")\n\tprintln(descOK \u0026\u0026 ascOK)\n}\n\n// Output:\n// true\n"},{"name":"z_ui_thread_12_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_thread_12_filetest\n\n// When the render budget is exhausted mid-page in the threaded view, the\n// offset page-picker would offer a \"next page\" that jumps past the replies\n// that were skipped when the budget ran out. Instead the picker is suppressed\n// and the reader is funneled to the complete, reachable flat view.\npackage z_ui_thread_12_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid boards.ID\n\ttid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"OP body\")\n\n\t// First top-level reply carries a deep chain that alone exhausts the\n\t// render budget (maxRenderedBodies, 246) on page 1.\n\tprev := boards2.CreateReply(cross(cur), bid, tid, 0, \"top-deep\")\n\tfor i := 0; i \u003c 250; i++ {\n\t\tprev = boards2.CreateReply(cross(cur), bid, tid, prev, \"chain\")\n\t}\n\t// Plus enough more top-level replies that the thread spans 2 pages, so a\n\t// picker WOULD render absent the suppression.\n\tfor i := 0; i \u003c 12; i++ {\n\t\tboards2.CreateReply(cross(cur), bid, tid, 0, \"top-more\")\n\t}\n}\n\nfunc main(cur realm) {\n\tout := boards2.Render(\"test-board/1\")\n\t// Budget truncated page 1: the flat \"view all comments\" link is shown,\n\t// and the content-skipping page picker (\"page 1 of N\") is suppressed.\n\tok := strings.Contains(out, \"view all comments\") \u0026\u0026\n\t\t!strings.Contains(out, \"page 1 of\")\n\tprintln(ok)\n}\n\n// Output:\n// true\n"},{"name":"z_ui_thread_13_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_thread_13_filetest\n\n// A non-numeric thread/reply ID segment in the URL is echoed back in the error\n// message; it must be escaped so a crafted URL can't inject markup/HTML into\n// the rendered page (a reflected-injection vector, live under gnoweb -html).\npackage z_ui_thread_13_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.CreateBoard(cross(cur), \"test-board\", false, false)\n}\n\nfunc main(cur realm) {\n\t// board exists, so the route reaches renderThread; \"9\u003cx\" fails Atoi and is\n\t// echoed — escaped, so the raw \"9\u003cx\" never appears (md.EscapeText → \"9\\\u003cx\").\n\tout := boards2.Render(\"test-board/9\u003cx\")\n\tok := strings.Contains(out, \"Invalid thread ID\") \u0026\u0026\n\t\t!strings.Contains(out, \"9\u003cx\")\n\tprintln(ok)\n}\n\n// Output:\n// true\n"},{"name":"z_ui_thread_14_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_ui_thread_14_filetest\n\n// In a frozen thread, a reply must not show Reply/Edit/Delete action links\n// (the backend rejects them as the thread is frozen); only Flag remains —\n// matching how the OP and a readonly board already behave.\npackage z_ui_thread_14_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar (\n\tbid      boards.ID\n\trid, tid boards.ID\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test-board\", false, false)\n\ttid = boards2.CreateThread(cross(cur), bid, \"Foo\", \"OP body\")\n\trid = boards2.CreateReply(cross(cur), bid, tid, 0, \"a reply\") // #2\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tboards2.FreezeThread(cross(cur), bid, tid)\n\n\tout := boards2.Render(\"test-board/1\")\n\t// Reply #2 keeps Flag but loses Reply/Edit/Delete in a frozen thread.\n\tok := strings.Contains(out, \"test-board/1/2/flag\") \u0026\u0026\n\t\t!strings.Contains(out, \"test-board/1/2/edit\") \u0026\u0026\n\t\t!strings.Contains(out, \"test-board/1/2/reply\")\n\tprintln(ok)\n}\n\n// Output:\n// true\n"},{"name":"z_unban_00_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_unban_00_filetest\n\npackage z_unban_00_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n)\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\tboards2.Ban(cross(cur), bid, user, boards2.BanDay, \"Unpolite behavior\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.Unban(cross(cur), bid, user, \"\")\n\n\tprintln(boards2.IsBanned(bid, user))\n}\n\n// Output:\n// false\n"},{"name":"z_unban_01_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_unban_01_filetest\n\npackage z_unban_01_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst owner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tboards2.Unban(cross(cur), bid, \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\", \"\")\n}\n\n// Error:\n// user is not banned\n"},{"name":"z_unban_02_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/boards2/v1/filetests/z_unban_02_filetest\n\npackage z_unban_02_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/gnoland/boards\"\n\n\tboards2 \"gno.land/r/gnoland/boards2/v1\"\n)\n\nconst (\n\towner address = \"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\"\n\tuser  address = \"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"\n)\n\nvar bid boards.ID\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tbid = boards2.CreateBoard(cross(cur), \"test123\", false, false)\n\tboards2.Ban(cross(cur), bid, user, boards2.BanDay, \"Unpolite behavior\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\"))\n\n\t// Try to unban without unbanning permissions\n\tboards2.Unban(cross(cur), bid, user, \"\")\n}\n\n// Error:\n// unauthorized, user g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj doesn't have the required permission\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"WgNNebstUAjGSnmairaLo9d0B7Kh3vHw4bmQRpccuzRUkr9hrX5t3HREq9I0C/+8O04VZH32Geu5TUR9JN8H6A=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1g3lsfxhvaqgdv4ccemwpnms4fv6t3aq3p5z6u7","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\"\n\t\"gno.land/p/leon/ctg\"\n\t\"gno.land/p/moul/md\"\n\t\"gno.land/p/moul/mdtable\"\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":"coins_test.gno","body":"package coins\n\nimport (\n\t\"chain\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/leon/ctg\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n)\n\nfunc TestBalanceChecker(t *testing.T) {\n\tdenom1 := \"testtoken1\"\n\tdenom2 := \"testtoken2\"\n\taddr1 := testutils.TestAddress(\"user1\")\n\taddr2 := testutils.TestAddress(\"user2\")\n\n\tcoinsRealm := testing.NewCodeRealm(\"gno.land/r/gnoland/coins\")\n\ttesting.SetRealm(coinsRealm)\n\n\ttesting.IssueCoins(addr1, chain.NewCoins(chain.NewCoin(denom1, 1000000)))\n\ttesting.IssueCoins(addr2, chain.NewCoins(chain.NewCoin(denom1, 501)))\n\n\ttesting.IssueCoins(addr2, chain.NewCoins(chain.NewCoin(denom2, 12345)))\n\n\tgnoAddr, _ := ctg.ConvertCosmosToGno(\"cosmos1s2v4tdskccx2p3yyvzem4mw5nn5fprwcku77hr\")\n\tosmoAddr := \"osmo1fl48vsnmsdzcv85q5d2q4z5ajdha8yu3aq6l09\"\n\tgnoAddr1, _ := ctg.ConvertAnyToGno(osmoAddr)\n\n\ttesting.IssueCoins(gnoAddr1, chain.NewCoins(chain.NewCoin(denom2, 12345)))\n\n\ttests := []struct {\n\t\tname      string\n\t\tpath      string\n\t\tcontains  string\n\t\twantPanic bool\n\t}{\n\t\t{\n\t\t\tname:     \"homepage\",\n\t\t\tpath:     \"\",\n\t\t\tcontains: \"# Gno.land Coins Explorer\",\n\t\t},\n\t\t// TODO: not supported yet\n\t\t// {\n\t\t// \tname:     \"total supply\",\n\t\t// \tpath:     denom,\n\t\t// \texpected: \"Balance: 1500000testtoken\",\n\t\t// },\n\t\t{\n\t\t\tname:     \"addr1's coin balance\",\n\t\t\tpath:     ufmt.Sprintf(\"balances?address=%s\u0026coin=%s\", addr1.String(), denom1),\n\t\t\tcontains: ufmt.Sprintf(\"`%s` has `%d%s`\", addr1.String(), 1000000, denom1),\n\t\t},\n\t\t{\n\t\t\tname:     \"addr2's full balances\",\n\t\t\tpath:     ufmt.Sprintf(\"balances?address=%s\", addr2.String()),\n\t\t\tcontains: ufmt.Sprintf(\"This page shows full coin balances of `%s` at block\", addr2.String()),\n\t\t},\n\t\t{\n\t\t\tname: \"addr2's full balances\",\n\t\t\tpath: ufmt.Sprintf(\"balances?address=%s\", addr2.String()),\n\t\t\tcontains: `| testtoken1 | 501 |\n| testtoken2 | 12345 |`,\n\t\t},\n\t\t{\n\t\t\tname:     \"addr2's coin balance\",\n\t\t\tpath:     ufmt.Sprintf(\"balances?address=%s\u0026coin=%s\", addr2.String(), denom1),\n\t\t\tcontains: ufmt.Sprintf(\"`%s` has `%d%s`\", addr2.String(), 501, denom1),\n\t\t},\n\t\t{\n\t\t\tname:     \"cosmos addr conversion\",\n\t\t\tpath:     \"convert/cosmos1s2v4tdskccx2p3yyvzem4mw5nn5fprwcku77hr\",\n\t\t\tcontains: ufmt.Sprintf(\"`cosmos1s2v4tdskccx2p3yyvzem4mw5nn5fprwcku77hr` on Cosmos matches `%s`\", gnoAddr),\n\t\t},\n\t\t{\n\t\t\tname:     \"balances bech32 auto convert\",\n\t\t\tpath:     ufmt.Sprintf(\"balances?address=%s\u0026coin=%s\", osmoAddr, denom1),\n\t\t\tcontains: \"Automatically converted `osmo1fl48vsnmsdzcv85q5d2q4z5ajdha8yu3aq6l09`\",\n\t\t},\n\t\t{\n\t\t\tname:     \"single coin balance bech32 auto convert\",\n\t\t\tpath:     ufmt.Sprintf(\"balances?address=%s\", osmoAddr),\n\t\t\tcontains: \"Automatically converted `osmo1fl48vsnmsdzcv85q5d2q4z5ajdha8yu3aq6l09`\",\n\t\t},\n\t\t{\n\t\t\t// The \"coin\" parameter is whatever the URL says. banker.GetCoin panics on a\n\t\t\t// malformed denom where chain.Coins.AmountOf returns zero, so this page\n\t\t\t// must be rendered from the balances already read rather than by asking\n\t\t\t// the banker for an unvalidated denom — otherwise any visitor can 500 it.\n\t\t\tname:     \"malformed coin denom renders zero instead of panicking\",\n\t\t\tpath:     ufmt.Sprintf(\"balances?address=%s\u0026coin=UPPERCASE\", addr1.String()),\n\t\t\tcontains: ufmt.Sprintf(\"`%s` has `%d%s`\", addr1.String(), 0, \"UPPERCASE\"),\n\t\t},\n\t\t{\n\t\t\tname:      \"no addr\",\n\t\t\tpath:      \"balances?address=\",\n\t\t\tcontains:  \"Please input a valid address\",\n\t\t\twantPanic: false,\n\t\t},\n\t\t{\n\t\t\tname:      \"no addr\",\n\t\t\tpath:      \"balances?address=\u0026coin=\",\n\t\t\tcontains:  \"Please input a valid address and coin denomination.\",\n\t\t\twantPanic: false,\n\t\t},\n\t\t{\n\t\t\tname:      \"invalid path\",\n\t\t\tpath:      \"invalid\",\n\t\t\tcontains:  \"404\",\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\tif tt.wantPanic {\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 panic for %s\", tt.name)\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t}\n\n\t\t\tresult := Render(tt.path)\n\t\t\tif !tt.wantPanic {\n\t\t\t\tif !strings.Contains(result, tt.contains) {\n\t\t\t\t\tt.Errorf(\"expected %s to contain %s\", result, tt.contains)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"80Pel3MORxbpyt7WJze5hGKSrIjenoHnwCzScIB/9tgkKHMg0wycBGMMNbcrKFNLiqsl1N2w7KJ0i8wR2q/6Zw=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1g3lsfxhvaqgdv4ccemwpnms4fv6t3aq3p5z6u7","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\"\n\t\"gno.land/p/demo/gnorkle/gnorkle\"\n\t\"gno.land/p/demo/gnorkle/message\"\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":"contract_test.gno","body":"package ghverify\n\nimport (\n\t\"chain/runtime/unsafe\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n)\n\nfunc TestVerificationLifecycle(cur realm, t *testing.T) {\n\tdefaultAddress := unsafe.OriginCaller()\n\tuser1Address := address(testutils.TestAddress(\"user 1\"))\n\tuser2Address := address(testutils.TestAddress(\"user 2\"))\n\n\t// Verify request returns no feeds.\n\tresult := GnorkleEntrypoint(cur, \"request\")\n\tif result != \"[]\" {\n\t\tt.Fatalf(\"expected empty request result, got %s\", result)\n\t}\n\n\t// Make a verification request with the created user.\n\ttesting.SetOriginCaller(user1Address)\n\tRequestVerification(cur, \"deelawn\")\n\n\t// A subsequent request from the same address should panic because there is\n\t// already a feed with an ID of this user's address.\n\tvar errMsg string\n\tfunc(cur realm) {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\terrMsg = r.(error).Error()\n\t\t\t}\n\t\t}()\n\t\tRequestVerification(cur, \"deelawn\")\n\t}(cur)\n\tif errMsg != \"feed already exists\" {\n\t\tt.Fatalf(\"expected feed already exists, got %s\", errMsg)\n\t}\n\n\t// Verify the request returns no feeds for this non-whitelisted user.\n\tresult = GnorkleEntrypoint(cur, \"request\")\n\tif result != \"[]\" {\n\t\tt.Fatalf(\"expected empty request result, got %s\", result)\n\t}\n\n\t// Make a verification request with the created user.\n\ttesting.SetOriginCaller(user2Address)\n\tRequestVerification(cur, \"omarsy\")\n\n\t// Set the caller back to the whitelisted user and verify that the feed data\n\t// returned matches what should have been created by the `RequestVerification`\n\t// invocation.\n\ttesting.SetOriginCaller(defaultAddress)\n\tresult = GnorkleEntrypoint(cur, \"request\")\n\texpResult := `[{\"id\":\"` + string(user1Address) + `\",\"type\":\"0\",\"value_type\":\"string\",\"tasks\":[{\"gno_address\":\"` +\n\t\tstring(user1Address) + `\",\"github_handle\":\"deelawn\"}]},` +\n\t\t`{\"id\":\"` + string(user2Address) + `\",\"type\":\"0\",\"value_type\":\"string\",\"tasks\":[{\"gno_address\":\"` +\n\t\tstring(user2Address) + `\",\"github_handle\":\"omarsy\"}]}]`\n\tif result != expResult {\n\t\tt.Fatalf(\"expected request result %s, got %s\", expResult, result)\n\t}\n\n\t// Try to trigger feed ingestion from the non-authorized user.\n\ttesting.SetOriginCaller(user1Address)\n\tfunc(cur realm) {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\terrMsg = r.(error).Error()\n\t\t\t}\n\t\t}()\n\t\tGnorkleEntrypoint(cur, \"ingest,\"+string(user1Address)+\",OK\")\n\t}(cur)\n\tif errMsg != \"caller not whitelisted\" {\n\t\tt.Fatalf(\"expected caller not whitelisted, got %s\", errMsg)\n\t}\n\n\t// Set the caller back to the whitelisted user and transfer contract ownership.\n\ttesting.SetOriginCaller(defaultAddress)\n\tSetOwner(cross(cur), defaultAddress)\n\n\t// Now trigger the feed ingestion from the user and new owner and only whitelisted address.\n\tGnorkleEntrypoint(cur, \"ingest,\"+string(user1Address)+\",OK\")\n\tGnorkleEntrypoint(cur, \"ingest,\"+string(user2Address)+\",OK\")\n\n\t// Verify the ingestion autocommitted the value and triggered the post handler.\n\tdata := Render(\"\")\n\texpResult = `{\"deelawn\": \"` + string(user1Address) + `\",\"omarsy\": \"` + string(user2Address) + `\"}`\n\tif data != expResult {\n\t\tt.Fatalf(\"expected render data %s, got %s\", expResult, data)\n\t}\n\n\t// Finally make sure the feed was cleaned up after the data was committed.\n\tresult = GnorkleEntrypoint(cur, \"request\")\n\tif result != \"[]\" {\n\t\tt.Fatalf(\"expected empty request result, got %s\", result)\n\t}\n\n\t// Check that the accessor functions are working as expected.\n\tif handle := GetHandleByAddress(cur, string(user1Address)); handle != \"deelawn\" {\n\t\tt.Fatalf(\"expected deelawn, got %s\", handle)\n\t}\n\tif address_XXX := GetAddressByHandle(cur, \"deelawn\"); address_XXX != string(user1Address) {\n\t\tt.Fatalf(\"expected %s, got %s\", string(user1Address), address_XXX)\n\t}\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"s+j5t4a13h5OPx+xw2eenEf6x+vFAogLYlWWPm62STcLgz1b8s/DrrrZ27fcOU9S/QFrRI/1NRkFjf7cN5Sr2g=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1g3lsfxhvaqgdv4ccemwpnms4fv6t3aq3p5z6u7","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\"\n\t\"gno.land/p/moul/dynreplacer\"\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(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\") // 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/v1) - 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/v1)**\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.gg/S8nKUqwkPn)\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"},{"name":"home_filetest.gno","body":"package main\n\nimport \"gno.land/r/gnoland/home\"\n\nfunc main() {\n\tprintln(home.Render(\"\"))\n}\n\n// Output:\n// # Welcome to Gno.land\n//\n// We're building Gno.land, set to become the leading open-source smart contract\n// platform, using Gno, an interpreted and fully deterministic variation of the\n// Go programming language for succinct and composable smart contracts.\n//\n// With transparent and timeless code, Gno.land is the next generation of smart\n// contract platforms, serving as the \"GitHub\" of the ecosystem, with realms built\n// using fully transparent, auditable code that anyone can inspect and reuse.\n//\n// Intuitive and easy to use, Gno.land lowers the barrier to web3 and makes\n// censorship-resistant platforms accessible to everyone. If you want to help lay\n// the foundations of a fairer and freer world, join us today.\n//\n// ---\n//\n// ## [Boards](/r/gnoland/boards2/v1) - 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//\n// Explore this ready-to-use Gno dApp, and experience decentralized social media in action.\n//\n// **[Open Boards](/r/gnoland/boards2/v1)**\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// No posts.\n//\n// \u003cgno-columns-sep\u003e\n//\n// ## [Latest Events](/events)\n//\n// No events.\n//\n// \u003c/gno-columns\u003e\n//\n// ---\n//\n// ## [Gno Playground](https://play.gno.land)\n//\n// Gno Playground is a web application designed for building, running, testing, and\n// interacting with your Gno code, enhancing your understanding of the Gno\n// language. With Gno Playground, you can share your code, execute tests, deploy\n// your realms and packages to Gno.land, and explore a multitude of other features.\n//\n// Experience 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//\n// All 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//\n// Official 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//\n// System-level realm packages used by the chain.\n//\n// [Browse](/r/sys)\n//\n// \u003cgno-columns-sep\u003e\n//\n// ### r/demo\n//\n// Demo realm packages showcasing what’s possible.\n//\n// [Browse](/r/demo)\n//\n// \u003cgno-columns-sep\u003e\n//\n// ### p/demo\n//\n// Pure 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.gg/S8nKUqwkPn)\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 #123\n//\n// \u003e Now, you Gno.\n//\n// \u003c/gno-columns\u003e\n//\n// ---\n//\n// ## Sign up for our newsletter\n//\n// Stay in the Gno by signing up for our newsletter. You'll get the scoop on dev updates, fresh content, and community news.\n//\n// [![Subscribe to stay in the Gno](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNTYiIGhlaWdodD0iNDQiIHZpZXdCb3g9IjAgMCAyNTYgNDQiPjxzdHlsZT50ZXh0e2ZvbnQtZmFtaWx5OnNhbnMtc2VyaWY7Zm9udC1zaXplOjE0cHg7dGV4dC1hbmNob3I6bWlkZGxlO2RvbWluYW50LWJhc2VsaW5lOm1pZGRsZTt9PC9zdHlsZT48cmVjdCB4PSIwIiB5PSIwIiB3aWR0aD0iMjU2IiBoZWlnaHQ9IjQ0IiByeD0iOCIgcnk9IjgiIGZpbGw9IiMyMjZjNTciIC8+PHRleHQgeD0iMTI4IiB5PSIyMiIgZHg9IjAiIGR5PSIwIiByb3RhdGU9IiIgZmlsbD0iI2ZmZmZmZiIgPlN1YnNjcmliZSB0byBzdGF5IGluIHRoZSBHbm88L3RleHQ+PC9zdmc+)](https://land.us18.list-manage.com/subscribe?u=8befe3303cf82796d2c1a1aff\u0026id=271812000b)\n//\n// ---\n//\n// **This is a testnet.** Package names are not guaranteed to be available for production.\n"},{"name":"override_filetest.gno","body":"// PKGPATH: gno.land/r/gnoland/home/filetests/override_filetest\n\npackage override_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/r/gnoland/home\"\n)\n\nfunc main(cur realm) {\n\tvar admin = address(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\")\n\ttesting.SetOriginCaller(admin)\n\thome.AdminSetOverride(cross(cur), \"Hello World!\")\n\tprintln(\"---\")\n\tprintln(home.Render(\"\"))\n\n\tnewAdmin := testutils.TestAddress(\"newAdmin\")\n\thome.AdminTransferOwnership(cross(cur), newAdmin)\n\tif err := revive(func() {\n\t\thome.AdminSetOverride(cross(cur), \"Not admin anymore\")\n\t}); err == nil {\n\t\tpanic(\"AdminSetOverride should have aborted the transaction\")\n\t}\n}\n\n// Output:\n// ---\n// Hello World!\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"81bfEObAw+uq7qB3hsxuLfSCokYHqyI5htV51ka7ATdqmvLtnszFVDa0eFEC9b58YPd/oqXkci3bXRaoGoSLHA=="}],"memo":""}},{"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/demo/tokens/grc20\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/r/demo/defi/grc20reg\"\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"},{"name":"z0_filetest.gno","body":"// PKGPATH: gno.land/r/test\npackage test\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/r/gnoland/wugnot\"\n)\n\nvar (\n\taddr1 = testutils.TestAddress(\"test1\")\n\taddrc = chain.PackageAddress(\"gno.land/r/gnoland/wugnot\")\n)\n\nfunc main(cur realm) {\n\t// issue ugnots\n\ttesting.IssueCoins(addr1, chain.Coins{{\"ugnot\", 100000001}})\n\tprintBalances()\n\t// println(wugnot.Render(\"queues\"))\n\t// println(\"A -\", wugnot.Render(\"\"))\n\n\t// deposit of 123400ugnot from addr1\n\t// origin send must be simulated\n\tcoins := chain.Coins{{\"ugnot\", 123_400}}\n\ttesting.SetOriginCaller(addr1)\n\ttesting.SetOriginSend(coins)\n\tbanker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(addr1, addrc, coins)\n\twugnot.Deposit(cross(cur))\n\tprintBalances()\n\n\t// withdraw of 4242ugnot to addr1\n\twugnot.Withdraw(cross(cur), 4242)\n\tprintBalances()\n}\n\nfunc printBalances() {\n\tprintSingleBalance := func(name string, addr address) {\n\t\twugnotBal := wugnot.BalanceOf(addr)\n\t\ttesting.SetOriginCaller(addr)\n\t\trobanker := banker.NewReadonlyBanker()\n\t\tcoins := robanker.GetCoins(addr).AmountOf(\"ugnot\")\n\t\tfmt.Printf(\"| %-13s | addr=%s | wugnot=%-6d | ugnot=%-9d |\\n\",\n\t\t\tname, addr, wugnotBal, coins)\n\t}\n\tprintln(\"-----------\")\n\tprintSingleBalance(\"wugnot\", addrc)\n\tprintSingleBalance(\"addr1\", addr1)\n\tprintln(\"-----------\")\n}\n\n// Output:\n// -----------\n// | wugnot        | addr=g15vj5q08amlvyd0nx6zjgcvwq2d0gt9fcchrvum | wugnot=0      | ugnot=0         |\n// | addr1         | addr=g1w3jhxap3ta047h6lta047h6lta047h6l4mfnm7 | wugnot=0      | ugnot=100000001 |\n// -----------\n// -----------\n// | wugnot        | addr=g15vj5q08amlvyd0nx6zjgcvwq2d0gt9fcchrvum | wugnot=0      | ugnot=123400    |\n// | addr1         | addr=g1w3jhxap3ta047h6lta047h6lta047h6l4mfnm7 | wugnot=123400 | ugnot=99876601  |\n// -----------\n// -----------\n// | wugnot        | addr=g15vj5q08amlvyd0nx6zjgcvwq2d0gt9fcchrvum | wugnot=0      | ugnot=119158    |\n// | addr1         | addr=g1w3jhxap3ta047h6lta047h6lta047h6l4mfnm7 | wugnot=119158 | ugnot=99880843  |\n// -----------\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"/cK/hbLScVljjgH11c7GVs66CFIID5S6YQ5T9hZPTB9V/IuKSOD+M19PENVVv/MjOpCh1uYjZfdbciOTQeHo6w=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1g73v2anukg4ej7axwqpthsatzrxjsh0wk797da","package":{"name":"memberstore","path":"gno.land/r/gov/dao/v3/memberstore","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/gov/dao/v3/memberstore\"\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/demo/svg\"\n\t\"gno.land/p/moul/md\"\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/mux/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/v3/memberstore: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/v3/memberstore)\")\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 v3\"))\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":"memberstore_test.gno","body":"package memberstore\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nfunc TestPower(t *testing.T) {\n\tms := NewMembersByTier()\n\taddMembers(ms, 100, T1)\n\taddMembers(ms, 100, T2)\n\taddMembers(ms, 100, T3)\n\n\ttiers.Iterate(\"\", \"\", func(key string, value interface{}) bool {\n\t\tpo := value.(Tier).PowerHandler(ms, tiers)\n\t\tif key == T1 \u0026\u0026 po != 3.0 {\n\t\t\tt.Fatal(\"wrong value for T1\")\n\t\t}\n\t\tif key == T2 \u0026\u0026 po != 2.0 {\n\t\t\tt.Fatal(\"wrong value for T2\")\n\t\t}\n\t\tif key == T3 \u0026\u0026 po != 1.0 {\n\t\t\tt.Fatal(\"wrong value for T3\")\n\t\t}\n\n\t\treturn false\n\t})\n\n\tms = NewMembersByTier()\n\taddMembers(ms, 100, T1)\n\taddMembers(ms, 50, T2)\n\taddMembers(ms, 10, T3)\n\n\ttiers.Iterate(\"\", \"\", func(key string, value interface{}) bool {\n\t\tpo := value.(Tier).PowerHandler(ms, tiers)\n\t\tif key == T1 \u0026\u0026 po != 3.0 {\n\t\t\tt.Fatal(\"wrong value for T1\")\n\t\t}\n\t\tif key == T2 \u0026\u0026 po != 2.0 {\n\t\t\tt.Fatal(\"wrong value for T2\")\n\t\t}\n\t\tif key == T3 \u0026\u0026 po != 1.0 {\n\t\t\tt.Fatal(\"wrong value for T3\")\n\t\t}\n\n\t\treturn false\n\t})\n\n\tms = NewMembersByTier()\n\taddMembers(ms, 100, T1)\n\taddMembers(ms, 200, T2)\n\taddMembers(ms, 100, T3)\n\n\ttiers.Iterate(\"\", \"\", func(key string, value interface{}) bool {\n\t\tpo := value.(Tier).PowerHandler(ms, tiers)\n\t\tif key == T1 \u0026\u0026 po != 3.0 {\n\t\t\tt.Fatal(\"wrong value for T1\")\n\t\t}\n\t\tif key == T2 \u0026\u0026 po != 1.0 {\n\t\t\tt.Fatal(\"wrong value for T2\")\n\t\t}\n\t\tif key == T3 \u0026\u0026 po != 1.0 {\n\t\t\tt.Fatal(\"wrong value for T3\")\n\t\t}\n\n\t\treturn false\n\t})\n\n\tms = NewMembersByTier()\n\taddMembers(ms, 100, T1)\n\taddMembers(ms, 200, T2)\n\taddMembers(ms, 1000, T3)\n\n\ttiers.Iterate(\"\", \"\", func(key string, value interface{}) bool {\n\t\tpo := value.(Tier).PowerHandler(ms, tiers)\n\t\tif key == T1 \u0026\u0026 po != 3.0 {\n\t\t\tt.Fatal(\"wrong value for T1\")\n\t\t}\n\t\tif key == T2 \u0026\u0026 po != 1.0 {\n\t\t\tt.Fatal(\"wrong value for T2\")\n\t\t}\n\t\tif key == T3 \u0026\u0026 po != 0.1 {\n\t\t\tt.Fatal(\"wrong value for T3\")\n\t\t}\n\n\t\treturn false\n\t})\n}\n\nfunc TestCreateMembers(t *testing.T) {\n\tms := NewMembersByTier()\n\tprintln(\"adding members...\")\n\taddMembers(ms, 10, \"T1\")\n\tprintln(\"added T1\")\n\taddMembers(ms, 100, \"T2\")\n\tprintln(\"added T2\")\n\taddMembers(ms, 1000, \"T3\")\n\tprintln(\"added T3\")\n\n\tm, tier := ms.GetMember(address(\"11T3\"))\n\turequire.Equal(t, \"T3\", tier)\n\n\tm, tier = ms.GetMember(address(\"2000T1\"))\n\turequire.Equal(t, \"\", tier)\n\tif m != nil {\n\t\tt.Fatal(\"member must be nil if not found\")\n\t}\n\n\ttier = ms.RemoveMember(address(\"1T1\"))\n\turequire.Equal(t, \"T1\", tier)\n}\n\nfunc addMembers(ms MembersByTier, c int, tier string) {\n\t// mt := avl.NewTree() XXX\n\tms.SetTier(tier)\n\tfor i := 0; i \u003c c; i++ {\n\t\taddr := address(strconv.Itoa(i) + tier)\n\t\tif err := ms.SetMember(tier, addr, \u0026Member{}); err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t}\n}\n\nfunc TestRenderMembersToleratesMalformedPath(t *testing.T) {\n\tms := NewMembersByTier()\n\taddMembers(ms, 3, T1)\n\t// A control byte makes url.Parse reject the path; RenderMembers must\n\t// degrade to the first page rather than nil-deref / panic (Render is an\n\t// unauthenticated, read-only path).\n\tout := RenderMembers(\"?\\x01\", ms)\n\turequire.True(t, len(out) \u003e 0, \"malformed path must render, not panic\")\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\"\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\"\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/bptree/v0/pager\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/p/samcrew/tablesort\"\n\t\"gno.land/p/samcrew/urlfilter\"\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/v3/memberstore\") + \"\\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"},{"name":"z0_filetest.gno","body":"// PKGPATH: gno.land/r/test/exploit\npackage exploit\n\nimport (\n\t\"gno.land/r/gov/dao/v3/memberstore\"\n)\n\nfunc main() {\n\t// After the fix, memberstore.Tiers is no longer accessible (lowercase 'tiers')\n\t// External realms can only use the safe accessor functions:\n\t// - memberstore.GetTier(name) - read-only tier access\n\t// - memberstore.IterateTiers(fn) - read-only iteration\n\t// - memberstore.GetTierPower(name, members) - calculated power\n\n\t// Verify we can still READ tier data via the safe accessor\n\tt3, ok := memberstore.GetTier(memberstore.T3)\n\tif !ok {\n\t\tpanic(\"T3 tier not found\")\n\t}\n\tprintln(\"T3 BasePower (read-only):\", t3.BasePower)\n\tprintln(\"T3 InvitationPoints (read-only):\", t3.InvitationPoints)\n\n\t// The following lines would cause a compile error if uncommented:\n\t// memberstore.Tiers.Set(...) // ERROR: Tiers is not exported (lowercase)\n\n\t// Iterate over tiers (read-only)\n\tprintln(\"All tiers:\")\n\tmemberstore.IterateTiers(func(name string, tier memberstore.Tier) bool {\n\t\tprintln(\"  -\", name, \"BasePower:\", tier.BasePower)\n\t\treturn false\n\t})\n\n\tprintln(\"Security fix verified: external realms cannot modify tiers\")\n}\n\n// Output:\n// T3 BasePower (read-only): 1\n// T3 InvitationPoints (read-only): 1\n// All tiers:\n//   - T1 BasePower: 3\n//   - T2 BasePower: 2\n//   - T3 BasePower: 1\n// Security fix verified: external realms cannot modify tiers\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"kms8Fm8I6IrW1v5fhjhOnvBMbKhHFJ8QVe9G97LWvLAaK1IkZVy9Q7euNGf5Cry43jAG1OoBbuxDtGzDJTj27w=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"treasury","path":"gno.land/r/gov/dao/v3/treasury","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/gov/dao/v3/treasury\"\ngno = \"0.9\"\n"},{"name":"treasury.gno","body":"package treasury\n\nimport (\n\t\"chain/banker\"\n\n\t\"gno.land/p/demo/tokens/grc20\"\n\tt \"gno.land/p/nt/treasury/v0\"\n\n\t\"gno.land/r/demo/defi/grc20reg\"\n\t\"gno.land/r/gov/dao\"\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/v3/treasury:.../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\ttokenKeys = 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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"DpYDLJeLtHMRhvFFSlEQA8zFBSNW1n4qbNmomxTwqmQ2mMDTtpIycp7QZS2qahnjFgBgu9KFTyKNeeRR3leYMg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1g73v2anukg4ej7axwqpthsatzrxjsh0wk797da","package":{"name":"impl","path":"gno.land/r/gov/dao/v3/impl","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/v3/treasury/test), 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)\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":"clamp_test.gno","body":"package impl\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// Sanitizing costs ~11,310 gas/byte, and rendering is reachable unauthenticated\n// through vm/qrender under a 3,000,000,000 gas cap. ExecutorCreationRealm is\n// dispatched through the public dao.Executor interface, so a hostile executor\n// computes it per call and stores almost nothing: unclamped, a ~250KB value\n// costs over 3G gas in one render and bricks the proposal page for everyone.\n// Measured on the real render path: 2,839,117,770 gas unclamped versus\n// 18,749,984 clamped. About 265KB of input crosses the query cap entirely.\nfunc TestClampFieldBoundsSanitizerInput(t *testing.T) {\n\tuassert.Equal(t, \"short\", clampField(\"short\", maxRenderedRealm),\n\t\t\"a value within the bound must pass through untouched\")\n\n\thuge := strings.Repeat(\"a\", 250000)\n\tgot := clampField(huge, maxRenderedRealm)\n\tuassert.True(t, len(got) \u003c maxRenderedRealm+32,\n\t\t\"the clamped value must be bounded by the limit, not by the input\")\n\tuassert.True(t, strings.HasSuffix(got, \"… truncated\"),\n\t\t\"a clamped value must say it was cut rather than look authored short\")\n}\n\n// Cutting at a byte offset can land inside a multi-byte rune; the sanitizer\n// tolerates invalid UTF-8, but handing it a split rune is sloppy and would\n// render a replacement character mid-path.\nfunc TestClampFieldCutsOnRuneBoundary(t *testing.T) {\n\t// 3-byte runes, so a 256-byte cut lands mid-rune (256 = 85*3 + 1).\n\tgot := clampField(strings.Repeat(\"世\", 200), maxRenderedRealm)\n\tbody := strings.TrimSuffix(got, \"… truncated\")\n\n\tuassert.True(t, len(body)%3 == 0,\n\t\t\"the cut must land on a rune boundary\")\n\tuassert.Equal(t, strings.Repeat(\"世\", len(body)/3), body,\n\t\t\"every retained rune must be intact\")\n}\n\n// Boundary and malformed input. clampField does byte arithmetic and backs off\n// over UTF-8 continuation bytes, so the interesting cases are the ones where\n// that loop has nowhere to back off to.\nfunc TestClampFieldBoundaries(t *testing.T) {\n\texact := strings.Repeat(\"a\", maxRenderedRealm)\n\tuassert.Equal(t, exact, clampField(exact, maxRenderedRealm),\n\t\t\"a value exactly at the bound must not be marked truncated\")\n\n\tover := strings.Repeat(\"a\", maxRenderedRealm+1)\n\tuassert.True(t, strings.HasSuffix(clampField(over, maxRenderedRealm), \"… truncated\"),\n\t\t\"one byte over the bound must be cut\")\n\n\t// Already-invalid UTF-8: every byte is a continuation, so the backoff\n\t// walks to zero. Must degrade to the marker rather than panic or loop.\n\tcont := strings.Repeat(\"\\x80\", maxRenderedRealm+10)\n\tuassert.Equal(t, \"… truncated\", clampField(cont, maxRenderedRealm),\n\t\t\"an all-continuation string must degrade to just the marker\")\n\n\tuassert.Equal(t, \"… truncated\", clampField(\"abc\", 0),\n\t\t\"a zero bound must still terminate\")\n}\n"},{"name":"denied_reason_test.gno","body":"package impl\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/r/gov/dao/v3/memberstore\"\n)\n\n// DeniedReason is \"execution failed: \" + err.Error() (govdao.gno), and that\n// error comes from the proposal's executor callback — which any third-party\n// realm can supply (see govdao_execute_reject_proposal.txtar, where the\n// executor lives in gno.land/r/test/request). Rendered raw it let a failing\n// proposal write markdown straight beneath the \"PROPOSAL HAS BEEN DENIED\"\n// line, including a forged heading and vote tally.\n//\n// Operates on proposalStatus.String directly rather than through a real\n// proposal, so it does not disturb the proposal ids and counts that the other\n// tests in this package assert against shared realm state.\nfunc TestDeniedReasonCannotForgePageStructure(cur realm, t *testing.T) {\n\tps := newProposalStatus([]string{memberstore.T1})\n\tps.Denied = true\n\tps.DeniedReason = \"execution failed: boom\\n\\n### Stats\\n\\n- **PROPOSAL HAS BEEN ACCEPTED**\\n\\n---\\n\u003cdiv\u003eswallow the tally\"\n\n\tout := ps.String(0, cur)\n\n\tuassert.False(t, strings.Contains(out, \"\\n### Stats\"),\n\t\t\"an injected heading must not survive into the rendered stats block\")\n\tuassert.False(t, strings.Contains(out, \"\\n- **PROPOSAL HAS BEEN ACCEPTED**\"),\n\t\t\"an injected list item must not forge an acceptance line\")\n\tuassert.False(t, strings.Contains(out, \"\\n---\\n\"),\n\t\t\"an injected horizontal rule must not survive\")\n\n\t// Emphasis and raw HTML are residue that sanitize.Block would have left\n\t// live; InlineText escapes both. A reader must not see a bold\n\t// \"ACCEPTED\" on a denied proposal, and a \u003cdiv\u003e must not open an HTML\n\t// block that swallows the vote tally rendered after it.\n\tuassert.False(t, strings.Contains(out, \"**PROPOSAL HAS BEEN ACCEPTED**\"),\n\t\t\"injected bold text must not forge an acceptance line\")\n\tuassert.False(t, strings.Contains(out, \"\u003cdiv\u003e\"),\n\t\t\"injected raw HTML must not open a block that swallows the tally\")\n\n\t// Folding is the property InlineText adds over the alternatives: the whole\n\t// reason must land on the REASON: line, so nothing after a newline can be\n\t// read as new top-level markdown. Asserted by requiring the payload's LAST\n\t// segment on the same line as its first.\n\treason := out[strings.Index(out, \"REASON: \"):]\n\tfirstLine := reason[:strings.Index(reason, \"\\n\")]\n\tuassert.True(t, strings.Contains(firstLine, \"swallow the tally\"),\n\t\t\"the entire reason must be folded onto the REASON line\")\n}\n\n// ...and ordinary error text stays readable. InlineText backslash-escapes\n// markdown punctuation, so the raw output carries \"Boom\\!\" — but a\n// backslash-escaped punctuation mark renders as the bare character, so a\n// reader sees \"Boom!\". Words and spacing are untouched.\nfunc TestDeniedReasonKeepsPlainTextIntact(cur realm, t *testing.T) {\n\tps := newProposalStatus([]string{memberstore.T1})\n\tps.Denied = true\n\tps.DeniedReason = \"execution failed: Boom!\"\n\n\tuassert.True(t, strings.Contains(ps.String(0, cur), `REASON: execution failed: Boom\\!`),\n\t\t\"a plain denial reason must stay on the REASON line, escaped but readable\")\n}\n\n// The reason reaches an unauthenticated render path and InlineText costs\n// ~6,990 gas/byte, so it must be bounded before it is escaped, not after.\n// Asserts the clamp at the call site, not clampField in isolation.\n//\n// The payload is exclamation marks, not letters, and that choice is the whole\n// test. InlineText escapes \"!\" to \"\\!\" but leaves letters alone, so with a\n// letter payload the escaped text is the same length as the raw text and both\n// orderings produce identical output — the test would pass either way and\n// prove nothing. With punctuation, escaping doubles the length, and the two\n// orderings become tellable apart.\nfunc TestDeniedReasonIsClampedBeforeSanitizing(cur realm, t *testing.T) {\n\tps := newProposalStatus([]string{memberstore.T1})\n\tps.Denied = true\n\tps.DeniedReason = strings.Repeat(\"!\", 50000)\n\n\tout := ps.String(0, cur)\n\n\t// The clamp bounds what goes INTO the escaper, so a full maxRenderedReason\n\t// characters survive and the escaped output is about twice that. Clamping\n\t// the escaped text instead would leave only half as many, and the escaper\n\t// would still have processed all 50,000 characters — exactly the cost the\n\t// clamp exists to avoid.\n\tuassert.True(t, strings.Count(out, \"!\") \u003e= maxRenderedReason,\n\t\t\"the clamp must bound the escaper's input, not its output\")\n\tuassert.True(t, len(out) \u003c 4*maxRenderedReason,\n\t\t\"the rendered stats block must still be bounded by the clamp\")\n\tuassert.True(t, strings.Contains(out, \"… truncated\"),\n\t\t\"a clamped reason must be marked as cut\")\n}\n"},{"name":"executor_disclosure_filetest.gno","body":"// PKGPATH: gno.land/r/test/disclosure\npackage disclosure\n\n// Covers the executor-disclosure changes in an isolated realm. The unit tests\n// in the impl package share proposal ids across files (govdao_test.gno asserts\n// a hard-coded id) and swap the DAO implementation partway through, so these\n// live here instead.\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/r/gov/dao\"\n\t\"gno.land/r/gov/dao/v3/impl\"\n\t\"gno.land/r/gov/dao/v3/memberstore\"\n)\n\nconst user address = \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"\n\nfunc init(cur realm) {\n\tmemberstore.Get(0, cur).DeleteAll()\n\tmemberstore.Get(0, cur).SetTier(memberstore.T1)\n\tmemberstore.Get(0, cur).SetMember(memberstore.T1, user, memberstore.NewMember(3))\n\tdao.UpdateImpl(cross(cur), dao.NewUpdateRequest(impl.NewGovDAO(), nil))\n}\n\n// hostileExecutor implements dao.Executor directly rather than through\n// NewSimpleExecutor, which is what lets it choose its own CreationRealm.\n// CreationRealm() is dispatched through the public dao.Executor interface, so\n// only SimpleExecutor's value is VM-supplied from rlm.PkgPath().\ntype hostileExecutor struct{}\n\nfunc (e *hostileExecutor) Execute(cur realm) error { return nil }\n\nfunc (e *hostileExecutor) String() string { return \"\" }\n\nfunc (e *hostileExecutor) CreationRealm() string {\n\treturn \"gno.land/r/sys/params\\n\\n### Stats\\n\\n- **PROPOSAL HAS BEEN ACCEPTED**\\n- YES PERCENT: 100%\\n\\n---\\n\"\n}\n\n// blankExecutor's CreationRealm is non-empty but strips to nothing:\n// sanitize.InlineCode removes bidi and zero-width characters, so it returns \"\".\ntype blankExecutor struct{}\n\nfunc (e *blankExecutor) Execute(cur realm) error { return nil }\n\nfunc (e *blankExecutor) String() string { return \"\" }\n\nfunc (e *blankExecutor) CreationRealm() string { return \"\\u200b\\u200b\\u202e\" }\n\n// whitespaceExecutor covers the other half of the guard: plain whitespace,\n// which InlineCode would otherwise wrap in a padded, empty-looking span.\ntype whitespaceExecutor struct{}\n\nfunc (e *whitespaceExecutor) Execute(cur realm) error { return nil }\n\nfunc (e *whitespaceExecutor) String() string { return \"\" }\n\nfunc (e *whitespaceExecutor) CreationRealm() string { return \"   \\t \" }\n\n// hugeExecutor computes a very large CreationRealm while storing nothing.\n// Sanitizing costs ~11,310 gas/byte and render is reachable unauthenticated\n// under a 3,000,000,000 gas cap, so this must be clamped before escaping.\ntype hugeExecutor struct{}\n\nfunc (e *hugeExecutor) Execute(cur realm) error { return nil }\n\nfunc (e *hugeExecutor) String() string { return \"\" }\n\nfunc (e *hugeExecutor) CreationRealm() string { return strings.Repeat(\"z\", 20000) }\n\n// fenceExecutor attacks the code span itself. Section 4 below sends backticks\n// through the grant sentence, but that path escapes the value directly. The\n// creation realm is clamped first and escaped second, so it needs its own\n// case: the fence is chosen after the cut, and must still outscan whatever\n// backticks survived it. The run here is two long, so a two-backtick fence\n// would be closed by the payload.\ntype fenceExecutor struct{}\n\nfunc (e *fenceExecutor) Execute(cur realm) error { return nil }\n\nfunc (e *fenceExecutor) String() string { return \"\" }\n\nfunc (e *fenceExecutor) CreationRealm() string { return \"gno.land/r/evil`` **INJECTED**\" }\n\n// wsExecutor returns a large run of spaces. TrimSpace used to run before the\n// clamp, so it scanned every byte of whatever the executor returned: 250KB of\n// spaces cost 1,368,719,824 gas to render nothing at all, and 560KB cost\n// 3,048,904,520 — past the query cap, so the page could not be rendered by\n// anyone. Clamping first bounds the scan; the same 560KB now costs 16,657,792.\ntype wsExecutor struct{}\n\nfunc (e *wsExecutor) Execute(cur realm) error { return nil }\n\nfunc (e *wsExecutor) String() string { return \"\" }\n\nfunc (e *wsExecutor) CreationRealm() string { return strings.Repeat(\" \", 20000) }\n\nfunc main(cur realm) {\n\ttesting.SetOriginCaller(user)\n\n\t// 1. An executor with NO description. The creation realm used to share the\n\t// `ExecutorString() != \"\"` gate with the description, so it was hidden for\n\t// every such proposal — 16 call sites across 7 production realms.\n\t// SetRealm first: NewSimpleExecutor captures rlm.PkgPath(), which is empty\n\t// outside a code realm.\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/template/silent\"))\n\tsilent := dao.NewSimpleExecutor(0, cur, func(realm) error { return nil }, \"\")\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tpid := dao.MustCreateProposal(cross(cur), dao.NewProposalRequest(\n\t\t\"Silent\", \"A proposal whose executor has no description\", silent))\n\tout := dao.Render(cross(cur), pid.String())\n\n\tprintln(\"empty-description proposal discloses creation realm:\",\n\t\tstrings.Contains(out, \"Executor created in: `gno.land/r/template/silent`\"))\n\tprintln(\"and prints no empty metadata block:\",\n\t\t!strings.Contains(out, \"This proposal contains the following metadata\"))\n\n\t// 2. CreationRealm() is dispatched through the public dao.Executor\n\t// interface, so a third-party executor picks its own value — and the\n\t// disclosure now renders for every proposal. InlineCode does not delete the\n\t// hostile text; it folds it onto one line inside a code span, where it can\n\t// no longer forge page structure. So assert structure, not absence.\n\thpid := dao.MustCreateProposal(cross(cur), dao.NewProposalRequest(\n\t\t\"Hostile\", \"A proposal whose executor forges page structure\", \u0026hostileExecutor{}))\n\thout := dao.Render(cross(cur), hpid.String())\n\n\tprintln(\"only the genuine Stats heading exists:\",\n\t\tstrings.Count(hout, \"\\n### Stats\") == 1)\n\tprintln(\"no forged acceptance line:\",\n\t\t!strings.Contains(hout, \"\\n- **PROPOSAL HAS BEEN ACCEPTED**\"))\n\tprintln(\"no forged tally line:\",\n\t\t!strings.Contains(hout, \"\\n- YES PERCENT: 100%\"))\n\tprintln(\"genuine tally and status still render:\",\n\t\tstrings.Contains(hout, \"\\n- YES PERCENT: 0%\") \u0026\u0026\n\t\t\tstrings.Contains(hout, \"- **Proposal is open for votes**\"))\n\t// One line, inside a code span: the newlines are folded to spaces, so none\n\t// of the payload can start a block. (No pad space before the value now —\n\t// TrimSpace removes the payload's trailing newline, so InlineCode does not\n\t// need to pad the fence.)\n\tprintln(\"hostile value is confined to one code-span line:\",\n\t\tstrings.Contains(hout, \"Executor created in: `gno.land/r/sys/params  ### Stats\"))\n\n\t// 3. The upgrade proposal rewrites AllowedDAOs — the sole authorization for\n\t// replacing the implementation, mutating the member store and moving\n\t// treasury funds. It used to carry an empty description, so the realm\n\t// receiving that authority appeared nowhere a voter would read.\n\tupid := dao.MustCreateProposal(cross(cur),\n\t\timpl.NewUpgradeDaoImplRequest(cross(cur), impl.NewGovDAO(), \"gno.land/r/gov/dao/v4/impl\", \"reason\"))\n\tuout := dao.Render(cross(cur), upid.String())\n\n\tprintln(\"upgrade proposal states the grant:\",\n\t\tstrings.Contains(uout, \"may replace the implementation, mutate the member store, or move treasury funds\"))\n\tprintln(\"upgrade proposal names the granted realm:\",\n\t\tstrings.Contains(uout, \"`gno.land/r/gov/dao/v4/impl`\"))\n\n\t// 4. realmPkg is caller-supplied and lands inside a code span. md.EscapeText\n\t// was wrong there: CommonMark 6.1 does not process backslash escapes inside\n\t// code spans, so it rendered visible backslashes, and a backtick closed the\n\t// span early. InlineCode widens the fence instead, so the payload stays\n\t// inside it as literal text.\n\tbpid := dao.MustCreateProposal(cross(cur),\n\t\timpl.NewUpgradeDaoImplRequest(cross(cur), impl.NewGovDAO(),\n\t\t\t\"gno.land/r/x` **PROPOSAL HAS BEEN ACCEPTED** `\", \"reason\"))\n\tbout := dao.Render(cross(cur), bpid.String())\n\n\t// The payload's own backtick sits INSIDE a widened `` fence, so it renders\n\t// as literal code rather than closing the span and freeing the bold text.\n\tprintln(\"fence widened to contain the backtick:\",\n\t\tstrings.Contains(bout, \"`` gno.land/r/x` **PROPOSAL HAS BEEN ACCEPTED** ` ``\"))\n\tprintln(\"no forged acceptance line from the breakout attempt:\",\n\t\t!strings.Contains(bout, \"\\n- **PROPOSAL HAS BEEN ACCEPTED**\"))\n\tprintln(\"no visible backslashes in the path:\",\n\t\t!strings.Contains(bout, \"gno\\\\.land\"))\n\n\t// 4b. Guarding the raw value would print the label with nothing after it\n\t// for a creation realm that sanitizes away entirely.\n\tzpid := dao.MustCreateProposal(cross(cur), dao.NewProposalRequest(\n\t\t\"Blank\", \"A proposal whose creation realm strips to nothing\", \u0026blankExecutor{}))\n\tzout := dao.Render(cross(cur), zpid.String())\n\n\tprintln(\"a creation realm that strips to nothing prints no bare label:\",\n\t\t!strings.Contains(zout, \"Executor created in:\"))\n\n\twpid := dao.MustCreateProposal(cross(cur), dao.NewProposalRequest(\n\t\t\"Whitespace\", \"A proposal whose creation realm is only whitespace\", \u0026whitespaceExecutor{}))\n\tprintln(\"a whitespace-only creation realm prints no bare label:\",\n\t\t!strings.Contains(dao.Render(cross(cur), wpid.String()), \"Executor created in:\"))\n\n\thupid := dao.MustCreateProposal(cross(cur), dao.NewProposalRequest(\n\t\t\"Huge\", \"A proposal whose creation realm is enormous\", \u0026hugeExecutor{}))\n\thurendered := dao.Render(cross(cur), hupid.String())\n\t// The truncation marker must sit INSIDE the code span, so the value ends\n\t// with its closing fence. That is what proves the clamp ran before the\n\t// escaping and not after. Cutting an already-escaped value slices the\n\t// closing fence off and leaves the span hanging open, and a length check\n\t// alone cannot tell the two apart — both produce a short string ending in\n\t// the marker.\n\tprintln(\"an enormous creation realm is clamped before escaping:\",\n\t\tlen(hurendered) \u003c 2000 \u0026\u0026 strings.Contains(hurendered, \"… truncated`\"))\n\n\t// 4c. The same breakout attempt through the creation realm, which is\n\t// clamped before it is escaped. The fence must be sized from the clamped\n\t// string, so it widens to three backticks and the payload stays literal.\n\tfpid := dao.MustCreateProposal(cross(cur), dao.NewProposalRequest(\n\t\t\"Fence\", \"A proposal whose creation realm tries to close the code span\", \u0026fenceExecutor{}))\n\tfout := dao.Render(cross(cur), fpid.String())\n\n\tprintln(\"fence outscans the payload's backtick run:\",\n\t\tstrings.Contains(fout, \"Executor created in: ```gno.land/r/evil`` **INJECTED**```\"))\n\tprintln(\"no bold text escapes the code span:\",\n\t\t!strings.Contains(fout, \"\\n**INJECTED**\"))\n\n\t// 4d. A large all-whitespace creation realm. Clamping before trimming is\n\t// what bounds the work here, and the marker is how the test can tell: cut\n\t// first and the marker survives the trim, so the label renders. Trim first\n\t// and the value collapses to nothing, printing no label — and the trim has\n\t// already walked every byte the executor produced.\n\twpid2 := dao.MustCreateProposal(cross(cur), dao.NewProposalRequest(\n\t\t\"BigWhitespace\", \"A proposal whose creation realm is a huge run of spaces\", \u0026wsExecutor{}))\n\twout2 := dao.Render(cross(cur), wpid2.String())\n\n\tprintln(\"a huge whitespace creation realm is clamped before trimming:\",\n\t\tstrings.Contains(wout2, \"Executor created in: `… truncated`\"))\n\n\t// 5. Proposals live on the proxy but their voting status lives on the\n\t// GovDAO instance, so replacing the implementation leaves earlier\n\t// proposals renderable but statusless. renderProposalPage took a\n\t// user-supplied pid and dereferenced that nil status.\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/gov/dao/v3/impl\"))\n\tdao.UpdateImpl(cross(cur), dao.NewUpdateRequest(impl.NewGovDAO(), nil))\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tprintln(\"a proposal orphaned by an upgrade renders instead of panicking:\",\n\t\tstrings.Contains(dao.Render(cross(cur), pid.String()), \"not available\"))\n}\n\n// Output:\n// empty-description proposal discloses creation realm: true\n// and prints no empty metadata block: true\n// only the genuine Stats heading exists: true\n// no forged acceptance line: true\n// no forged tally line: true\n// genuine tally and status still render: true\n// hostile value is confined to one code-span line: true\n// upgrade proposal states the grant: true\n// upgrade proposal names the granted realm: true\n// fence widened to contain the backtick: true\n// no forged acceptance line from the breakout attempt: true\n// no visible backslashes in the path: true\n// a creation realm that strips to nothing prints no bare label: true\n// a whitespace-only creation realm prints no bare label: true\n// an enormous creation realm is clamped before escaping: true\n// fence outscans the payload's backtick run: true\n// no bold text escapes the code span: true\n// a huge whitespace creation realm is clamped before trimming: true\n// a proposal orphaned by an upgrade renders instead of panicking: true\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/v3/impl\"\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/v3/memberstore\"\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":"govdao_execute_proposal_00_filetest.gno","body":"// PKGPATH: gno.land/r/test/govdao\npackage govdao\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/gov/dao\"\n\t\"gno.land/r/gov/dao/v3/impl\"\n\t\"gno.land/r/gov/dao/v3/memberstore\"\n)\n\nconst user address = \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"\n\nvar (\n\texecutor   dao.Executor\n\tproposalID dao.ProposalID\n\trenderPath string\n\tgovdao     = impl.NewGovDAO()\n)\n\nfunc init(cur realm) {\n\t// Initialize GovDAO members\n\tmemberstore.Get(0, cur).DeleteAll()\n\tmemberstore.Get(0, cur).SetTier(memberstore.T1)\n\tmemberstore.Get(0, cur).SetMember(memberstore.T1, user, memberstore.NewMember(3))\n\tdao.UpdateImpl(cross(cur), dao.NewUpdateRequest(impl.NewGovDAO(), nil))\n\n\t// Create an executor that always fails\n\tcb := func(realm) error { return errors.New(\"Boom!\") }\n\texecutor = dao.NewSimpleExecutor(0, cur, cb, \"\")\n\n\t// Create a proposal request that fails on execution\n\trequest := dao.NewProposalRequest(\"Test\", \"This proposal always fails on execution\", executor)\n\n\t// Create the proposal from a realm so GovDAO instance is able to render the proposal\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tproposalID = dao.MustCreateProposal(cross(cur), request)\n\trenderPath = strconv.FormatUint(uint64(proposalID), 10)\n\n\t// Register proposal with the local GovDAO instance\n\tgovdao.PostCreateProposal(0, cur, request, proposalID)\n}\n\nfunc main(cur realm) {\n\t// Execute proposal, status should be REJECTED\n\terr := govdao.ExecuteProposal(0, cur, proposalID, executor)\n\n\tprintln(err.Error())\n\tprintln()\n\tprintln(govdao.Render(cross(cur), \"gno.land/r/gov/dao/v3/impl\", renderPath))\n}\n\n// Output:\n// Boom!\n//\n// ## Prop #0 - Test\n// Author: g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n//\n// This proposal always fails on execution\n//\n// Executor created in: `gno.land/r/test/govdao`\n//\n//\n//\n//\n// ---\n//\n// ### Stats\n// - **PROPOSAL HAS BEEN DENIED**\n// REASON: execution failed: Boom\\!\n// - Tiers eligible to vote: T1, T2, T3\n// - YES PERCENT: 0%\n// - NO PERCENT: 0%\n// - ABSTAIN PERCENT: 0%\n//\n// [Detailed voting list](/r/gov/dao/v3/impl:0/votes)\n//\n// ---\n//\n// ### Actions\n// [Vote YES](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=YES\u0026pid=0) | [Vote NO](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=NO\u0026pid=0) | [Vote ABSTAIN](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=ABSTAIN\u0026pid=0)\n//\n// WARNING: Please double check transaction data before voting.\n"},{"name":"govdao_execute_proposal_01_filetest.gno","body":"// PKGPATH: gno.land/r/test/govdao\npackage govdao\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/gov/dao\"\n\t\"gno.land/r/gov/dao/v3/impl\"\n\t\"gno.land/r/gov/dao/v3/memberstore\"\n)\n\nconst user address = \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"\n\nvar (\n\texecutor   dao.Executor\n\tproposalID dao.ProposalID\n\trenderPath string\n\tgovdao     = impl.NewGovDAO()\n)\n\nfunc init(cur realm) {\n\t// Initialize GovDAO members\n\tmemberstore.Get(0, cur).DeleteAll()\n\tmemberstore.Get(0, cur).SetTier(memberstore.T1)\n\tmemberstore.Get(0, cur).SetMember(memberstore.T1, user, memberstore.NewMember(3))\n\tdao.UpdateImpl(cross(cur), dao.NewUpdateRequest(impl.NewGovDAO(), nil))\n\n\t// Create a dummy executor\n\tcb := func(realm) error { return nil }\n\texecutor = dao.NewSimpleExecutor(0, cur, cb, \"\")\n\n\t// Create a proposal request that pass on execution\n\trequest := dao.NewProposalRequest(\"Test\", \"This proposal always pass on execution\", executor)\n\n\t// Create the proposal from a realm so GovDAO instance is able to render the proposal\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tproposalID = dao.MustCreateProposal(cross(cur), request)\n\trenderPath = strconv.FormatUint(uint64(proposalID), 10)\n\n\t// Register proposal with the local GovDAO instance\n\tgovdao.PostCreateProposal(0, cur, request, proposalID)\n}\n\nfunc main(cur realm) {\n\t// Execute proposal, status should be ACTIVE\n\terr := govdao.ExecuteProposal(0, cur, proposalID, executor)\n\n\tprintln(err == nil)\n\tprintln()\n\tprintln(govdao.Render(cross(cur), \"gno.land/r/gov/dao/v3/impl\", renderPath))\n}\n\n// Output:\n// true\n//\n// ## Prop #0 - Test\n// Author: g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n//\n// This proposal always pass on execution\n//\n// Executor created in: `gno.land/r/test/govdao`\n//\n//\n//\n//\n// ---\n//\n// ### Stats\n// - **Proposal is open for votes**\n// - Tiers eligible to vote: T1, T2, T3\n// - YES PERCENT: 0%\n// - NO PERCENT: 0%\n// - ABSTAIN PERCENT: 0%\n//\n// [Detailed voting list](/r/gov/dao/v3/impl:0/votes)\n//\n// ---\n//\n// ### Actions\n// [Vote YES](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=YES\u0026pid=0) | [Vote NO](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=NO\u0026pid=0) | [Vote ABSTAIN](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=ABSTAIN\u0026pid=0)\n//\n// WARNING: Please double check transaction data before voting.\n"},{"name":"govdao_execute_proposal_02_filetest.gno","body":"// PKGPATH: gno.land/r/test/govdao\n\npackage govdao\n\nimport \"gno.land/r/gov/dao/v3/impl\"\n\nvar govdao = impl.NewGovDAO()\n\nfunc main(cur realm) {\n\t// Try to execute a proposal using a nil executor\n\tgovdao.ExecuteProposal(0, cur, 0, nil)\n}\n\n// Error:\n// an executor is required to execute the proposal\n"},{"name":"govdao_execute_proposal_03_filetest.gno","body":"// PKGPATH: gno.land/r/test/govdao\npackage govdao\n\nimport (\n\t\"gno.land/r/gov/dao\"\n\t\"gno.land/r/gov/dao/v3/impl\"\n)\n\nvar (\n\texecutor dao.Executor\n\tgovdao   = impl.NewGovDAO()\n)\n\nfunc init(cur realm) {\n\t// Create a dummy executor\n\tcb := func(realm) error { return nil }\n\texecutor = dao.NewSimpleExecutor(0, cur, cb, \"\")\n}\n\nfunc main(cur realm) {\n\t// Try to execute a proposal that doesn't exist\n\tgovdao.ExecuteProposal(0, cur, 404, executor)\n}\n\n// Error:\n// proposal not found\n"},{"name":"govdao_test.gno","body":"package impl\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n\t\"gno.land/r/gov/dao\"\n\t\"gno.land/r/gov/dao/v3/memberstore\"\n)\n\n// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\n\nfunc init(cur realm) {\n\tloadMembers(cur)\n\n\tdao.UpdateImpl(cross(cur), dao.NewUpdateRequest(govDAO, []string{\"gno.land/r/gov/dao/v3/impl\"}))\n}\n\nvar (\n\tm1    = testutils.TestAddress(\"m1\")\n\tm11   = testutils.TestAddress(\"m1.1\")\n\tm111  = testutils.TestAddress(\"m1.1.1\")\n\tm1111 = testutils.TestAddress(\"m1.1.1.1\")\n\tm2    = testutils.TestAddress(\"m2\")\n\tm3    = testutils.TestAddress(\"m3\")\n\tm4    = testutils.TestAddress(\"m4\")\n\tm5    = testutils.TestAddress(\"m5\")\n\tm6    = testutils.TestAddress(\"m6\")\n\n\tnoMember = testutils.TestAddress(\"nm1\")\n)\n\nfunc loadMembers(cur realm) {\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\tmstore := memberstore.Get(0, cur)\n\tmstore.DeleteAll()\n\n\tmstore.SetTier(memberstore.T1)\n\tmstore.SetTier(memberstore.T2)\n\tmstore.SetTier(memberstore.T3)\n\n\tmstore.SetMember(memberstore.T1, m1, memberByTier(memberstore.T1))\n\tmstore.SetMember(memberstore.T1, m11, memberByTier(memberstore.T1))\n\tmstore.SetMember(memberstore.T1, m111, memberByTier(memberstore.T1))\n\tmstore.SetMember(memberstore.T1, m1111, memberByTier(memberstore.T1))\n\n\tmstore.SetMember(memberstore.T2, m2, memberByTier(memberstore.T2))\n\tmstore.SetMember(memberstore.T2, m3, memberByTier(memberstore.T2))\n\tmstore.SetMember(memberstore.T3, m4, memberByTier(memberstore.T3))\n\tmstore.SetMember(memberstore.T3, m5, memberByTier(memberstore.T3))\n\tmstore.SetMember(memberstore.T3, m6, memberByTier(memberstore.T3))\n}\n\nfunc TestCreateProposalAndVote(cur realm, t *testing.T) {\n\tloadMembers(cur)\n\n\tportfolio := \"# This is my portfolio:\\n\\n- THINGS\"\n\n\ttesting.SetOriginCaller(noMember)\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/gov/dao/v3/impl\"))\n\n\tnm1 := testutils.TestAddress(\"nm1\")\n\n\turequire.AbortsWithMessage(t, cur, \"Only T1 and T2 members can be added by proposal. To add a T3 member use AddMember function directly.\", func(cur realm) {\n\t\tdao.MustCreateProposal(cross(cur), NewAddMemberRequest(cur, nm1, memberstore.T3, portfolio))\n\t})\n\n\turequire.AbortsWithMessage(t, cur, \"proposer is not a member\", func(cur realm) {\n\t\tdao.MustCreateProposal(cross(cur), NewAddMemberRequest(cur, nm1, memberstore.T2, portfolio))\n\t})\n\n\ttesting.SetOriginCaller(m1)\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/gov/dao/v3/impl\"))\n\n\tproposalRequest := NewAddMemberRequest(cur, nm1, memberstore.T2, portfolio)\n\n\ttesting.SetOriginCaller(m1)\n\ttesting.SetRealm(testing.NewUserRealm(m1))\n\tpid := dao.MustCreateProposal(cross(cur), proposalRequest)\n\turequire.Equal(t, int(pid), 0)\n\n\t// m1 votes yes because that member is interested on it\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(0)))\n\n\ttesting.SetOriginCaller(m11)\n\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.NoVote, dao.ProposalID(0)))\n\n\ttesting.SetOriginCaller(m2)\n\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.NoVote, dao.ProposalID(0)))\n\n\ttesting.SetOriginCaller(m3)\n\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.NoVote, dao.ProposalID(0)))\n\n\ttesting.SetOriginCaller(m4)\n\n\turequire.AbortsWithMessage(t, cur, \"member on specified tier is not allowed to vote on this proposal\", func() {\n\t\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.NoVote, dao.ProposalID(0)))\n\t})\n\n\ttesting.SetOriginCaller(m111)\n\n\t// Same effect as:\n\t// dao.MustVoteOnProposal(dao.VoteRequest{\n\t// \tOption:     dao.NoVote,\n\t// \tProposalID: dao.ProposalID(0),\n\t// })\n\tdao.MustVoteOnProposalSimple(cross(cur), 0, \"NO\")\n\n\turequire.Equal(t, true, strings.Contains(dao.Render(cross(cur), \"\"), \"Prop #0 - New T2 Member Proposal\"))\n\t// urequire.Equal(t, true, strings.Contains(dao.Render(cross(cur), \"\"), \"Author: \"+m1.String()))\n\n\turequire.AbortsWithMessage(t, cur, \"proposal didn't reach supermajority yet: 66.66\", func() {\n\t\tdao.ExecuteProposal(cross(cur), dao.ProposalID(0))\n\t})\n\n\ttesting.SetOriginCaller(m1111)\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.NoVote, dao.ProposalID(0)))\n\n\taccepted := dao.ExecuteProposal(cross(cur), dao.ProposalID(0))\n\turequire.Equal(t, false, accepted)\n\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), \"0\"), \"**PROPOSAL HAS BEEN DENIED**\"))\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), \"0\"), \"NO PERCENT: 81.25%\"))\n}\n\nfunc TestExecutorCreationRealm(cur realm, t *testing.T) {\n\tloadMembers(cur)\n\n\t// Test that executor creation realm is captured correctly\n\ttesting.SetOriginCaller(m1)\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/template/contract\"))\n\n\t// Create executor in the template contract realm\n\texecutor := dao.NewSimpleExecutor(0, cur, func(realm) error { return nil }, \"Test executor from template\")\n\n\tproposalRequest := dao.NewProposalRequest(\n\t\t\"Test Proposal\",\n\t\t\"This proposal tests executor creation realm tracking\",\n\t\texecutor,\n\t)\n\n\t// Create proposal from user realm (user can call DAO directly)\n\ttesting.SetRealm(testing.NewUserRealm(m1))\n\tpid := dao.MustCreateProposal(cross(cur), proposalRequest)\n\n\t// Get the proposal\n\tprop := dao.MustGetProposal(pid)\n\n\t// Verify the author is m1\n\turequire.Equal(t, m1, prop.Author())\n\n\t// Verify the executor creation realm is captured correctly\n\turequire.Equal(t, \"gno.land/r/template/contract\", prop.ExecutorCreationRealm())\n\n\t// Check that it's displayed in the individual proposal render output\n\tindividualRendered := dao.Render(cross(cur), pid.String())\n\t// Rendered as a code span: CreationRealm() is interface-dispatched and so\n\t// third-party controlled, and InlineCode neutralizes it while reading\n\t// naturally for a realm path.\n\turequire.Equal(t, true, contains(individualRendered, \"Executor created in: `gno.land/r/template/contract`\"))\n\turequire.Equal(t, true, contains(individualRendered, \"Test executor from template\"))\n\n\t// Also verify the main content is there\n\turequire.Equal(t, true, contains(individualRendered, \"Test Proposal\"))\n\turequire.Equal(t, true, contains(individualRendered, \"This proposal tests executor creation realm tracking\"))\n}\n\nfunc TestProposalPagination(cur realm, t *testing.T) {\n\tloadMembers(cur)\n\tportfolio := \"### This is my portfolio:\\n\\n- THINGS\"\n\n\ttesting.SetOriginCaller(m1)\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/gov/dao/v3/impl\"))\n\n\tnm1 := testutils.TestAddress(\"nm1\")\n\n\tvar pid dao.ProposalID\n\n\tproposalRequest := NewAddMemberRequest(cur, nm1, memberstore.T2, portfolio)\n\n\ttesting.SetOriginCaller(m1)\n\ttesting.SetRealm(testing.NewUserRealm(m1))\n\tpid = dao.MustCreateProposal(cross(cur), proposalRequest)\n\n\t// TODO: tests keep the same vm state: https://github.com/gnolang/gno/issues/1982\n\turequire.Equal(t, 2, int(pid))\n\n\ttesting.SetRealm(testing.NewUserRealm(m1))\n\tpid = dao.MustCreateProposal(cross(cur), proposalRequest)\n\turequire.Equal(t, 3, int(pid))\n\n\ttesting.SetRealm(testing.NewUserRealm(m1))\n\tpid = dao.MustCreateProposal(cross(cur), proposalRequest)\n\turequire.Equal(t, 4, int(pid))\n\n\ttesting.SetRealm(testing.NewUserRealm(m1))\n\tpid = dao.MustCreateProposal(cross(cur), proposalRequest)\n\turequire.Equal(t, 5, int(pid))\n\n\ttesting.SetRealm(testing.NewUserRealm(m1))\n\tpid = dao.MustCreateProposal(cross(cur), proposalRequest)\n\turequire.Equal(t, 6, int(pid))\n\n\ttesting.SetRealm(testing.NewUserRealm(m1))\n\tpid = dao.MustCreateProposal(cross(cur), proposalRequest)\n\turequire.Equal(t, 7, int(pid))\n\n\tfmt.Println(dao.Render(cross(cur), \"\"))\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), \"\"), \"### [Prop #7 - New T2 Member Proposal](/r/gov/dao:7)\"))\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), \"\"), \"### [Prop #6 - New T2 Member Proposal](/r/gov/dao:6)\"))\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), \"\"), \"### [Prop #5 - New T2 Member Proposal](/r/gov/dao:5)\"))\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), \"\"), \"### [Prop #4 - New T2 Member Proposal](/r/gov/dao:4)\"))\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), \"\"), \"### [Prop #3 - New T2 Member Proposal](/r/gov/dao:3)\"))\n\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), \"?page=2\"), \"### [Prop #2 - New T2 Member Proposal](/r/gov/dao:2)\"))\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), \"?page=2\"), \"### [Prop #1 - Test Proposal](/r/gov/dao:1)\"))\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), \"?page=2\"), \"### [Prop #0 - New T2 Member Proposal](/r/gov/dao:0)\"))\n}\n\nfunc TestUpgradeDaoImplementation(cur realm, t *testing.T) {\n\tloadMembers(cur)\n\n\ttesting.SetOriginCaller(noMember)\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/gov/dao/v3/impl\"))\n\n\turequire.PanicsWithMessage(t, cur, \"proposer is not a member\", func() {\n\t\tNewUpgradeDaoImplRequest(cur, govDAO, \"gno.land/r/gov/dao/v4/impl\", \"Something happened and we have to fix it.\")\n\t})\n\n\ttesting.SetOriginCaller(m1)\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/gov/dao/v3/impl\"))\n\n\tpreq := NewUpgradeDaoImplRequest(cur, govDAO, \"gno.land/r/gov/dao/v4/impl\", \"Something happened and we have to fix it.\")\n\n\ttesting.SetOriginCaller(m1)\n\ttesting.SetRealm(testing.NewUserRealm(m1))\n\tpid := dao.MustCreateProposal(cross(cur), preq)\n\turequire.Equal(t, int(pid), 8)\n\n\t// m1 votes yes because that member is interested on it\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(pid)))\n\n\ttesting.SetOriginCaller(m11)\n\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(pid)))\n\n\ttesting.SetOriginCaller(m2)\n\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(pid)))\n\n\ttesting.SetOriginCaller(m3)\n\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(pid)))\n\n\ttesting.SetOriginCaller(m111)\n\n\t// Same effect as:\n\t// dao.MustVoteOnProposal(dao.VoteRequest{\n\t// \tOption:     dao.YesVote,\n\t// \tProposalID: dao.ProposalID(pid),\n\t// })\n\tdao.MustVoteOnProposalSimple(cross(cur), int64(pid), \"YES\")\n\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), \"8\"), \"**Proposal is open for votes**\"))\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), \"8\"), \"68.42105263157895%\"))\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), \"8\"), \"0%\"))\n\n\taccepted := dao.ExecuteProposal(cross(cur), dao.ProposalID(pid))\n\turequire.Equal(t, true, accepted)\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), \"8\"), \"**PROPOSAL HAS BEEN ACCEPTED**\"))\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), \"8\"), \"YES PERCENT: 68.42105263157895%\"))\n}\n\nfunc TestAbstainVote(cur realm, t *testing.T) {\n\tloadMembers(cur)\n\n\tportfolio := \"# This is my portfolio:\\n\\n- THINGS\"\n\n\ttesting.SetOriginCaller(m1)\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/gov/dao/v3/impl\"))\n\n\tnm1 := testutils.TestAddress(\"nm1\")\n\tproposalRequest := NewAddMemberRequest(cur, nm1, memberstore.T2, portfolio)\n\n\ttesting.SetOriginCaller(m1)\n\ttesting.SetRealm(testing.NewUserRealm(m1))\n\tpid := dao.MustCreateProposal(cross(cur), proposalRequest)\n\n\t// m1 votes abstain\n\tdao.MustVoteOnProposalSimple(cross(cur), int64(pid), \"ABSTAIN\")\n\n\t// Other members vote YES to reach supermajority\n\ttesting.SetOriginCaller(m11)\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, pid))\n\n\ttesting.SetOriginCaller(m111)\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, pid))\n\n\ttesting.SetOriginCaller(m1111)\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, pid))\n\n\ttesting.SetOriginCaller(m2)\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, pid))\n\n\ttesting.SetOriginCaller(m3)\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, pid))\n\n\t// Verify render shows correct percentages\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), pid.String()), \"YES PERCENT: 81.25%\"))\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), pid.String()), \"NO PERCENT: 0%\"))\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), pid.String()), \"ABSTAIN PERCENT: 18.75%\"))\n\n\t// Supermajority reached despite one abstain voter\n\taccepted := dao.ExecuteProposal(cross(cur), pid)\n\turequire.Equal(t, true, accepted)\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), pid.String()), \"**PROPOSAL HAS BEEN ACCEPTED**\"))\n\n\t// Abstain voter appears in vote list\n\turequire.Equal(t, true, contains(dao.Render(cross(cur), fmt.Sprintf(\"%v/votes\", int64(pid))), \"ABSTAIN\"))\n}\n\nfunc contains(s, substr string) bool {\n\treturn strings.Index(s, substr) \u003e= 0\n}\n\n// TestAddMemberKeepsInvitationPointWhenAddFails covers the executor's ordering.\n//\n// The executor spends the proposer's invitation point and adds the member. If\n// the add fails, a returned executor error does NOT revert: ExecuteProposal\n// marks the proposal denied and ExecuteOrRejectProposal still commits the\n// transaction. So with the old order the point was gone and the member was not\n// added, permanently.\n//\n// The failure is reachable: SetMember refuses an address that is already a\n// member, and AddMember enrols T3 members directly, so proposing an existing\n// member to another tier is an ordinary mistake rather than a contrived one.\n//\n// Uses ExecuteOrRejectProposal deliberately. ExecuteProposal panics on an\n// executor error, and a panic aborts the transaction, which would revert the\n// spend and hide the bug.\nfunc TestAddMemberKeepsInvitationPointWhenAddFails(cur realm, t *testing.T) {\n\tloadMembers(cur)\n\n\t// m4 is already a T3 member, so adding it to T2 must fail in SetMember.\n\ttesting.SetOriginCaller(m1)\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/gov/dao/v3/impl\"))\n\tpreq := NewAddMemberRequest(cur, m4, memberstore.T2, \"# Portfolio\\n\\n- things\")\n\n\t// memberstore.Get requires an allowed-DAO caller, so read under the impl\n\t// realm rather than whatever the previous step left in place.\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/gov/dao/v3/impl\"))\n\tbefore, tier := memberstore.Get(0, cur).GetMember(m1)\n\turequire.Equal(t, memberstore.T1, tier)\n\tpointsBefore := before.InvitationPoints\n\turequire.Equal(t, true, pointsBefore \u003e 0, \"premise: the proposer must have a point to lose\")\n\n\ttesting.SetOriginCaller(m1)\n\ttesting.SetRealm(testing.NewUserRealm(m1))\n\tpid := dao.MustCreateProposal(cross(cur), preq)\n\n\t// A T2 addition is voted on by T1 and T2. Every one of them votes yes, so\n\t// the proposal certainly passes and the executor certainly runs -- if it did\n\t// not, this test would prove nothing.\n\tfor _, voter := range []address{m1, m11, m111, m1111, m2, m3} {\n\t\ttesting.SetOriginCaller(voter)\n\t\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(pid)))\n\t}\n\n\taccepted := dao.ExecuteOrRejectProposal(cross(cur), dao.ProposalID(pid))\n\turequire.Equal(t, false, accepted, \"the add must fail, since m4 is already a member\")\n\n\t// Proves the executor ran and returned an error, rather than the vote\n\t// failing to reach a threshold -- only GovDAO.ExecuteProposal writes this.\n\trendered := dao.Render(cross(cur), fmt.Sprintf(\"%d\", int(pid)))\n\turequire.Equal(t, true, contains(rendered, \"execution failed\"),\n\t\t\"the proposal must have been denied by the executor, not by the vote\")\n\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/gov/dao/v3/impl\"))\n\tafter, _ := memberstore.Get(0, cur).GetMember(m1)\n\turequire.Equal(t, pointsBefore, after.InvitationPoints,\n\t\t\"a failed add must not spend the proposer's invitation point\")\n}\n\n// TestPromoteToTierMissingFromStoreKeepsTheMember covers the remove-then-add\n// hazard in the promotion executor.\n//\n// The executor removes the member and re-adds them at the new tier. SetMember\n// returns an error rather than panicking when the store has no bucket for that\n// tier, and a returned executor error does not revert -- the proposal is marked\n// rejected and the transaction still commits -- so the member would be removed\n// and not re-added.\n//\n// The two tier registries are separate. GetTier reads the global definitions,\n// which always hold T1/T2/T3; SetMember checks whether this store has a bucket,\n// and DeleteAll empties the buckets while leaving the definitions intact. So a\n// destination can pass the first check and fail the second, which is what this\n// sets up.\nfunc TestPromoteToTierMissingFromStoreKeepsTheMember(cur realm, t *testing.T) {\n\tloadMembers(cur)\n\n\t// Drop the T3 bucket while the global definition of T3 survives.\n\tmstore := memberstore.Get(0, cur)\n\tmstore.DeleteAll()\n\tmstore.SetTier(memberstore.T1)\n\tmstore.SetTier(memberstore.T2)\n\tmstore.SetMember(memberstore.T1, m1, memberByTier(memberstore.T1))\n\tmstore.SetMember(memberstore.T1, m11, memberByTier(memberstore.T1))\n\tmstore.SetMember(memberstore.T1, m111, memberByTier(memberstore.T1))\n\tmstore.SetMember(memberstore.T1, m1111, memberByTier(memberstore.T1))\n\tmstore.SetMember(memberstore.T2, m2, memberByTier(memberstore.T2))\n\tmstore.SetMember(memberstore.T2, m3, memberByTier(memberstore.T2))\n\n\t// Premise: T3 is defined globally but absent from this store.\n\t_, defined := memberstore.GetTier(memberstore.T3)\n\turequire.Equal(t, true, defined, \"premise: T3 must still be a defined tier\")\n\turequire.Equal(t, false, mstore.Has(memberstore.T3),\n\t\t\"premise: this store must have no T3 bucket, or the test proves nothing\")\n\n\ttesting.SetOriginCaller(m1)\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/gov/dao/v3/impl\"))\n\tpreq := NewPromoteMemberRequest(cur, m1, memberstore.T1, memberstore.T3)\n\n\ttesting.SetOriginCaller(m1)\n\ttesting.SetRealm(testing.NewUserRealm(m1))\n\tpid := dao.MustCreateProposal(cross(cur), preq)\n\n\tfor _, voter := range []address{m1, m11, m111, m1111, m2, m3} {\n\t\ttesting.SetOriginCaller(voter)\n\t\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(pid)))\n\t}\n\n\t// The executor refuses before removing anything, and returns rather than\n\t// panicking. That rejects the proposal and closes it, and since nothing was\n\t// written, committing the rejection loses nothing.\n\t//\n\t// So the assertion below is about the chain, not the harness: the member\n\t// survives because no write happened, not because a panic reverted one.\n\t// Under the earlier panic-after-removal shape it held only because gno test\n\t// does not revert an abort, which proved nothing about production.\n\taccepted := dao.ExecuteOrRejectProposal(cross(cur), dao.ProposalID(pid))\n\turequire.Equal(t, false, accepted, \"the promotion must be rejected\")\n\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/gov/dao/v3/impl\"))\n\tafter, tier := memberstore.Get(0, cur).GetMember(m1)\n\turequire.Equal(t, true, after != nil, \"the member must survive a refused promotion\")\n\turequire.Equal(t, memberstore.T1, tier, \"and must still be on their original tier\")\n\n\tloadMembers(cur)\n}\n"},{"name":"impl.gno","body":"package impl\n\nimport (\n\t\"gno.land/r/gov/dao/v3/memberstore\"\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/v3/loader\" {\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\"\n\t\"gno.land/p/moul/md\"\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/v3/memberstore\"\n\t\"gno.land/r/gov/dao/v3/treasury\"\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 v3/impl but\n\t\t// what calls this cb function is r/gov/dao.\n\t\t// therefore we must cross back into v3/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/v3/impl\", 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/v3/impl` 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\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\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\treason,\n\t\t\tpayment.String(),\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\treason,\n\t\t\tpayment.String(),\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\tcb := func(cur realm) error {\n\t\treturn panictoerr.PanicToError(func() {\n\t\t\t// NOTE:: Consider checking if the newTokenKeys are already registered\n\t\t\t// in the grc20reg before updating the treasury tokens keys.\n\t\t\ttreasury.SetTokenKeys(cross(cur), newTokenKeys)\n\t\t})\n\t}\n\n\tbulletList := md.BulletList(newTokenKeys)\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\"\n\t\"gno.land/p/moul/md\"\n\t\"gno.land/p/nt/bptree/v0/pager\"\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/v3/memberstore)\\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":"render_error_paths_filetest.gno","body":"// PKGPATH: gno.land/r/test/rendererr\npackage rendererr\n\n// Render is reachable unauthenticated via vm/qrender with an attacker-chosen\n// path. Two pre-existing defects on that path are covered here:\n//   - the \"invalid proposal id\" error echoed the raw pid segment (strconv\n//     quotes it but leaves markdown/HTML metachars), so a crafted pid injected\n//     inline markup into a govDAO-branded page;\n//   - a control byte in the query string made the pager's MustGetPageByPath\n//     panic, aborting the landing-page render.\n// Both are now escaped / degraded-gracefully.\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/r/gov/dao\"\n\t\"gno.land/r/gov/dao/v3/impl\"\n\t\"gno.land/r/gov/dao/v3/memberstore\"\n)\n\nconst user address = \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"\n\nfunc init(cur realm) {\n\tmemberstore.Get(0, cur).DeleteAll()\n\tmemberstore.Get(0, cur).SetTier(memberstore.T1)\n\tmemberstore.Get(0, cur).SetMember(memberstore.T1, user, memberstore.NewMember(3))\n\tdao.UpdateImpl(cross(cur), dao.NewUpdateRequest(impl.NewGovDAO(), nil))\n}\n\nfunc main(cur realm) {\n\ttesting.SetOriginCaller(user)\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// 1. A non-numeric pid whose segment carries an inline-markdown payload.\n\t// No '/', so it routes to {pid}; ParseInt fails and the error is escaped.\n\tpout := dao.Render(cross(cur), \"99[pwn](evil.example)\")\n\tprintln(\"payload is escaped, not a live link:\",\n\t\tstrings.Contains(pout, `\\[pwn\\]`) \u0026\u0026 !strings.Contains(pout, \"[pwn](evil.example)\"))\n\tprintln(\"still shows the invalid-id message:\",\n\t\tstrings.Contains(pout, \"Invalid proposal ID format\"))\n\n\t// Same on the /votes route.\n\tvout := dao.Render(cross(cur), \"88[x](evil.example)/votes\")\n\tprintln(\"votes route escapes it too:\",\n\t\t!strings.Contains(vout, \"[x](evil.example)\"))\n\n\t// 2. A control byte in the query — url.Parse rejects it. The landing page\n\t// must degrade to page 1, not panic.\n\tlout := dao.Render(cross(cur), \"?\\x01\")\n\tprintln(\"control-byte query renders instead of panicking:\",\n\t\tstrings.Contains(lout, \"# GovDAO\"))\n}\n\n// Output:\n// payload is escaped, not a live link: true\n// still shows the invalid-id message: true\n// votes route escapes it too: true\n// control-byte query renders instead of panicking: true\n"},{"name":"stringify_proposal_00_filetest.gno","body":"// PKGPATH: gno.land/r/test\npackage test\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/r/gov/dao\"\n\t\"gno.land/r/gov/dao/v3/impl\"\n\t\"gno.land/r/gov/dao/v3/memberstore\"\n)\n\nvar (\n\ttestUser = testutils.TestAddress(\"test\")\n)\n\n// StringifyProposal carries its own copy of the disclosure expression, separate\n// from the one in render.gno. It has no production caller today, but it is\n// exported, and an untested copy of a security-relevant expression is free to\n// drift from the tested one. This executor pins it: CreationRealm is reached\n// through the public interface, so it can return anything, and the run of two\n// backticks closes a narrower fence.\ntype hostileExec struct{}\n\nfunc (e *hostileExec) Execute(cur realm) error { return nil }\n\nfunc (e *hostileExec) String() string { return \"\" }\n\n// Padded on both ends as well as fenced: without the TrimSpace, InlineCode\n// pads the fence to protect the leading and trailing spaces, and the expected\n// span below no longer matches. That makes one payload cover both the escaping\n// and the trim.\nfunc (e *hostileExec) CreationRealm() string { return \"  gno.land/r/evil`` **INJECTED**  \" }\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\tdefault:\n\t\tpanic(\"unsupported tier: \" + tier)\n\t}\n}\n\nfunc init(cur realm) {\n\t// Load members for testing\n\tmstore := memberstore.Get(0, cur)\n\tmstore.DeleteAll()\n\tmstore.SetTier(memberstore.T1)\n\tmstore.SetMember(memberstore.T1, testUser, memberByTier(memberstore.T1))\n\n\t// Set up the DAO implementation using proper constructor\n\tgovDAO := impl.NewGovDAO()\n\tdao.UpdateImpl(cross(cur), dao.NewUpdateRequest(govDAO, []string{\"gno.land/r/test\", \"gno.land/r/gov/dao/v3/impl\"}))\n}\n\nfunc main(cur realm) {\n\t// Create an executor in a specific realm to test creation realm tracking\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/template/contract\"))\n\texecutor := dao.NewSimpleExecutor(0, cur, func(realm) error { return nil }, \"Test executor description\")\n\n\t// Create a proposal request\n\tproposalRequest := dao.NewProposalRequest(\n\t\t\"Test Proposal Title\",\n\t\t\"This is a test proposal description to verify StringifyProposal works correctly.\",\n\t\texecutor,\n\t)\n\n\t// Switch to user realm to create the proposal\n\ttesting.SetOriginCaller(testUser)\n\ttesting.SetRealm(testing.NewUserRealm(testUser))\n\tpid := dao.MustCreateProposal(cross(cur), proposalRequest)\n\n\t// Get the proposal and test the core functionality\n\tprop := dao.MustGetProposal(pid)\n\n\t// Test that executor string is captured correctly\n\tprintln(\"Executor string:\", prop.ExecutorString())\n\n\t// Test that executor creation realm is captured correctly\n\tprintln(\"Executor creation realm:\", prop.ExecutorCreationRealm())\n\n\t// Stringify\n\tprintln(\"----\")\n\tprintln(impl.StringifyProposal(prop))\n\n\t// The same disclosure, through a hostile executor.\n\thpid := dao.MustCreateProposal(cross(cur), dao.NewProposalRequest(\n\t\t\"Hostile\", \"creation realm attacks the code span\", \u0026hostileExec{}))\n\thout := impl.StringifyProposal(dao.MustGetProposal(hpid))\n\n\tprintln(\"stringify widens the fence too:\",\n\t\tstrings.Contains(hout, \"```gno.land/r/evil`` **INJECTED**```\"))\n\tprintln(\"and no bold escapes it:\", !strings.Contains(hout, \"\\n**INJECTED**\"))\n}\n\n// Output:\n// Executor string: Test executor description\n// Executor creation realm: gno.land/r/template/contract\n// ----\n//\n// ### Title: Test Proposal Title\n//\n// ### Proposed by: g1w3jhxazlta047h6lta047h6lta047h6lwmjv0n\n//\n// This is a test proposal description to verify StringifyProposal works correctly.\n//\n// This proposal contains the following metadata:\n//\n// Test executor description\n//\n// Executor created in: `gno.land/r/template/contract`\n//\n// stringify widens the fence too: true\n// and no bold escapes it: true\n"},{"name":"title_clamp_filetest.gno","body":"// PKGPATH: gno.land/r/test/titleclamp\npackage titleclamp\n\n// A proposal title is attacker-chosen (by a member) and is escaped on two\n// pages: the proposal page and the list page. Escaping costs about 6,990 gas a\n// byte, and the list page escapes one title per proposal shown, so an oversized\n// title priced the whole list out of the query cap: five proposals with 90 KB\n// titles cost 3,172,507,361 gas against a 3,000,000,000 cap. Clamping the title\n// before it is escaped brings the same five to 66,871,916.\n//\n// Runs in its own realm because it creates proposals, and the unit tests in the\n// impl package assert hard-coded proposal ids against shared state.\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/r/gov/dao\"\n\t\"gno.land/r/gov/dao/v3/impl\"\n\t\"gno.land/r/gov/dao/v3/memberstore\"\n)\n\nconst user address = \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"\n\nfunc init(cur realm) {\n\tmemberstore.Get(0, cur).DeleteAll()\n\tmemberstore.Get(0, cur).SetTier(memberstore.T1)\n\tmemberstore.Get(0, cur).SetMember(memberstore.T1, user, memberstore.NewMember(3))\n\tdao.UpdateImpl(cross(cur), dao.NewUpdateRequest(impl.NewGovDAO(), nil))\n}\n\nfunc main(cur realm) {\n\ttesting.SetOriginCaller(user)\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tshort := dao.MustCreateProposal(cross(cur), dao.NewProposalRequest(\n\t\t\"An ordinary title\", \"d\", nil))\n\tlong := dao.MustCreateProposal(cross(cur), dao.NewProposalRequest(\n\t\tstrings.Repeat(\"t\", 50000), \"d\", nil))\n\n\t// An ordinary title is untouched. Real titles in examples/ are about 40\n\t// bytes, so the bound never reaches them.\n\tsout := dao.Render(cross(cur), short.String())\n\tprintln(\"an ordinary title is left alone:\",\n\t\tstrings.Contains(sout, \"An ordinary title\") \u0026\u0026 !strings.Contains(sout, \"… truncated\"))\n\n\t// The proposal page cuts the title before escaping it. Asserting the marker\n\t// rather than a length: escaping first and cutting second would also\n\t// produce a short page, so length alone cannot tell the two apart.\n\tpout := dao.Render(cross(cur), long.String())\n\tprintln(\"the proposal page clamps a huge title:\",\n\t\tstrings.Contains(pout, \"… truncated\") \u0026\u0026 len(pout) \u003c 4000)\n\n\t// The list page escapes one title per proposal it shows, so it is the page\n\t// the bound actually protects.\n\tlout := dao.Render(cross(cur), \"\")\n\tprintln(\"the list page clamps it too:\",\n\t\tstrings.Contains(lout, \"… truncated\") \u0026\u0026 len(lout) \u003c 4000)\n}\n\n// Output:\n// an ordinary title is left alone: true\n// the proposal page clamps a huge title: true\n// the list page clamps it too: true\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/v3/memberstore\"\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"},{"name":"z_addr_validation_test.gno","body":"package impl\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n\t\"gno.land/r/gov/dao/v3/memberstore\"\n)\n\n// Member addresses arrive as raw MsgCall strings (the VM does not validate an\n// `address` arg), so a non-bech32 value — blank, oversized, or carrying\n// markdown/pipe/HTML metachars — would otherwise be stored and then injected\n// into the members render table. Both admission points reject it, matching the\n// InitWithUsers precedent.\nfunc TestNewAddMemberRequestRejectsInvalidAddress(cur realm, t *testing.T) {\n\ttesting.SetOriginCaller(m1)\n\ttesting.SetRealm(testing.NewUserRealm(m1))\n\n\tfor _, bad := range []string{\"evil|**pwn**\", \"\", \"not-an-address\"} {\n\t\turequire.PanicsWithMessage(t, cur,\n\t\t\t\"invalid member address: \"+bad,\n\t\t\tfunc() {\n\t\t\t\tNewAddMemberRequest(cur, address(bad), memberstore.T2, \"portfolio\")\n\t\t\t})\n\t}\n}\n"},{"name":"z_denied_reason_store_test.gno","body":"package impl\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/r/gov/dao\"\n\t\"gno.land/r/gov/dao/v3/memberstore\"\n)\n\n// Named z_* so it sorts after govdao_test.gno, whose TestUpgradeDaoImplementation\n// asserts a hard-coded proposal id. This builds its own GovDAO instance and\n// registers a status directly, so it never touches the shared one.\n\ntype hugeErrExecutor struct{ msg string }\n\nfunc (e *hugeErrExecutor) Execute(cur realm) error { return errors.New(e.msg) }\n\nfunc (e *hugeErrExecutor) String() string { return \"\" }\n\nfunc (e *hugeErrExecutor) CreationRealm() string { return \"gno.land/r/test/hugeerr\" }\n\n// The denial reason is stored, not just shown. It is \"execution failed: \" plus\n// whatever error the proposal's executor returned, and the executor is\n// third-party code. Whoever executes the proposal pays the storage deposit for\n// it, and that need not be the person who wrote the executor.\n//\n// This has to read the stored value rather than the rendered page. The render\n// clamps to the same bound, so a page rendered from an unclamped store looks\n// exactly like one rendered from a clamped store — testing through Render would\n// pass whether or not the write is bounded.\nfunc TestDeniedReasonIsClampedBeforeStoring(cur realm, t *testing.T) {\n\tg := NewGovDAO()\n\tpid := dao.ProposalID(987654)\n\tg.pss.Set(pid.String(), newProposalStatus([]string{memberstore.T1}))\n\n\tg.ExecuteProposal(0, cur, pid, \u0026hugeErrExecutor{msg: strings.Repeat(\"E\", 50000)})\n\n\tstored := g.pss.GetStatus(pid).DeniedReason\n\tuassert.True(t, len(stored) \u003c maxRenderedReason+64,\n\t\t\"the realm must not store a reason larger than it can display\")\n\tuassert.True(t, strings.Contains(stored, \"… truncated\"),\n\t\t\"a stored reason that was cut must say so\")\n\tuassert.True(t, strings.HasPrefix(stored, \"execution failed: E\"),\n\t\t\"the prefix and the start of the error must survive\")\n}\n"},{"name":"z_unknown_proposal_test.gno","body":"package impl\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n\t\"gno.land/r/gov/dao\"\n)\n\n// Named z_* so it sorts after govdao_test.gno, whose TestUpgradeDaoImplementation\n// swaps the DAO implementation and asserts a hard-coded proposal id. This test\n// creates no proposal, so it is safe to run against the shared state.\n\n// A proposal id this implementation has no status for — an unknown id, or a\n// proposal that outlived the GovDAO instance that created it (statuses live on\n// the instance). The nil deref this used to hit surfaced as \"runtime error:\n// nil pointer dereference\", which reads like a VM fault rather than a bad\n// request.\n//\n// Note what this does NOT assert: that the proposal becomes rejectable.\n// dao.executeProposal panics on ANY error from PreExecuteProposal, ahead of\n// its execErrorRejects branch, so the guard buys a named error and nothing\n// more.\nfunc TestExecuteUnknownProposalNamesTheError(cur realm, t *testing.T) {\n\ttesting.SetOriginCaller(m1)\n\ttesting.SetRealm(testing.NewUserRealm(m1))\n\n\turequire.AbortsWithMessage(t, cur, \"proposal not found\", func() {\n\t\tdao.ExecuteProposal(cross(cur), dao.ProposalID(999999))\n\t})\n}\n"},{"name":"z_upgrade_request_test.gno","body":"package impl\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n\t\"gno.land/r/gov/dao\"\n)\n\n// Named z_* so it sorts after govdao_test.gno, whose TestUpgradeDaoImplementation\n// swaps the DAO implementation and asserts a hard-coded proposal id. This test\n// creates no proposal, so it is safe to run against the shared state.\n\n// An empty realmPkg would be stored verbatim as an allowlist entry, and\n// InAllowedDAOs compares by exact string against a caller's PkgPath() — which\n// is \"\" for a user realm. It would also render as a blank name in the grant\n// sentence, so the proposal would not say who it was empowering. Rejected at\n// proposal-construction time so the mistake surfaces to the author rather than\n// at execution. UpdateImpl rejects it too; see r/gov/dao/allowlist_test.gno.\nfunc TestUpgradeRequestRejectsBlankRealmPkg(cur realm, t *testing.T) {\n\ttesting.SetOriginCaller(m1)\n\ttesting.SetRealm(testing.NewUserRealm(m1))\n\n\tfor _, padded := range []string{\" gno.land/r/x\", \"gno.land/r/x \"} {\n\t\turequire.PanicsWithMessage(t, cur,\n\t\t\t\"realmPkg must not have leading or trailing spaces\",\n\t\t\tfunc() {\n\t\t\t\tNewUpgradeDaoImplRequest(cur, \u0026mockDAO{}, padded, \"reason\")\n\t\t\t})\n\t}\n\n\tfor _, blank := range []string{\"\", \"   \"} {\n\t\t// PanicsWithMessage, not AbortsWithMessage: this is a same-realm call,\n\t\t// so the guard raises a plain panic rather than a cross-realm abort.\n\t\turequire.PanicsWithMessage(t, cur,\n\t\t\t\"realmPkg must be the realm path being granted govDAO authority\",\n\t\t\tfunc() {\n\t\t\t\tNewUpgradeDaoImplRequest(cur, \u0026mockDAO{}, blank, \"reason\")\n\t\t\t})\n\t}\n}\n\ntype mockDAO struct{}\n\nfunc (d *mockDAO) PreCreateProposal(_ int, rlm realm, r dao.ProposalRequest) (address, error) {\n\treturn m1, nil\n}\n\nfunc (d *mockDAO) PostCreateProposal(_ int, rlm realm, r dao.ProposalRequest, pid dao.ProposalID) {}\n\nfunc (d *mockDAO) VoteOnProposal(_ int, rlm realm, r dao.VoteRequest) error { return nil }\n\nfunc (d *mockDAO) PreExecuteProposal(_ int, rlm realm, pid dao.ProposalID) (bool, error) {\n\treturn true, nil\n}\n\nfunc (d *mockDAO) ExecuteProposal(_ int, rlm realm, pid dao.ProposalID, e dao.Executor) error {\n\treturn nil\n}\n\nfunc (d *mockDAO) Render(cur realm, pkgpath string, path string) string { return \"\" }\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"hVI/2MSkZffNojEiEOeiz7W+zwVEBCH7Q8vZVVmbF+0L3wxkhVXxnMoPdQ4VdrXWJ6+EwWuDJgQKiNzITQ3xvw=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1g73v2anukg4ej7axwqpthsatzrxjsh0wk797da","package":{"name":"init","path":"gno.land/r/gov/dao/v3/init","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/gov/dao/v3/init\"\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/v3/impl\"\n\t\"gno.land/r/gov/dao/v3/memberstore\"\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/v3/impl\"}))\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/v3/impl\"}))\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"nAkucs9qs80ruhytd+nUE378EIaP+a817iIqZA/lSNJBlU8N/cjmUUmewuvAgHQC+2746W7J5yTZB0aDNwCzKg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l","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":"delegate_test.gno","body":"package params\n\nimport (\n\t\"testing\"\n\n\tprms \"sys/params\"\n\n\t\"gno.land/p/moul/addrset\"\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nconst (\n\ttestDelegate = \"gno.land/r/test/delegate\"\n\ttestOther    = \"gno.land/r/test/other\"\n\t// A sub-realm identity, the form a single DAO hosted by a multi-tenant\n\t// realm presents. \"#\" cannot occur in a real package path.\n\ttestSubDelegate = \"gno.land/r/nt/commondao/v0#dao/42\"\n)\n\n// resetDelegation returns the slot to undelegated. The realm's tests share\n// package state, so anything touching the slot must put it back.\nfunc resetDelegation() {\n\trunSubmittersMgr = \"\"\n\trunSubmittersGrants = addrset.Set{}\n}\n\n// armRunSubmitters puts addresses on the list the way GovDAO does: by writing\n// the parameter, not through the delegate.\n//\n// Tests need it because the delegate may no longer arm an empty list. An empty\n// run_submitters means the gate is off, so the first add would switch a\n// chain-wide restriction on rather than curate one, and that is a vote.\nfunc armRunSubmitters(addrs ...string) {\n\tprms.UpdateSysParamStrings(vmModulePrefix, vmParamsSubmodule, runSubmittersKey, addrs, true)\n}\n\n// unarmRunSubmitters drops addresses the way a GovDAO vote does, bypassing the\n// delegate's grant-scoping. Used to build a list whose every remaining entry was\n// granted by the delegate, which is the only state where the non-empty floor is\n// the binding constraint.\nfunc unarmRunSubmitters(addrs ...string) {\n\tprms.UpdateSysParamStrings(vmModulePrefix, vmParamsSubmodule, runSubmittersKey, addrs, false)\n}\n\n// TestRunSubmittersUndelegatedDeniesEveryone is the single most important test\n// here: with no delegate configured, the slot is \"\" and a direct user call also\n// presents \"\". A gate that compared the two without checking for empty first\n// would admit every account on the chain.\nfunc TestRunSubmittersUndelegatedDeniesEveryone(cur realm, t *testing.T) {\n\tresetDelegation()\n\tdefer resetDelegation()\n\n\tuassert.Equal(t, \"\", RunSubmittersManager())\n\n\t// A user account: PkgPath() is empty, matching the empty slot.\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"nobody\")))\n\tuassert.AbortsContains(t, cur, \"no delegate is configured\", func() {\n\t\tAddRunSubmitters(cross(cur), []string{testutils.TestAddress(\"victim\").String()})\n\t})\n\n\t// And a code realm, for completeness.\n\ttesting.SetRealm(testing.NewCodeRealm(testOther))\n\tuassert.AbortsContains(t, cur, \"no delegate is configured\", func() {\n\t\tAddRunSubmitters(cross(cur), []string{testutils.TestAddress(\"victim\").String()})\n\t})\n}\n\n// TestRunSubmittersOnlyTheDelegateMayWrite pins that authorization is by exact\n// package path.\nfunc TestRunSubmittersOnlyTheDelegateMayWrite(cur realm, t *testing.T) {\n\tresetDelegation()\n\tdefer resetDelegation()\n\n\trunSubmittersMgr = testDelegate\n\tarmRunSubmitters(testutils.TestAddress(\"seeded-by-vote\").String())\n\taddr := testutils.TestAddress(\"granted\").String()\n\n\t// A different realm is refused.\n\ttesting.SetRealm(testing.NewCodeRealm(testOther))\n\tuassert.AbortsContains(t, cur, \"unauthorized\", func() {\n\t\tAddRunSubmitters(cross(cur), []string{addr})\n\t})\n\n\t// A user account is refused: an empty path must not match a set slot.\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"nobody\")))\n\tuassert.AbortsContains(t, cur, \"unauthorized\", func() {\n\t\tAddRunSubmitters(cross(cur), []string{addr})\n\t})\n\n\t// The delegate itself succeeds.\n\ttesting.SetRealm(testing.NewCodeRealm(testDelegate))\n\tAddRunSubmitters(cross(cur), []string{addr})\n\tuassert.True(t, contains(GetRunSubmitters(), addr),\n\t\t\"the delegate's addition must reach the parameter\")\n}\n\n// TestRunSubmittersSubRealmIdentityIsExact pins that delegate matching is exact\n// string equality, which is what makes a per-DAO delegation safe.\n//\n// A sub-realm identity minted by cur.Sub(subpath) presents \"host#subpath\", so a\n// single DAO hosted by a multi-tenant realm can hold the capability. Matching by\n// prefix instead would hand it to every DAO that host serves -- and CommonDAO\n// membership, while invite-gated, is unlimited once invited.\n//\n// Asserted through the pure predicate rather than by crossing: constructing a\n// live sub-realm cur is not something the test harness can do (NewCodeRealm\n// rejects \"#\", and MakeRealm does not satisfy IsCurrent), and the comparison\n// under test is the same one assertDelegate performs.\nfunc TestRunSubmittersSubRealmIdentityIsExact(t *testing.T) {\n\tresetDelegation()\n\tdefer resetDelegation()\n\n\trunSubmittersMgr = testSubDelegate\n\n\tuassert.True(t, IsRunSubmittersDelegate(testSubDelegate),\n\t\t\"the named DAO holds the capability\")\n\tuassert.False(t, IsRunSubmittersDelegate(\"gno.land/r/nt/commondao/v0\"),\n\t\t\"the host realm must not inherit its sub-identity's authority\")\n\tuassert.False(t, IsRunSubmittersDelegate(\"gno.land/r/nt/commondao/v0#dao/43\"),\n\t\t\"a sibling DAO of the same host must not match\")\n\tuassert.False(t, IsRunSubmittersDelegate(\"gno.land/r/nt/commondao/v0#dao/4\"),\n\t\t\"a prefix of the subpath must not match\")\n\tuassert.False(t, IsRunSubmittersDelegate(\"\"),\n\t\t\"an empty path must never match a configured delegate\")\n}\n\n// TestRunSubmittersRemoveIsScopedToOwnGrants pins that the delegate cannot\n// remove an address it did not add, so a list GovDAO curated survives a rogue\n// delegate. The companion bound -- that it can never take the list to zero by\n// any route -- is TestRunSubmittersCannotEmptyTheList.\nfunc TestRunSubmittersRemoveIsScopedToOwnGrants(cur realm, t *testing.T) {\n\tresetDelegation()\n\tdefer resetDelegation()\n\n\tpreexisting := testutils.TestAddress(\"breakglass\").String()\n\ttesting.SetSysParamStrings(vmModulePrefix, vmParamsSubmodule, runSubmittersKey,\n\t\t[]string{preexisting})\n\n\trunSubmittersMgr = testDelegate\n\tarmRunSubmitters(testutils.TestAddress(\"seeded-by-vote\").String())\n\town := testutils.TestAddress(\"ownadd\").String()\n\n\ttesting.SetRealm(testing.NewCodeRealm(testDelegate))\n\tAddRunSubmitters(cross(cur), []string{own})\n\n\t// It may remove what it granted.\n\tuassert.True(t, RunSubmittersGrantedBy(address(own)))\n\tRemoveRunSubmitters(cross(cur), []string{own})\n\tuassert.False(t, contains(GetRunSubmitters(), own))\n\n\t// It may NOT remove the address that predated the delegation.\n\tuassert.False(t, RunSubmittersGrantedBy(address(preexisting)))\n\tuassert.AbortsContains(t, cur, \"only GovDAO may remove it\", func() {\n\t\tRemoveRunSubmitters(cross(cur), []string{preexisting})\n\t})\n\tuassert.True(t, contains(GetRunSubmitters(), preexisting),\n\t\t\"the pre-existing entry must survive a refused removal\")\n}\n\n// TestRunSubmittersCannotEmptyTheList pins the non-empty floor.\n//\n// An empty run_submitters means the gate is OFF: anyone on the chain may\n// MsgRun. So emptying the list is not a smaller version of removing one\n// address, it is the unilateral revocation of the whole restriction GovDAO\n// voted for -- the one thing this capability must not be able to do.\n//\n// Grant-scoping alone does not prevent it. It holds only while an entry the\n// delegate did not grant survives, and GovDAO replacing the list wholesale can\n// remove its own entries without touching the grant record, which is exactly\n// the state set up below.\nfunc TestRunSubmittersCannotEmptyTheList(cur realm, t *testing.T) {\n\tresetDelegation()\n\tdefer resetDelegation()\n\n\trunSubmittersMgr = testDelegate\n\tseed := testutils.TestAddress(\"seeded-by-vote\").String()\n\tarmRunSubmitters(seed)\n\ta := testutils.TestAddress(\"granted-a\").String()\n\tb := testutils.TestAddress(\"granted-b\").String()\n\n\ttesting.SetRealm(testing.NewCodeRealm(testDelegate))\n\tAddRunSubmitters(cross(cur), []string{a, b})\n\n\t// GovDAO then drops its own seed by vote, which grant-scoping does not\n\t// constrain. This is the only way to reach a list whose every entry was\n\t// granted by the delegate, now that the delegate cannot arm an empty one --\n\t// and it is the state where the floor is the last thing standing.\n\tunarmRunSubmitters(seed)\n\tuassert.Equal(t, 2, len(GetRunSubmitters()))\n\n\t// Every listed address is now one the delegate granted, so grant-scoping\n\t// permits removing all of them. The floor is the only thing left.\n\tuassert.True(t, RunSubmittersGrantedBy(address(a)))\n\tuassert.True(t, RunSubmittersGrantedBy(address(b)))\n\n\t// Down to one is fine: shrinking the list is the delegate's job.\n\tRemoveRunSubmitters(cross(cur), []string{a})\n\tuassert.Equal(t, 1, len(GetRunSubmitters()))\n\n\t// The last one is not.\n\tuassert.AbortsContains(t, cur, \"refusing to empty\", func() {\n\t\tRemoveRunSubmitters(cross(cur), []string{b})\n\t})\n\tuassert.True(t, contains(GetRunSubmitters(), b),\n\t\t\"the last entry must survive a refused removal\")\n\n\t// Nor in one call, and nor by naming addresses that are not listed: the\n\t// count is taken against the parameter, not the argument.\n\tuassert.AbortsContains(t, cur, \"refusing to empty\", func() {\n\t\tRemoveRunSubmitters(cross(cur), []string{b, b})\n\t})\n\tuassert.True(t, contains(GetRunSubmitters(), b))\n\n\t// And the delegate is not locked out of its ordinary work: adding still\n\t// works, and once there are two again it may remove one.\n\tAddRunSubmitters(cross(cur), []string{a})\n\tRemoveRunSubmitters(cross(cur), []string{b})\n\tuassert.True(t, contains(GetRunSubmitters(), a))\n\tuassert.False(t, contains(GetRunSubmitters(), b))\n}\n\n// TestRunSubmittersRevocationDropsGrantRecord pins that a new holder does not\n// inherit removal authority over its predecessor's grants.\nfunc TestRunSubmittersRevocationDropsGrantRecord(cur realm, t *testing.T) {\n\tresetDelegation()\n\tdefer resetDelegation()\n\n\trunSubmittersMgr = testDelegate\n\tarmRunSubmitters(testutils.TestAddress(\"seeded-by-vote\").String())\n\taddr := testutils.TestAddress(\"byfirst\").String()\n\ttesting.SetRealm(testing.NewCodeRealm(testDelegate))\n\tAddRunSubmitters(cross(cur), []string{addr})\n\tuassert.True(t, RunSubmittersGrantedBy(address(addr)))\n\n\t// Hand the capability over, as the proposal executor would.\n\trunSubmittersMgr = testOther\n\trunSubmittersGrants = addrset.Set{}\n\n\ttesting.SetRealm(testing.NewCodeRealm(testOther))\n\tuassert.False(t, RunSubmittersGrantedBy(address(addr)))\n\tuassert.AbortsContains(t, cur, \"only GovDAO may remove it\", func() {\n\t\tRemoveRunSubmitters(cross(cur), []string{addr})\n\t})\n}\n\n// TestDelegatePathValidation pins what may be stored in a slot. An ephemeral\n// `maketx run` realm has a NON-empty path, so a check for \"is this code\" would\n// let one through; only the gno.land/r/ requirement excludes it.\nfunc TestDelegatePathValidation(t *testing.T) {\n\tfor _, bad := range []string{\n\t\t\"\",\n\t\t\"gno.land/p/nt/avl/v0\",\n\t\t\"gno.land/e/g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5/run\",\n\t\t\"gno.land/r/\",\n\t\t// Paths no caller could ever present. Storing one would leave GovDAO\n\t\t// believing it delegated while the delegate is refused on every call.\n\t\t\"gno.land/r/test/delegate \",                // trailing space\n\t\t\" gno.land/r/test/delegate\",                // leading space\n\t\t\"gno.land/r/nt/commondao/v0#DAO/42\",        // uppercase subpath\n\t\t\"gno.land/r/nt/commondao/v0#dao/42#dao/43\", // two separators\n\t} {\n\t\t// PanicsContains, not AbortsContains: this is a same-realm call, so\n\t\t// the panic never crosses a realm boundary and is not an abort.\n\t\tuassert.PanicsContains(t, cur, \"invalid delegate\", func() {\n\t\t\tassertDelegatePath(bad)\n\t\t})\n\t}\n\t// Sound paths, including a sub-realm identity.\n\tassertDelegatePath(testDelegate)\n\tassertDelegatePath(testSubDelegate)\n}\n\n// TestValsetGateRejectsForeignRealm closes a pre-existing coverage gap found\n// while factoring the shared gate: assertValsetCaller had no test in this realm\n// at all, so nothing asserted that a realm other than r/sys/validators/v3 is\n// refused.\nfunc TestValsetGateRejectsForeignRealm(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(testOther))\n\tuassert.AbortsContains(t, cur, \"unauthorized\", func() {\n\t\tSetValsetProposal(cross(cur), []string{\"somepubkey:1\"})\n\t})\n\n\t// A user account must be refused identically -- the empty-path case.\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"nobody\")))\n\tuassert.AbortsContains(t, cur, \"unauthorized\", func() {\n\t\tSetValsetProposal(cross(cur), []string{\"somepubkey:1\"})\n\t})\n}\n\n// TestAssertNotValsetKeyRejectsGenericFactory closes the other gap: the guard\n// whose own comment says it stops \"any GovDAO supermajority\" from writing\n// validator-set state through the generic param factory had no test.\nfunc TestAssertNotValsetKeyRejectsGenericFactory(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"proposer\")))\n\tuassert.AbortsContains(t, cur, \"reserved for\", func() {\n\t\tNewSysParamStringsPropRequest(cross(cur), \"node\", \"valset\", \"proposed\",\n\t\t\t[]string{\"somepubkey:1\"})\n\t})\n}\n\nfunc contains(haystack []string, needle string) bool {\n\tfor _, h := range haystack {\n\t\tif h == needle {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// TestRunSubmittersGrantLaunderingIsRefused reproduces a real hole in the first\n// version of this code, found by audit.\n//\n// UpdateSysParamStrings dedupes on add, so re-adding an address already on the\n// list is a no-op on the parameter. The first implementation recorded a grant\n// for every argument regardless, which let the delegate launder authority over\n// entries it never granted:\n//\n//\tread the list -\u003e re-add all of it -\u003e remove all of it\n//\n// The parameter never changed on the middle step, but every address became\n// \"granted by me\", so the removal was permitted and the allowlist ended empty --\n// including the entry that predated the delegation. Since GovDAO proposal\n// creation is MsgRun-only, an empty run_submitters means no proposal can be\n// created to revoke the delegate or restore the list. That is a chain brick\n// recoverable only by relaunch.\nfunc TestRunSubmittersGrantLaunderingIsRefused(cur realm, t *testing.T) {\n\tresetDelegation()\n\tdefer resetDelegation()\n\n\tbreakglass := testutils.TestAddress(\"breakglass2\").String()\n\ttesting.SetSysParamStrings(vmModulePrefix, vmParamsSubmodule, runSubmittersKey,\n\t\t[]string{breakglass})\n\n\trunSubmittersMgr = testDelegate\n\tarmRunSubmitters(testutils.TestAddress(\"seeded-by-vote\").String())\n\ttesting.SetRealm(testing.NewCodeRealm(testDelegate))\n\n\t// Step 1: re-add what is already there. A no-op on the parameter, and it\n\t// must NOT create a grant.\n\tAddRunSubmitters(cross(cur), GetRunSubmitters())\n\tuassert.False(t, RunSubmittersGrantedBy(address(breakglass)),\n\t\t\"re-adding an existing address must not record a grant for it\")\n\n\t// Step 2: the removal must therefore still be refused.\n\tuassert.AbortsContains(t, cur, \"only GovDAO may remove it\", func() {\n\t\tRemoveRunSubmitters(cross(cur), []string{breakglass})\n\t})\n\tuassert.True(t, contains(GetRunSubmitters(), breakglass),\n\t\t\"the pre-existing entry must survive\")\n\n\t// And the whole-list version of the same attack, which is how it would\n\t// actually be run.\n\tAddRunSubmitters(cross(cur), GetRunSubmitters())\n\tuassert.AbortsContains(t, cur, \"only GovDAO may remove it\", func() {\n\t\tRemoveRunSubmitters(cross(cur), GetRunSubmitters())\n\t})\n\tuassert.True(t, len(GetRunSubmitters()) \u003e 0,\n\t\t\"the allowlist must never end up empty at a delegate's hand\")\n\n\t// A genuinely new address still works normally.\n\tfresh := testutils.TestAddress(\"freshgrant\").String()\n\tAddRunSubmitters(cross(cur), []string{fresh})\n\tuassert.True(t, RunSubmittersGrantedBy(address(fresh)))\n\tRemoveRunSubmitters(cross(cur), []string{fresh})\n\tuassert.False(t, contains(GetRunSubmitters(), fresh))\n}\n\n// TestRenderShowsDelegationState pins that the page actually reports the state\n// it exists to report.\n//\n// The value of a Render here is that someone auditing the chain can see whether\n// a parameter is delegated without knowing to ask. A page that renders the same\n// text whether or not a delegation exists would defeat that, so both states are\n// checked.\nfunc TestRenderShowsDelegationState(t *testing.T) {\n\tresetDelegation()\n\tdefer resetDelegation()\n\n\taddr := testutils.TestAddress(\"rendered\").String()\n\ttesting.SetSysParamStrings(vmModulePrefix, vmParamsSubmodule, runSubmittersKey,\n\t\t[]string{addr})\n\n\t// Undelegated: it must say so rather than leave the reader guessing.\n\tout := Render(\"\")\n\tuassert.True(t, contains2(out, \"nobody\"),\n\t\t\"an undelegated parameter must be reported as such\")\n\tuassert.False(t, contains2(out, testDelegate),\n\t\t\"no delegate should be named when none is set\")\n\n\t// Delegated: the holder is named.\n\trunSubmittersMgr = testDelegate\n\tarmRunSubmitters(testutils.TestAddress(\"seeded-by-vote\").String())\n\tout = Render(\"\")\n\tuassert.True(t, contains2(out, testDelegate),\n\t\t\"the delegate holding the capability must be named\")\n\tuassert.True(t, contains2(out, addr),\n\t\t\"the addresses the parameter currently allows must be listed\")\n\n\t// The valset writer is fixed in source, not delegated, and the page should\n\t// not blur the two.\n\tuassert.True(t, contains2(out, valsetAuthorizedRealm),\n\t\t\"the realm that writes valset params must be shown too\")\n}\n\n// contains2 reports whether s contains sub.\nfunc contains2(s, sub string) bool {\n\tif len(sub) == 0 {\n\t\treturn true\n\t}\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\n// TestRunSubmittersDelegateCannotArmTheGate covers the direction the non-empty\n// floor does not: turning the allowlist ON.\n//\n// An empty run_submitters means the gate is off and anyone may MsgRun. So a\n// delegate adding the first address is not curating a list, it is switching a\n// chain-wide restriction on and choosing who it admits -- leaving that address\n// the only one on the chain that may run code.\n//\n// That is unrepairable in band. Creating a GovDAO proposal needs MsgRun, so\n// once the gate is armed against the members they cannot propose the vote that\n// would reset the list or revoke the delegation, and the floor in\n// RemoveRunSubmitters stops the delegate from undoing it either.\nfunc TestRunSubmittersDelegateCannotArmTheGate(cur realm, t *testing.T) {\n\tresetDelegation()\n\tdefer resetDelegation()\n\n\trunSubmittersMgr = testDelegate\n\tattacker := testutils.TestAddress(\"attacker\").String()\n\n\t// The gate starts off.\n\tuassert.Equal(t, 0, len(GetRunSubmitters()))\n\n\ttesting.SetRealm(testing.NewCodeRealm(testDelegate))\n\tuassert.AbortsContains(t, cur, \"refusing to arm\", func() {\n\t\tAddRunSubmitters(cross(cur), []string{attacker})\n\t})\n\tuassert.Equal(t, 0, len(GetRunSubmitters()),\n\t\t\"a refused arm must leave the gate off\")\n\n\t// Once GovDAO has armed it, the delegate may curate as before.\n\tseeded := testutils.TestAddress(\"seeded-by-vote\").String()\n\tarmRunSubmitters(seeded)\n\ttesting.SetRealm(testing.NewCodeRealm(testDelegate))\n\tAddRunSubmitters(cross(cur), []string{attacker})\n\tuassert.Equal(t, 2, len(GetRunSubmitters()),\n\t\t\"curating an armed list is still the delegate's job\")\n}\n\n// TestRunSubmittersKeyIsReservedFromGenericFactories pins that the whole-list\n// path is the dedicated constructor and nothing else.\n//\n// The generic factories take module, submodule and name as arguments, so\n// without this any of the nine could write run_submitters and walk past the\n// proposer rule in ProposeSetRunSubmitters. Same shape as the valset\n// reservation next to it.\nfunc TestRunSubmittersKeyIsReservedFromGenericFactories(cur realm, t *testing.T) {\n\taddr := testutils.TestAddress(\"someone\").String()\n\n\tuassert.AbortsContains(t, cur, \"reserved for ProposeSetRunSubmitters\", func() {\n\t\tNewSysParamStringsPropRequest(cross(cur), \"vm\", \"p\", runSubmittersKey, []string{addr})\n\t})\n\tuassert.AbortsContains(t, cur, \"reserved for ProposeSetRunSubmitters\", func() {\n\t\tNewSysParamStringsPropRequestWithTitle(cross(cur), \"vm\", \"p\", runSubmittersKey, \"t\", []string{addr})\n\t})\n\tuassert.AbortsContains(t, cur, \"reserved for ProposeSetRunSubmitters\", func() {\n\t\tNewSysParamStringsPropRequestAddWithTitle(cross(cur), \"vm\", \"p\", runSubmittersKey, \"t\", []string{addr})\n\t})\n\tuassert.AbortsContains(t, cur, \"reserved for ProposeSetRunSubmitters\", func() {\n\t\tNewSysParamStringsPropRequestRemoveWithTitle(cross(cur), \"vm\", \"p\", runSubmittersKey, \"t\", []string{addr})\n\t})\n\tuassert.AbortsContains(t, cur, \"reserved for ProposeSetRunSubmitters\", func() {\n\t\tNewSysParamStringPropRequest(cross(cur), \"vm\", \"p\", runSubmittersKey, addr)\n\t})\n\n\t// The four typed factories too. They cannot carry a run_submitters value,\n\t// but they can name the key, and the reservation is about the key -- all\n\t// nine share one check on the funnel they return through, so all nine are\n\t// listed here rather than the five that happen to take strings.\n\tuassert.AbortsContains(t, cur, \"reserved for ProposeSetRunSubmitters\", func() {\n\t\tNewSysParamInt64PropRequest(cross(cur), \"vm\", \"p\", runSubmittersKey, 1)\n\t})\n\tuassert.AbortsContains(t, cur, \"reserved for ProposeSetRunSubmitters\", func() {\n\t\tNewSysParamUint64PropRequest(cross(cur), \"vm\", \"p\", runSubmittersKey, 1)\n\t})\n\tuassert.AbortsContains(t, cur, \"reserved for ProposeSetRunSubmitters\", func() {\n\t\tNewSysParamBoolPropRequest(cross(cur), \"vm\", \"p\", runSubmittersKey, true)\n\t})\n\tuassert.AbortsContains(t, cur, \"reserved for ProposeSetRunSubmitters\", func() {\n\t\tNewSysParamBytesPropRequest(cross(cur), \"vm\", \"p\", runSubmittersKey, []byte{1})\n\t})\n\n\t// A different key in the same module is unaffected.\n\tuassert.NotAborts(t, cur, func() {\n\t\tNewSysParamStringsPropRequest(cross(cur), \"vm\", \"p\", \"code_submitters\", []string{addr})\n\t})\n}\n\n// TestProposeSetRunSubmittersRequiresProposerOnTheList covers the rule that a\n// non-empty allowlist must include whoever proposed it.\n//\n// A list naming nobody who can create a proposal cannot be undone, because\n// creating one needs MsgRun. Requiring the proposer's own address proves the\n// list is usable: GovDAO refuses a proposal from a non-member, and the proposer\n// just signed the transaction, so that address demonstrably holds a key.\nfunc TestProposeSetRunSubmittersRequiresProposerOnTheList(cur realm, t *testing.T) {\n\tother := testutils.TestAddress(\"someone-else\").String()\n\n\t// A list without the proposer is refused.\n\tuassert.AbortsContains(t, cur, \"omits the proposer\", func() {\n\t\tProposeSetRunSubmitters(cross(cur), []string{other})\n\t})\n\n\t// Emptying the list is always allowed: that switches the gate off, which\n\t// cannot lock anyone out.\n\tuassert.NotAborts(t, cur, func() {\n\t\tProposeSetRunSubmitters(cross(cur), []string{})\n\t})\n\n\t// A list that does include the proposer goes through.\n\tproposer := testutils.TestAddress(\"proposer\")\n\ttesting.SetRealm(testing.NewUserRealm(proposer))\n\tuassert.NotAborts(t, cur, func() {\n\t\tProposeSetRunSubmitters(cross(cur), []string{other, proposer.String()})\n\t})\n}\n\n// TestSetRunSubmittersReplacesTheList covers what the whole-list setter does to\n// a list that is not empty.\n//\n// This realm reserves run_submitters from the generic factories, so its own\n// setter is the only route by vote. If that setter appended instead of\n// replacing, the parameter would be append-only chain-wide: a compromised\n// address could never be de-listed and the gate could never be turned back off,\n// while the proposal shown to voters would say otherwise.\n//\n// Every other test here starts from an empty list, where appending and\n// replacing look identical, which is why this one starts armed.\nfunc TestSetRunSubmittersReplacesTheList(cur realm, t *testing.T) {\n\tresetDelegation()\n\tdefer resetDelegation()\n\n\ta := testutils.TestAddress(\"keep-a\").String()\n\tb := testutils.TestAddress(\"drop-b\").String()\n\tarmRunSubmitters(a, b)\n\tuassert.Equal(t, 2, len(GetRunSubmitters()))\n\n\t// Dropping b must actually drop it.\n\tsetRunSubmitters([]string{a})\n\tgot := GetRunSubmitters()\n\tuassert.Equal(t, 1, len(got), \"the list must be replaced, not appended to\")\n\tuassert.True(t, contains(got, a))\n\tuassert.False(t, contains(got, b), \"a de-listed address must be gone\")\n\n\t// And emptying must switch the gate off, which is what the proposal says.\n\tsetRunSubmitters([]string{})\n\tuassert.Equal(t, 0, len(GetRunSubmitters()),\n\t\t\"an empty list must be reachable, or the gate can never be turned off\")\n}\n\n// TestAssertDelegateRejectsANonLiveRealm covers the IsCurrent check in\n// assertDelegate.\n//\n// This is the shape where the check can actually fire. assertDelegate takes its\n// realm as an ordinary parameter, so a caller can hand it a stashed or\n// sibling-frame value; without IsCurrent it would then compare that value's\n// Previous() against the delegate path and admit whoever assembled it.\n//\n// Crossing functions cannot be tested this way, and do not need to be: the\n// compiler refuses anything but `cur` or `cross(rlm)` as their first argument,\n// so their cur is live by construction.\nfunc TestAssertDelegateRejectsANonLiveRealm(cur realm, t *testing.T) {\n\tresetDelegation()\n\tdefer resetDelegation()\n\n\trunSubmittersMgr = testDelegate\n\n\t// A synthetic realm whose Previous() names the delegate. The path check\n\t// alone would admit it; IsCurrent is the only thing that does not.\n\tfake := testing.MakeRealm(\n\t\ttestutils.TestAddress(\"impostor\"), \"gno.land/r/impostor\",\n\t\ttesting.MakeRealm(testutils.TestAddress(\"d\"), testDelegate, testing.OriginRealm()),\n\t)\n\tuassert.Equal(t, testDelegate, fake.Previous().PkgPath(),\n\t\t\"premise: the forged realm must pass the path check, or this proves nothing\")\n\n\t// PanicsContains, not Aborts: assertDelegate is called directly here, in\n\t// this realm, so the refusal is a panic. It surfaces as an abort only when\n\t// it happens across a realm boundary.\n\tuassert.PanicsContains(t, cur, \"not the caller's live cur\", func() {\n\t\tassertDelegate(0, fake, runSubmittersMgr, \"the \"+runSubmittersKey+\" allowlist\")\n\t})\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":"fee_collector_test.gno","body":"package params\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n\t\"gno.land/r/gov/dao\"\n)\n\n// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\n\nfunc TestSetFeeCollector(cur realm, t *testing.T) {\n\tuserRealm := testing.NewUserRealm(g1user)\n\ttesting.SetRealm(userRealm)\n\n\tpr := NewSetFeeCollectorRequest(cur, userRealm.Address())\n\tid := dao.MustCreateProposal(cross(cur), pr)\n\t_, err := dao.GetProposal(id)\n\turequire.NoError(t, err)\n\n\turequire.NotPanics(\n\t\tt, cur,\n\t\tfunc() {\n\t\t\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(id)))\n\t\t},\n\t)\n\n\turequire.NotPanics(\n\t\tt, cur,\n\t\tfunc() {\n\t\t\tdao.ExecuteProposal(cross(cur), id)\n\t\t},\n\t)\n\n\t// XXX: test that the value got properly updated, when we can get params from gno code\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=\"chain/gnoland1.1\" prevents gnoland1.0 from resuming.\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/v3. Without this\n// guard, a generic NewSysParam*PropRequest(\"node\",\"valset\",...) would\n// let any GovDAO supermajority bypass the v3 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/v3; 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":"params_test.gno","body":"package params\n\nimport (\n\t\"testing\"\n)\n\n// These tests cover proposal CONSTRUCTION. Reading a value back is possible --\n// sys/params exposes typed getters (GetSysParamStrings and friends), which\n// valset.gno and delegate_test.gno both use, and tests can seed with\n// testing.SetSysParam* -- so add read-back assertions rather than assuming they\n// cannot be written. End-to-end execution is additionally covered by the\n// propX_filetest.gno files under r/gov/dao/.\n\nfunc TestNewStringPropRequest(cur realm, t *testing.T) {\n\tpr := NewSysParamStringPropRequest(cur, \"foo\", \"bar\", \"baz\", \"qux\")\n\tif pr.Title() == \"\" {\n\t\tt.Errorf(\"executor shouldn't be nil\")\n\t}\n}\n\nfunc TestNewSetHaltRequest(cur realm, t *testing.T) {\n\tpr := NewSetHaltRequest(cur, 100_000, \"chain/gnoland1.1\")\n\tif pr.Title() == \"\" {\n\t\tt.Errorf(\"proposal title shouldn't be empty\")\n\t}\n}\n\nfunc TestNewSetHaltRequestNoVersion(cur realm, t *testing.T) {\n\tpr := NewSetHaltRequest(cur, 100_000, \"\")\n\tif pr.Title() == \"\" {\n\t\tt.Errorf(\"proposal title shouldn't be empty\")\n\t}\n}\n\nfunc TestNewSetHaltRequestCancel(cur realm, t *testing.T) {\n\tpr := NewSetHaltRequest(cur, 0, \"\")\n\tif pr.Title() == \"\" {\n\t\tt.Errorf(\"proposal title shouldn't be empty\")\n\t}\n}\n"},{"name":"render.gno","body":"package params\n\nimport (\n\t\"gno.land/p/moul/md\"\n\t\"gno.land/p/moul/mdtable\"\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\"\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":"unlock_test.gno","body":"package params\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n\t\"gno.land/r/gov/dao\"\n\tini \"gno.land/r/gov/dao/v3/init\"\n)\n\nvar g1user = testutils.TestAddress(\"g1user\")\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(g1user))\n\tini.InitWithUsers(cross(cur), g1user)\n}\n\nfunc TestProUnlockTransfer(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(g1user))\n\n\tpr := ProposeUnlockTransferRequest(cur)\n\tid := dao.MustCreateProposal(cross(cur), pr)\n\tp, err := dao.GetProposal(id)\n\turequire.NoError(t, err)\n\turequire.Equal(t, unlockTransferTitle, p.Title())\n}\n\nfunc TestFailUnlockTransfer(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(g1user))\n\n\tpr := ProposeUnlockTransferRequest(cur)\n\tid := dao.MustCreateProposal(cross(cur), pr)\n\turequire.AbortsWithMessage(\n\t\tt, cur,\n\t\t\"proposal didn't reach supermajority yet: 66.66\",\n\t\tfunc() {\n\t\t\tdao.ExecuteProposal(cross(cur), id)\n\t\t},\n\t)\n}\n\nfunc TestExeUnlockTransfer(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(g1user))\n\n\tpr := ProposeUnlockTransferRequest(cur)\n\tid := dao.MustCreateProposal(cross(cur), pr)\n\t_, err := dao.GetProposal(id)\n\turequire.NoError(t, err)\n\t// urequire.True(t, dao.Active == p.Status()) // TODO\n\n\turequire.NotPanics(\n\t\tt, cur,\n\t\tfunc() {\n\t\t\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(id)))\n\t\t},\n\t)\n\n\turequire.NotPanics(\n\t\tt, cur,\n\t\tfunc() {\n\t\t\tdao.ExecuteProposal(cross(cur), id)\n\t\t},\n\t)\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\"\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 = v3'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/v3\"\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 v3 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 v3 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/v3's internal\n// reads. Other realms making \"is X a validator\" decisions should\n// call v3.IsValidator, not this directly, so future changes to v3'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 v3'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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"12FFf6SBwaw+M3wI7ZaGulH9MAV4kJ2vnbXTzAianZkJvtEQgJpyfS3xHVwAvL6UjY8F3G/JwfUxWcfQTXZedA=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l","package":{"name":"validators","path":"gno.land/r/sys/validators/v3","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\"\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// (v3 imports valopers and reads them) — pulling would create an\n// import cycle, since valopers already imports v3 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 v3 → valopers\n// callbacks would make valopers see v3 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":"cache_test.gno","body":"package validators\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/bptree/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\tsysparams \"gno.land/r/sys/params\"\n)\n\n// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\n\n// resetCache clears valoperCache so subtests don't leak state.\nfunc resetCache() {\n\tvaloperCache = bptree.NewBPTree32()\n}\n\nfunc TestNotifyValoperChanged_HappyPath(cur realm, t *testing.T) {\n\tresetCache()\n\n\top := testutils.TestAddress(\"op-A\")\n\tsigningAddr := mustAddr(t, pubKeyA)\n\n\t// Caller realm = valopers; auth check passes.\n\ttesting.SetRealm(testing.NewCodeRealm(valopersRealmPath))\n\n\tNotifyValoperChanged(cross(cur), op, pubKeyA, signingAddr, true)\n\n\trawEntry := valoperCache.Get(op.String())\n\turequire.NotNil(t, rawEntry, \"cache entry must exist\")\n\tentry := rawEntry.(cacheEntry)\n\tuassert.Equal(t, pubKeyA, entry.SigningPubKey)\n\tuassert.Equal(t, signingAddr, entry.SigningAddress)\n\tuassert.Equal(t, true, entry.KeepRunning)\n\n\t// Subsequent call updates the same slot.\n\tsigningAddrB := mustAddr(t, pubKeyB)\n\tNotifyValoperChanged(cross(cur), op, pubKeyB, signingAddrB, false)\n\n\trawEntry = valoperCache.Get(op.String())\n\turequire.NotNil(t, rawEntry)\n\tentry = rawEntry.(cacheEntry)\n\tuassert.Equal(t, pubKeyB, entry.SigningPubKey)\n\tuassert.Equal(t, signingAddrB, entry.SigningAddress)\n\tuassert.Equal(t, false, entry.KeepRunning)\n}\n\nfunc TestNotifyValoperChanged_RejectsNonValopersCaller(cur realm, t *testing.T) {\n\tresetCache()\n\n\top := testutils.TestAddress(\"op-A\")\n\tsigningAddr := mustAddr(t, pubKeyA)\n\n\t// Caller realm = some other realm; auth check rejects.\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/attacker\"))\n\n\tuassert.AbortsContains(t, cur, \"caller realm must be \"+valopersRealmPath, func() {\n\t\tNotifyValoperChanged(cross(cur), op, pubKeyA, signingAddr, true)\n\t})\n\n\t// User MsgCall — UserRealm has empty pkgpath; rejected the same way.\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"user\")))\n\n\tuassert.AbortsContains(t, cur, \"caller realm must be \"+valopersRealmPath, func() {\n\t\tNotifyValoperChanged(cross(cur), op, pubKeyA, signingAddr, true)\n\t})\n}\n\nfunc TestRotateValoperSigningKey_AppliesRotation(cur realm, t *testing.T) {\n\tresetValset(t)\n\tresetCache()\n\n\t// Seed the valset with op-A signing under pubKeyA at power=10.\n\ttesting.SetSysParamStrings(module, submodule, currKey, []string{pubKeyA + \":10\"})\n\n\top := testutils.TestAddress(\"op-A\")\n\ttesting.SetRealm(testing.NewCodeRealm(valopersRealmPath))\n\n\tRotateValoperSigningKey(cross(cur), op, pubKeyA, pubKeyB)\n\n\t// After rotation the effective set (proposed-when-dirty) should\n\t// contain pubKeyB at the same power; pubKeyA should be gone.\n\tuassert.True(t, sysparams.ValsetDirty(), \"dirty bit set after RotateValoperSigningKey\")\n\n\teffective := sysparams.GetValsetEffective()\n\turequire.Equal(t, 1, len(effective))\n\tuassert.Equal(t, pubKeyB, effective[0].PubKey)\n\tuassert.Equal(t, uint64(10), effective[0].VotingPower)\n}\n\nfunc TestRotateValoperSigningKey_OperatorNotInValset_NoOp(cur realm, t *testing.T) {\n\tresetValset(t)\n\tresetCache()\n\n\t// Empty valset; the operator is not currently signing.\n\top := testutils.TestAddress(\"op-A\")\n\ttesting.SetRealm(testing.NewCodeRealm(valopersRealmPath))\n\n\t// Should not panic; no sysparams write expected (dirty stays false).\n\tuassert.NotAborts(t, cur, func() {\n\t\tRotateValoperSigningKey(cross(cur), op, pubKeyA, pubKeyB)\n\t})\n\n\tuassert.False(t, sysparams.ValsetDirty(), \"dirty bit must remain false on no-op rotation\")\n\tuassert.Equal(t, 0, len(sysparams.GetValsetEffective()))\n}\n\nfunc TestRotateValoperSigningKey_RejectsNonValopersCaller(cur realm, t *testing.T) {\n\tresetValset(t)\n\tresetCache()\n\ttesting.SetSysParamStrings(module, submodule, currKey, []string{pubKeyA + \":10\"})\n\n\top := testutils.TestAddress(\"op-A\")\n\n\t// Foreign realm — rejected.\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/attacker\"))\n\tuassert.AbortsContains(t, cur, \"caller realm must be \"+valopersRealmPath, func() {\n\t\tRotateValoperSigningKey(cross(cur), op, pubKeyA, pubKeyB)\n\t})\n\n\t// User MsgCall — UserRealm pkgpath is \"\" — rejected.\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"user\")))\n\tuassert.AbortsContains(t, cur, \"caller realm must be \"+valopersRealmPath, func() {\n\t\tRotateValoperSigningKey(cross(cur), op, pubKeyA, pubKeyB)\n\t})\n\n\t// Sanity: the valset wasn't mutated by the rejected calls (dirty\n\t// bit stays false; effective set still equals the seeded current).\n\tuassert.False(t, sysparams.ValsetDirty())\n\teffective := sysparams.GetValsetEffective()\n\turequire.Equal(t, 1, len(effective))\n\tuassert.Equal(t, pubKeyA, effective[0].PubKey)\n}\n\nfunc TestAssertGenesisValopersConsistent_HappyPath(cur realm, t *testing.T) {\n\tresetValset(t)\n\tresetCache()\n\ttesting.SetHeight(0) // assertion is genesis-mode only\n\n\t// Seed valset:current with two genesis validators.\n\ttesting.SetSysParamStrings(module, submodule, currKey, []string{\n\t\tpubKeyA + \":10\",\n\t\tpubKeyB + \":5\",\n\t})\n\n\t// Seed valoperCache with profiles whose SigningAddress matches.\n\topA := testutils.TestAddress(\"op-A\")\n\topB := testutils.TestAddress(\"op-B\")\n\tseedCache(t, []struct {\n\t\top          address\n\t\tpubKey      string\n\t\tkeepRunning bool\n\t}{\n\t\t{op: opA, pubKey: pubKeyA, keepRunning: true},\n\t\t{op: opB, pubKey: pubKeyB, keepRunning: true},\n\t})\n\n\tuassert.NotAborts(t, cur, func() {\n\t\tAssertGenesisValopersConsistent(cross(cur))\n\t})\n}\n\nfunc TestAssertGenesisValopersConsistent_PanicsOnMissingProfile(cur realm, t *testing.T) {\n\tresetValset(t)\n\tresetCache()\n\ttesting.SetHeight(0)\n\n\t// Two validators in valset:current but only one has a profile.\n\ttesting.SetSysParamStrings(module, submodule, currKey, []string{\n\t\tpubKeyA + \":10\",\n\t\tpubKeyB + \":5\",\n\t})\n\n\topA := testutils.TestAddress(\"op-A\")\n\tseedCache(t, []struct {\n\t\top          address\n\t\tpubKey      string\n\t\tkeepRunning bool\n\t}{\n\t\t{op: opA, pubKey: pubKeyA, keepRunning: true},\n\t\t// op for pubKeyB intentionally missing.\n\t})\n\n\tuassert.AbortsContains(t, cur, \"no corresponding valoper profile\", func() {\n\t\tAssertGenesisValopersConsistent(cross(cur))\n\t})\n}\n\nfunc TestAssertGenesisValopersConsistent_EmptyValsetTrivial(cur realm, t *testing.T) {\n\tresetValset(t)\n\tresetCache()\n\ttesting.SetHeight(0)\n\n\t// Empty valset → assertion trivially holds (no entries to check).\n\tuassert.NotAborts(t, cur, func() {\n\t\tAssertGenesisValopersConsistent(cross(cur))\n\t})\n}\n\nfunc TestAssertGenesisValopersConsistent_RejectsPostGenesis(cur realm, t *testing.T) {\n\tresetValset(t)\n\tresetCache()\n\t// Default test height is non-zero (123); the assertion must\n\t// refuse to run outside genesis-mode replay.\n\tuassert.AbortsContains(t, cur, \"only callable during genesis-mode replay\", func() {\n\t\tAssertGenesisValopersConsistent(cross(cur))\n\t})\n}\n\nfunc TestRotateValoperSigningKey_AccumulatesAcrossSameBlock(cur realm, t *testing.T) {\n\tresetValset(t)\n\tresetCache()\n\n\t// Seed valset with two operators signing under pubKeyA and pubKeyC.\n\ttesting.SetSysParamStrings(module, submodule, currKey, []string{\n\t\tpubKeyA + \":10\",\n\t\tpubKeyC + \":5\",\n\t})\n\n\topA := testutils.TestAddress(\"op-A\")\n\topC := testutils.TestAddress(\"op-C\")\n\ttesting.SetRealm(testing.NewCodeRealm(valopersRealmPath))\n\n\t// First rotation: A → B. Read-modify-write of GetValsetEffective.\n\tRotateValoperSigningKey(cross(cur), opA, pubKeyA, pubKeyB)\n\n\t// Second rotation in the same block: C → A. Should not clobber\n\t// the first rotation; should read proposed-when-dirty as baseline.\n\tRotateValoperSigningKey(cross(cur), opC, pubKeyC, pubKeyA)\n\n\t// Final effective set: {pubKeyB:10, pubKeyA:5}. Order may differ\n\t// because GetValsetEffective parses sysparams' sorted-string slot\n\t// and returns []Validator preserving that order.\n\teffective := sysparams.GetValsetEffective()\n\turequire.Equal(t, 2, len(effective))\n\n\t// Build a power-by-pubkey map and assert.\n\tpowerOf := map[string]uint64{}\n\tfor _, v := range effective {\n\t\tpowerOf[v.PubKey] = v.VotingPower\n\t}\n\tuassert.Equal(t, uint64(10), powerOf[pubKeyB])\n\tuassert.Equal(t, uint64(5), powerOf[pubKeyA])\n\t_, ok := powerOf[pubKeyC]\n\tuassert.False(t, ok, \"pubKeyC should be replaced by pubKeyA at the rotated slot\")\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/sys/validators/v3\"\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\"\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 v3 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":"proposal_test.gno","body":"package validators\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\t\"gno.land/p/nt/urequire/v0\"\n\tsysparams \"gno.land/r/sys/params\"\n)\n\n// seedCache populates valoperCache with the given (op, pubkey, kr)\n// tuples — used in tests to satisfy NewValidatorProposalRequest's\n// creation-time membership check without going through valopers.\nfunc seedCache(t *testing.T, entries []struct {\n\top          address\n\tpubKey      string\n\tkeepRunning bool\n}) {\n\tt.Helper()\n\tfor _, e := range entries {\n\t\tsigningAddr := mustAddr(t, e.pubKey)\n\t\tvaloperCache.Set(e.op.String(), cacheEntry{\n\t\t\tSigningPubKey:  e.pubKey,\n\t\t\tSigningAddress: signingAddr,\n\t\t\tKeepRunning:    e.keepRunning,\n\t\t})\n\t}\n}\n\nfunc TestNewValidatorProposalRequest_RejectsUnknownOperator(cur realm, t *testing.T) {\n\tresetCache()\n\n\top := testutils.TestAddress(\"ghost-op\")\n\n\tuassert.PanicsContains(t, cur, \"unknown operator\", func() {\n\t\t_ = NewValidatorProposalRequest(cur,\n\t\t\t[]ValoperChange{{OperatorAddress: op, Power: 1}},\n\t\t\t\"add ghost\",\n\t\t\t\"\",\n\t\t)\n\t})\n}\n\nfunc TestNewValidatorProposalRequest_RejectsEmptyChanges(cur realm, t *testing.T) {\n\tresetCache()\n\n\tuassert.PanicsContains(t, cur, errNoValoperChanges, func() {\n\t\t_ = NewValidatorProposalRequest(cur, nil, \"title\", \"\")\n\t})\n}\n\nfunc TestNewValidatorProposalRequest_RejectsEmptyTitle(cur realm, t *testing.T) {\n\tresetCache()\n\top := testutils.TestAddress(\"op-A\")\n\tseedCache(t, []struct {\n\t\top          address\n\t\tpubKey      string\n\t\tkeepRunning bool\n\t}{{op: op, pubKey: pubKeyA, keepRunning: true}})\n\n\tuassert.PanicsContains(t, cur, \"proposal title is empty\", func() {\n\t\t_ = NewValidatorProposalRequest(cur,\n\t\t\t[]ValoperChange{{OperatorAddress: op, Power: 1}},\n\t\t\t\"   \",\n\t\t\t\"\",\n\t\t)\n\t})\n}\n\nfunc TestNewValidatorProposalRequest_RejectsTooManyChanges(cur realm, t *testing.T) {\n\tresetCache()\n\n\t// Seed 41 cache entries so the membership check passes; the\n\t// length cap should fire before the per-entry validation.\n\tchanges := make([]ValoperChange, 41)\n\tpubkeys := []string{pubKeyA, pubKeyB, pubKeyC}\n\tfor i := 0; i \u003c 41; i++ {\n\t\top := testutils.TestAddress(\"op-\" + strconv.Itoa(i))\n\t\tpk := pubkeys[i%3]\n\t\tvaloperCache.Set(op.String(), cacheEntry{\n\t\t\tSigningPubKey:  pk,\n\t\t\tSigningAddress: mustAddr(t, pk),\n\t\t\tKeepRunning:    true,\n\t\t})\n\t\tchanges[i] = ValoperChange{OperatorAddress: op, Power: 1}\n\t}\n\n\tuassert.PanicsContains(t, cur, \"max number of allowed validators per proposal is 40\", func() {\n\t\t_ = NewValidatorProposalRequest(cur, changes, \"too many\", \"\")\n\t})\n}\n\nfunc TestNewValidatorProposalRequest_DescriptionRendering(cur realm, t *testing.T) {\n\tresetCache()\n\topA := testutils.TestAddress(\"op-A\")\n\topB := testutils.TestAddress(\"op-B\")\n\tseedCache(t, []struct {\n\t\top          address\n\t\tpubKey      string\n\t\tkeepRunning bool\n\t}{\n\t\t{op: opA, pubKey: pubKeyA, keepRunning: true},\n\t\t{op: opB, pubKey: pubKeyB, keepRunning: true},\n\t})\n\n\tpr := NewValidatorProposalRequest(cur,\n\t\t[]ValoperChange{\n\t\t\t{OperatorAddress: opA, Power: 5},\n\t\t\t{OperatorAddress: opB, Power: 0},\n\t\t},\n\t\t\"mixed changes\",\n\t\t\"context line\",\n\t)\n\n\tdesc := pr.Description()\n\turequire.True(t, len(desc) \u003e 0)\n\tuassert.True(t, contains(desc, \"context line\"))\n\tuassert.True(t, contains(desc, \"## Validator Updates\"))\n\tuassert.True(t, contains(desc, opA.String()+\": add (power 5)\"))\n\tuassert.True(t, contains(desc, opB.String()+\": remove\"))\n}\n\nfunc TestNewValidatorProposalRequest_ExecutorReResolvesPubkey(cur realm, t *testing.T) {\n\t// Creation-time captured changes: ValoperChange refers to opA.\n\t// Cache for opA points to pubKeyA at creation. Before execution,\n\t// opA's cache entry is updated to pubKeyB. Executor must publish\n\t// the NEW pubkey, not the creation-time one.\n\tresetValset(t)\n\tresetCache()\n\n\topA := testutils.TestAddress(\"op-A\")\n\tseedCache(t, []struct {\n\t\top          address\n\t\tpubKey      string\n\t\tkeepRunning bool\n\t}{{op: opA, pubKey: pubKeyA, keepRunning: true}})\n\n\tchanges := []ValoperChange{{OperatorAddress: opA, Power: 7}}\n\n\t// Build the executor; it captures `changes` by reference (slice\n\t// of structs) but resolves SigningPubKey at run-time via cache.\n\texec := newValoperChangeExecutor(cur, changes)\n\n\t// Simulate operator rotation: opA's cache entry now points to\n\t// pubKeyB. Captured changes slice is unchanged.\n\tvaloperCache.Set(opA.String(), cacheEntry{\n\t\tSigningPubKey:  pubKeyB,\n\t\tSigningAddress: mustAddr(t, pubKeyB),\n\t\tKeepRunning:    true,\n\t})\n\n\turequire.NoError(t, exec.Execute(cross(cur)))\n\n\t// Effective valset should contain pubKeyB (post-rotation), not\n\t// pubKeyA (creation-time).\n\teffective := sysparams.GetValsetEffective()\n\turequire.Equal(t, 1, len(effective))\n\tuassert.Equal(t, pubKeyB, effective[0].PubKey)\n\tuassert.Equal(t, uint64(7), effective[0].VotingPower)\n}\n\nfunc TestNewValidatorProposalRequest_RemoveOperator(cur realm, t *testing.T) {\n\tresetValset(t)\n\tresetCache()\n\n\t// Seed valset with opA already signing under pubKeyA.\n\ttesting.SetSysParamStrings(module, submodule, currKey, []string{pubKeyA + \":10\"})\n\n\topA := testutils.TestAddress(\"op-A\")\n\tseedCache(t, []struct {\n\t\top          address\n\t\tpubKey      string\n\t\tkeepRunning bool\n\t}{{op: opA, pubKey: pubKeyA, keepRunning: false}})\n\n\t// Liveness floor: removing the only validator empties the set.\n\t// Executor runs inside a crossing dao.Executor.Execute call, so\n\t// the panic surfaces as an abort, not a regular panic.\n\tuassert.AbortsContains(t, cur, \"would empty the validator set\", func() {\n\t\t_ = newValoperChangeExecutor(cur, []ValoperChange{{OperatorAddress: opA, Power: 0}}).Execute(cross(cur))\n\t})\n}\n\nfunc TestNewValidatorProposalRequest_RemoveLeavesOthers(cur realm, t *testing.T) {\n\tresetValset(t)\n\tresetCache()\n\n\t// Seed valset with two validators.\n\ttesting.SetSysParamStrings(module, submodule, currKey, []string{\n\t\tpubKeyA + \":10\",\n\t\tpubKeyB + \":5\",\n\t})\n\n\topA := testutils.TestAddress(\"op-A\")\n\topB := testutils.TestAddress(\"op-B\")\n\tseedCache(t, []struct {\n\t\top          address\n\t\tpubKey      string\n\t\tkeepRunning bool\n\t}{\n\t\t{op: opA, pubKey: pubKeyA, keepRunning: true},\n\t\t{op: opB, pubKey: pubKeyB, keepRunning: true},\n\t})\n\n\tchanges := []ValoperChange{{OperatorAddress: opA, Power: 0}}\n\t// Build the executor directly (private function, same package).\n\turequire.NoError(t, newValoperChangeExecutor(cur, changes).Execute(cross(cur)))\n\n\t// Effective set: only opB / pubKeyB remains.\n\teffective := sysparams.GetValsetEffective()\n\turequire.Equal(t, 1, len(effective))\n\tuassert.Equal(t, pubKeyB, effective[0].PubKey)\n}\n\nfunc TestNewValidatorProposalRequest_AllowsFullValsetReplacement(cur realm, t *testing.T) {\n\tresetValset(t)\n\tresetCache()\n\n\ttesting.SetSysParamStrings(module, submodule, currKey, []string{pubKeyA + \":10\"})\n\n\topA := testutils.TestAddress(\"op-A\")\n\topB := testutils.TestAddress(\"op-B\")\n\tseedCache(t, []struct {\n\t\top          address\n\t\tpubKey      string\n\t\tkeepRunning bool\n\t}{\n\t\t{op: opA, pubKey: pubKeyA, keepRunning: false},\n\t\t{op: opB, pubKey: pubKeyB, keepRunning: true},\n\t})\n\n\tchanges := []ValoperChange{\n\t\t{OperatorAddress: opA, Power: 0},\n\t\t{OperatorAddress: opB, Power: 10},\n\t}\n\turequire.NoError(t, newValoperChangeExecutor(cur, changes).Execute(cross(cur)))\n\n\teffective := sysparams.GetValsetEffective()\n\turequire.Equal(t, 1, len(effective))\n\tuassert.Equal(t, pubKeyB, effective[0].PubKey)\n\tuassert.Equal(t, uint64(10), effective[0].VotingPower)\n}\n\nfunc TestNewValidatorProposalRequest_RejectsKeepRunningFalseAtCreation(cur realm, t *testing.T) {\n\tresetCache()\n\top := testutils.TestAddress(\"op-A\")\n\tseedCache(t, []struct {\n\t\top          address\n\t\tpubKey      string\n\t\tkeepRunning bool\n\t}{{op: op, pubKey: pubKeyA, keepRunning: false}})\n\n\tuassert.PanicsContains(t, cur, \"KeepRunning=false\", func() {\n\t\t_ = NewValidatorProposalRequest(cur,\n\t\t\t[]ValoperChange{{OperatorAddress: op, Power: 1}},\n\t\t\t\"add opted-out\", \"\",\n\t\t)\n\t})\n}\n\nfunc TestNewValidatorProposalRequest_AllowsRemoveOfKeepRunningFalse(cur realm, t *testing.T) {\n\t// KeepRunning=false is the operator's opt-out signal; removing\n\t// such an operator must still be allowed (it's the standard\n\t// exit path). Only adds are gated.\n\tresetValset(t)\n\tresetCache()\n\n\t// Seed the valset with two operators so removing one doesn't\n\t// trip the empty-valset liveness floor.\n\ttesting.SetSysParamStrings(module, submodule, currKey, []string{\n\t\tpubKeyA + \":10\",\n\t\tpubKeyB + \":5\",\n\t})\n\n\topA := testutils.TestAddress(\"op-A\")\n\topB := testutils.TestAddress(\"op-B\")\n\tseedCache(t, []struct {\n\t\top          address\n\t\tpubKey      string\n\t\tkeepRunning bool\n\t}{\n\t\t{op: opA, pubKey: pubKeyA, keepRunning: false}, // opted out\n\t\t{op: opB, pubKey: pubKeyB, keepRunning: true},\n\t})\n\n\t// Build proposal succeeds (remove path: Power=0 ignores KeepRunning).\n\tpr := NewValidatorProposalRequest(cur,\n\t\t[]ValoperChange{{OperatorAddress: opA, Power: 0}},\n\t\t\"remove opted-out opA\", \"\",\n\t)\n\t_ = pr\n\n\t// Executor also succeeds.\n\turequire.NoError(t, newValoperChangeExecutor(cur, []ValoperChange{{OperatorAddress: opA, Power: 0}}).Execute(cross(cur)))\n}\n\nfunc TestNewValidatorProposalRequest_RejectsDuplicateOp(cur realm, t *testing.T) {\n\t// Each operator may appear at most once per proposal; any shape\n\t// that mentions the same op twice must panic at create-time.\n\tresetCache()\n\top := testutils.TestAddress(\"op-A\")\n\tseedCache(t, []struct {\n\t\top          address\n\t\tpubKey      string\n\t\tkeepRunning bool\n\t}{{op: op, pubKey: pubKeyA, keepRunning: true}})\n\n\tcases := [][]ValoperChange{\n\t\t{{OperatorAddress: op, Power: 0}, {OperatorAddress: op, Power: 7}}, // remove + re-add\n\t\t{{OperatorAddress: op, Power: 7}, {OperatorAddress: op, Power: 8}}, // double add\n\t\t{{OperatorAddress: op, Power: 0}, {OperatorAddress: op, Power: 0}}, // double remove\n\t}\n\tfor _, changes := range cases {\n\t\tuassert.PanicsContains(t, cur, \"duplicate operator in proposal\", func() {\n\t\t\t_ = NewValidatorProposalRequest(cur, changes, \"dup\", \"\")\n\t\t})\n\t}\n}\n\nfunc TestNewValidatorProposalRequest_RejectsPowerUpdatePairForOptedOutOp(cur realm, t *testing.T) {\n\t// KeepRunning=false is binding: no proposal shape can keep an\n\t// opted-out operator in the active set. The dedupe rejection\n\t// fires before the KR check is even reached.\n\tresetCache()\n\top := testutils.TestAddress(\"op-A\")\n\tseedCache(t, []struct {\n\t\top          address\n\t\tpubKey      string\n\t\tkeepRunning bool\n\t}{{op: op, pubKey: pubKeyA, keepRunning: false}})\n\n\tuassert.PanicsContains(t, cur, \"duplicate operator in proposal\", func() {\n\t\t_ = NewValidatorProposalRequest(cur,\n\t\t\t[]ValoperChange{\n\t\t\t\t{OperatorAddress: op, Power: 0},\n\t\t\t\t{OperatorAddress: op, Power: 7},\n\t\t\t},\n\t\t\t\"bypass attempt\", \"\",\n\t\t)\n\t})\n}\n\nfunc TestNewValidatorProposalRequest_UpsertExistingValidator(cur realm, t *testing.T) {\n\t// Single-entry {op, newPower} against an op already in the\n\t// effective valset must upsert: the existing entry's power is\n\t// overwritten, no remove/re-add ceremony required.\n\tresetValset(t)\n\tresetCache()\n\n\t// Seed valset with two validators; we upsert opA's power.\n\ttesting.SetSysParamStrings(module, submodule, currKey, []string{\n\t\tpubKeyA + \":1\",\n\t\tpubKeyB + \":1\",\n\t})\n\n\topA := testutils.TestAddress(\"op-A\")\n\topB := testutils.TestAddress(\"op-B\")\n\tseedCache(t, []struct {\n\t\top          address\n\t\tpubKey      string\n\t\tkeepRunning bool\n\t}{\n\t\t{op: opA, pubKey: pubKeyA, keepRunning: true},\n\t\t{op: opB, pubKey: pubKeyB, keepRunning: true},\n\t})\n\n\tchanges := []ValoperChange{{OperatorAddress: opA, Power: 9}}\n\turequire.NoError(t, newValoperChangeExecutor(cur, changes).Execute(cross(cur)))\n\n\teffective := sysparams.GetValsetEffective()\n\tpowerOf := map[string]uint64{}\n\tfor _, v := range effective {\n\t\tpowerOf[v.PubKey] = v.VotingPower\n\t}\n\tuassert.Equal(t, uint64(9), powerOf[pubKeyA], \"opA power upserted from 1 to 9\")\n\tuassert.Equal(t, uint64(1), powerOf[pubKeyB], \"opB unchanged\")\n}\n\nfunc TestNewValidatorProposalRequest_ExecutorRejectsRaceFlippedKeepRunning(cur realm, t *testing.T) {\n\t// KeepRunning=true at proposal-create time; operator flips to\n\t// false BEFORE the executor runs. Race-safety check rejects.\n\tresetValset(t)\n\tresetCache()\n\n\top := testutils.TestAddress(\"op-A\")\n\tseedCache(t, []struct {\n\t\top          address\n\t\tpubKey      string\n\t\tkeepRunning bool\n\t}{{op: op, pubKey: pubKeyA, keepRunning: true}})\n\n\tchanges := []ValoperChange{{OperatorAddress: op, Power: 5}}\n\texec := newValoperChangeExecutor(cur, changes)\n\n\t// Operator flips KeepRunning=false BEFORE the executor runs.\n\tvaloperCache.Set(op.String(), cacheEntry{\n\t\tSigningPubKey:  pubKeyA,\n\t\tSigningAddress: mustAddr(t, pubKeyA),\n\t\tKeepRunning:    false,\n\t})\n\n\tuassert.AbortsContains(t, cur, \"KeepRunning=false at execution\", func() {\n\t\t_ = exec.Execute(cross(cur))\n\t})\n}\n\nfunc TestNewValidatorProposalRequest_NaturalRotationFlow_NoGhost(cur realm, t *testing.T) {\n\t// RotateValoperSigningKey publishes valset:proposed before any\n\t// subsequent executor reads, so baseline always reflects the\n\t// post-rotation state. A later power-update upserts at NEW only;\n\t// no OLD ghost.\n\tresetValset(t)\n\tresetCache()\n\n\ttesting.SetSysParamStrings(module, submodule, currKey, []string{\n\t\tpubKeyA + \":1\",\n\t\tpubKeyB + \":5\",\n\t})\n\topA := testutils.TestAddress(\"op-A\")\n\topB := testutils.TestAddress(\"op-B\")\n\tseedCache(t, []struct {\n\t\top          address\n\t\tpubKey      string\n\t\tkeepRunning bool\n\t}{\n\t\t{op: opA, pubKey: pubKeyA, keepRunning: true},\n\t\t{op: opB, pubKey: pubKeyB, keepRunning: true},\n\t})\n\n\ttesting.SetRealm(testing.NewCodeRealm(valopersRealmPath))\n\tRotateValoperSigningKey(cross(cur), opA, pubKeyA, pubKeyC)\n\tNotifyValoperChanged(cross(cur), opA, pubKeyC, mustAddr(t, pubKeyC), true)\n\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/gov/dao/v3/impl\"))\n\turequire.NoError(t, newValoperChangeExecutor(cur,\n\t\t[]ValoperChange{{OperatorAddress: opA, Power: 2}},\n\t).Execute(cross(cur)))\n\n\teffective := sysparams.GetValsetEffective()\n\tpowerOf := map[string]uint64{}\n\tfor _, v := range effective {\n\t\tpowerOf[v.PubKey] = v.VotingPower\n\t}\n\tuassert.Equal(t, uint64(2), powerOf[pubKeyC], \"opA published at NEW power=2\")\n\tuassert.Equal(t, uint64(5), powerOf[pubKeyB], \"opB unchanged\")\n\t_, ghost := powerOf[pubKeyA]\n\tuassert.False(t, ghost, \"OLD signing key (pubKeyA) must not linger in valset\")\n\turequire.Equal(t, 2, len(effective), \"exactly two entries — opA(NEW), opB\")\n}\n\nfunc TestNewValidatorProposalRequest_PhantomBaselineDocumentsUnreachableState(cur realm, t *testing.T) {\n\t// Pin executor behavior on a phantom state (cache=NEW,\n\t// valset:current=OLD, dirty=false) — unreachable via natural\n\t// flow because RotateValoperSigningKey publishes proposed\n\t// before NotifyValoperChanged updates the cache. If a future\n\t// code path ever updates the cache without going through\n\t// Rotate, the asymmetry would be a real bug; this test pins\n\t// the current behavior so the divergence surfaces.\n\tresetValset(t)\n\tresetCache()\n\n\ttesting.SetSysParamStrings(module, submodule, currKey, []string{\n\t\tpubKeyA + \":1\",\n\t\tpubKeyB + \":5\",\n\t})\n\n\topA := testutils.TestAddress(\"op-A\")\n\topB := testutils.TestAddress(\"op-B\")\n\tseedCache(t, []struct {\n\t\top          address\n\t\tpubKey      string\n\t\tkeepRunning bool\n\t}{\n\t\t{op: opA, pubKey: pubKeyC, keepRunning: true},\n\t\t{op: opB, pubKey: pubKeyB, keepRunning: true},\n\t})\n\n\turequire.NoError(t, newValoperChangeExecutor(cur,\n\t\t[]ValoperChange{{OperatorAddress: opA, Power: 2}},\n\t).Execute(cross(cur)))\n\n\teffective := sysparams.GetValsetEffective()\n\tpowerOf := map[string]uint64{}\n\tfor _, v := range effective {\n\t\tpowerOf[v.PubKey] = v.VotingPower\n\t}\n\tuassert.Equal(t, uint64(1), powerOf[pubKeyA], \"phantom OLD lingers from baseline\")\n\tuassert.Equal(t, uint64(2), powerOf[pubKeyC], \"executor upserts at NEW\")\n\tuassert.Equal(t, uint64(5), powerOf[pubKeyB], \"opB unchanged\")\n\turequire.Equal(t, 3, len(effective),\n\t\t\"three entries — phantom-state ghost; this state is unreachable via natural flow\")\n}\n\nfunc TestNewValidatorProposalRequest_SameBlockExecuteThenRotate(cur realm, t *testing.T) {\n\t// Same-block ordering: proposal-execute writes proposed\n\t// (dirty=true); a subsequent rotation reads proposed-when-dirty\n\t// and accumulates the prior power change rather than clobbering\n\t// back to current.\n\tresetValset(t)\n\tresetCache()\n\n\ttesting.SetSysParamStrings(module, submodule, currKey, []string{\n\t\tpubKeyA + \":1\",\n\t\tpubKeyB + \":5\",\n\t})\n\n\topA := testutils.TestAddress(\"op-A\")\n\topB := testutils.TestAddress(\"op-B\")\n\tseedCache(t, []struct {\n\t\top          address\n\t\tpubKey      string\n\t\tkeepRunning bool\n\t}{\n\t\t{op: opA, pubKey: pubKeyA, keepRunning: true},\n\t\t{op: opB, pubKey: pubKeyB, keepRunning: true},\n\t})\n\n\turequire.NoError(t, newValoperChangeExecutor(cur,\n\t\t[]ValoperChange{{OperatorAddress: opA, Power: 3}},\n\t).Execute(cross(cur)))\n\n\ttesting.SetRealm(testing.NewCodeRealm(valopersRealmPath))\n\tRotateValoperSigningKey(cross(cur), opA, pubKeyA, pubKeyC)\n\tNotifyValoperChanged(cross(cur), opA, pubKeyC, mustAddr(t, pubKeyC), true)\n\n\teffective := sysparams.GetValsetEffective()\n\tpowerOf := map[string]uint64{}\n\tfor _, v := range effective {\n\t\tpowerOf[v.PubKey] = v.VotingPower\n\t}\n\tuassert.Equal(t, uint64(3), powerOf[pubKeyC], \"rotation accumulates with prior upsert; final power=3\")\n\tuassert.Equal(t, uint64(5), powerOf[pubKeyB], \"opB unchanged\")\n\t_, gotOld := powerOf[pubKeyA]\n\tuassert.False(t, gotOld, \"OLD signing key (pubKeyA) must not appear after rotation\")\n\turequire.Equal(t, 2, len(effective), \"exactly two entries — opA(NEW) and opB\")\n}\n\n// TestNewValidatorProposalRequest_ExecutorVanishedCacheEntryPanics pins\n// the \"operator vanished from valoperCache between propose and execute\"\n// branch. No production path deletes from valoperCache today (only Set\n// is called by NotifyValoperChanged), but bptree.BPTree exposes Remove\n// so the underlying data structure does support deletion. This test\n// simulates that hypothetical state directly via the package-private\n// cache var to confirm the executor panics with the documented message\n// rather than silently mis-publishing an empty/wrong valset.\n//\n// If a future commit ever introduces a public cache-delete path, this\n// test still passes — it's a contract-pinning test for the panic itself.\n// If the team decides the branch is unreachable enough to drop, this\n// test is the first thing to break.\nfunc TestNewValidatorProposalRequest_ExecutorVanishedCacheEntryPanics(cur realm, t *testing.T) {\n\tresetValset(t)\n\tresetCache()\n\n\top := testutils.TestAddress(\"op-A\")\n\tseedCache(t, []struct {\n\t\top          address\n\t\tpubKey      string\n\t\tkeepRunning bool\n\t}{{op: op, pubKey: pubKeyA, keepRunning: true}})\n\n\texec := newValoperChangeExecutor(cur,\n\t\t[]ValoperChange{{OperatorAddress: op, Power: 5}},\n\t)\n\n\t// Simulate the unreachable-today state: cache entry deleted between\n\t// proposal-create and proposal-execute. Direct package-private mutation\n\t// (NOT a public API) — production code has no path here today.\n\t_, removed := valoperCache.Remove(op.String())\n\turequire.True(t, removed, \"fixture: cache entry must have been present before Remove\")\n\n\tuassert.AbortsContains(t, cur, \"operator vanished from valoperCache between propose and execute\", func() {\n\t\t_ = exec.Execute(cross(cur))\n\t})\n}\n\n// contains is a tiny strings.Contains shim so tests don't import a\n// new package.\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":"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\"\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 v3 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"},{"name":"validators_test.gno","body":"// Tests for stateless v3.\n//\n// State isolation: gno's test runner constructs a fresh testParams\n// per top-level TestXxx, but t.Run subtests share the same map.\n// Each subtest below seeds (or clears) the valset slots it cares\n// about up front; do the same when adding cases.\npackage validators\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nconst (\n\t// Three distinct deterministic test pubkeys (and the addresses\n\t// they derive to) used across the cases below. Stable across\n\t// runs.\n\tpubKeyA = \"gpub1pggj7ard9eg82cjtv4u52epjx56nzwgjyg9zq3ds6sdvc0shfkq02h6xx5g0jp04aadexfnpsmgjxu72xz9y30aqfrlpny\"\n\tpubKeyB = \"gpub1pggj7ard9eg82cjtv4u52epjx56nzwgjyg9zqwpdwpd0f9fvqla089ndw5g9hcsufad77fml2vlu73fk8q8sh8v72cza5p\"\n\tpubKeyC = \"gpub1pgfj7ard9eg82cjtv4u4xetrwqer2dntxyfzxz3pqddddqg2glc8x4fl7vxjlnr7p5a3czm5kcdp4239sg6yqdc4rc2r5cjrffs\"\n\n\tmodule    = \"node\"\n\tsubmodule = \"valset\"\n\tcurrKey   = \"current\"\n\tpropKey   = \"proposed\"\n\tdirtyKey  = \"dirty\"\n)\n\nfunc resetValset(t *testing.T) {\n\tt.Helper()\n\ttesting.SetSysParamStrings(module, submodule, currKey, []string{})\n\ttesting.SetSysParamStrings(module, submodule, propKey, []string{})\n\ttesting.SetSysParamBool(module, submodule, dirtyKey, false)\n}\n\nfunc mustAddr(t *testing.T, pk string) address {\n\tt.Helper()\n\ta, err := chain.PubKeyAddress(pk)\n\turequire.NoError(t, err, \"valid pubkey\")\n\treturn a\n}\n\nfunc TestEffectiveView_DirtyFalseReadsCurrent(cur realm, t *testing.T) {\n\tresetValset(t)\n\ttesting.SetSysParamStrings(module, submodule, currKey, []string{pubKeyA + \":10\"})\n\n\taddrA := mustAddr(t, pubKeyA)\n\turequire.True(t, IsValidator(addrA), \"A in current\")\n\turequire.Equal(t, 1, len(GetValidators()))\n}\n\nfunc TestEffectiveView_DirtyTrueReadsProposed(cur realm, t *testing.T) {\n\tresetValset(t)\n\ttesting.SetSysParamStrings(module, submodule, currKey, []string{pubKeyA + \":10\"})\n\ttesting.SetSysParamStrings(module, submodule, propKey, []string{pubKeyA + \":10\", pubKeyB + \":1\"})\n\ttesting.SetSysParamBool(module, submodule, dirtyKey, true)\n\n\taddrA := mustAddr(t, pubKeyA)\n\taddrB := mustAddr(t, pubKeyB)\n\turequire.True(t, IsValidator(addrA), \"A still visible\")\n\turequire.True(t, IsValidator(addrB), \"B visible via proposed\")\n\turequire.Equal(t, 2, len(GetValidators()))\n}\n\nfunc TestGetValidator_ReturnsParsedEntry(cur realm, t *testing.T) {\n\tresetValset(t)\n\ttesting.SetSysParamStrings(module, submodule, currKey, []string{pubKeyA + \":42\"})\n\n\tv := GetValidator(mustAddr(t, pubKeyA))\n\turequire.Equal(t, uint64(42), v.VotingPower)\n\turequire.Equal(t, pubKeyA, v.PubKey)\n}\n\nfunc TestRender_DefaultTestHeight(cur realm, t *testing.T) {\n\tresetValset(t)\n\ttesting.SetSysParamStrings(module, submodule, currKey, []string{pubKeyA + \":10\"})\n\n\tout := Render(\"\")\n\t// gnovm/pkg/test/test.go sets DefaultHeight = 123.\n\turequire.Equal(t,\n\t\t\"## Valset at height 123\\n\\n- #0: \"+mustAddr(t, pubKeyA).String()+\" (10)\\n\",\n\t\tout)\n}\n\n// The same-block accumulation, panic-on-remove-of-missing,\n// panic-on-add-of-existing, and pubkey-validation tests for the\n// signing-keyed NewProposalRequest/newValsetChangeExecutor were\n// removed alongside the function itself. Equivalent coverage for\n// the operator-keyed flow lives in proposal_test.gno\n// (TestNewValidatorProposalRequest_*) and cache_test.gno\n// (TestRotateValoperSigningKey_AccumulatesAcrossSameBlock).\n//\n// Empty-final-set rejection in the executor still applies; it's\n// covered by TestNewValidatorProposalRequest_RemoveOperator in\n// proposal_test.gno.\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"n8bToo7iQWTUh7K2X3GFEtVcRbXnyioAdcR5eKJAwjU2u8yXMwgsOFfC8TwuiuPBzySAKOssmbKsYjkDNqTQlA=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1g3lsfxhvaqgdv4ccemwpnms4fv6t3aq3p5z6u7","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\"\n)\n\nvar auth *authz.Authorizer\n\nfunc Auth() *authz.Authorizer {\n\treturn auth\n}\n\nfunc updateInstructions(_ int, rlm realm, newInstructions string) {\n\terr := auth.DoByCurrent(0, rlm, \"update-instructions\", func() error {\n\t\tinstructions = newInstructions\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc NewInstructionsProposalCallback(newInstructions string) func(realm) error {\n\tcb := func(cur realm) error {\n\t\tupdateInstructions(0, cur, newInstructions)\n\t\treturn nil\n\t}\n\n\treturn cb\n}\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":"admin_test.gno","body":"package valopers\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/authz\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// Earlier this test also asserted a panic (\"action can only be\n// executed by the contract\") when called without SetOriginCaller.\n// That panic was emitted by a `unsafe.CurrentRealm() == contractAddr`\n// check inside authz.ContractAuthority.Authorize, which has been\n// removed — it was .Title()-bypassable (runtime.CurrentRealm inside a\n// non-crossing closure walks past non-crossing frames to the\n// most-recent crossing ancestor, so a malicious caller could shape\n// the call chain to make the check resolve to contractAddr).\n//\n// Caller authentication is now upstream of the deleted gate:\n// authz.Authorizer.DoByCurrent requires `rlm.IsCurrent()`, and the\n// contract handler closure (registered at init in this realm) is the\n// remaining Class-4 trust root by lexical capture. There is no\n// negative path here to assert, so the prior expectation was retired\n// along with its source.\nfunc TestUpdateInstructions(cur realm, t *testing.T) {\n\tauth = authz.NewWithAuthority(\n\t\tauthz.NewContractAuthority(\n\t\t\t\"gno.land/r/gov/dao\",\n\t\t\tfunc(title string, action authz.PrivilegedAction) error {\n\t\t\t\treturn action()\n\t\t\t},\n\t\t),\n\t)\n\n\tnewInstructions := \"new instructions\"\n\n\tuassert.NotPanics(t, cur, func() {\n\t\tupdateInstructions(0, cur, newInstructions)\n\t})\n\n\tuassert.Equal(t, newInstructions, instructions)\n}\n\n// TestUpdateMinFee was removed: register_fee now lives in sysparams\n// (node:valoper:register_fee), governed via the generic\n// NewSysParamUint64PropRequest factory. See proposal.gno for the\n// replacement flow.\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\"\n\t\"gno.land/p/moul/txlink\"\n\t\"gno.land/p/nt/avl/v0\"\n)\n\nfunc init() {\n\tvalopers = avl.NewTree()\n\n\tauth = authz.NewWithAuthority(\n\t\tauthz.NewContractAuthority(\n\t\t\t\"gno.land/r/gnops/valopers\",\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":"pubkey_type_test.gno","body":"package valopers\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\nconst (\n\ttestEd25519PubKey   = \"gpub1pggj7ard9eg82cjtv4u52epjx56nzwgjyg9zqkn3nln2k8glpf9kpqtz4h63n7cd0jvxkq6rpk4dxzp4sq527mhqwv40hr\"\n\ttestSecp256k1PubKey = \"gpub1pgfj7ard9eg82cjtv4u4xetrwqer2dntxyfzxz3pq0skzdkmzu0r9h6gny6eg8c9dc303xrrudee6z4he4y7cs5rnjwmyf40yaj\"\n)\n\nfunc TestPubKeyTypeURL(t *testing.T) {\n\tgot, err := pubKeyTypeURL(testEd25519PubKey)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, \"/tm.PubKeyEd25519\", got)\n\n\tgot, err = pubKeyTypeURL(testSecp256k1PubKey)\n\tuassert.NoError(t, err)\n\tuassert.Equal(t, \"/tm.PubKeySecp256k1\", got)\n\n\t_, err = pubKeyTypeURL(\"not-a-valid-bech32-pubkey\")\n\tuassert.Error(t, err)\n}\n\nfunc TestAssertPubKeyTypeAllowed(t *testing.T) {\n\t// Empty allow-list accepts any well-formed type.\n\ttesting.SetSysParamStrings(\"node\", \"valset\", \"pubkey_types\", []string{})\n\tuassert.NotPanics(t, cur, func() { assertPubKeyTypeAllowed(testSecp256k1PubKey) })\n\n\t// ed25519-only allow-list: ed25519 accepted, secp256k1 rejected.\n\ttesting.SetSysParamStrings(\"node\", \"valset\", \"pubkey_types\", []string{\"/tm.PubKeyEd25519\"})\n\tuassert.NotPanics(t, cur, func() { assertPubKeyTypeAllowed(testEd25519PubKey) })\n\tuassert.PanicsWithMessage(t, cur, ErrDisallowedPubKeyType.Error(), func() {\n\t\tassertPubKeyTypeAllowed(testSecp256k1PubKey)\n\t})\n\n\t// Reset so the non-empty allow-list doesn't leak into other tests.\n\ttesting.SetSysParamStrings(\"node\", \"valset\", \"pubkey_types\", []string{})\n}\n"},{"name":"rotate_test.gno","body":"package valopers\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\t\"gno.land/p/nt/urequire/v0\"\n)\n\nconst (\n\t// Second valid pubkey used as the rotation target. Distinct from\n\t// validValidatorInfo's pubkey so the signingRegistry uniqueness\n\t// check is exercised.\n\trotateTargetPubKey = \"gpub1pggj7ard9eg82cjtv4u52epjx56nzwgjyg9zq3ds6sdvc0shfkq02h6xx5g0jp04aadexfnpsmgjxu72xz9y30aqfrlpny\"\n\n\t// Test-local mirror of the rotation_period_blocks sys-param's\n\t// default. resetState() seeds the same value into sysparams.\n\ttestRotationPeriodBlocks = int64(600)\n)\n\n// registerForRotation does the boilerplate setup that every rotation\n// test starts from: clear state, register the valoper as info.Address,\n// and return the info struct. rlm is threaded into Register via\n// cross(rlm) — it's a non-first parameter so the helper stays a\n// regular (non-crossing) function.\nfunc registerForRotation(t *testing.T, rlm realm) struct {\n\tMoniker     string\n\tDescription string\n\tServerType  string\n\tAddress     address\n\tPubKey      string\n} {\n\tt.Helper()\n\tresetState()\n\tinfo := validValidatorInfo(t)\n\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\ttesting.SetOriginSend(chain.Coins{minFee})\n\tRegister(cross(rlm), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\treturn info\n}\n\nfunc TestUpdateSigningKey_HappyPath(cur realm, t *testing.T) {\n\tinfo := registerForRotation(t, cur)\n\n\t// Advance past the throttle window. SkipHeights doesn't preserve\n\t// the realm context across the boundary, so re-set it before the\n\t// next cross-call.\n\ttesting.SkipHeights(testRotationPeriodBlocks + 1)\n\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\n\tuassert.NotAborts(t, cur, func() {\n\t\tUpdateSigningKey(cross(cur), info.Address, rotateTargetPubKey)\n\t})\n\n\tv := GetByAddr(info.Address)\n\tuassert.Equal(t, rotateTargetPubKey, v.SigningPubKey)\n\n\tnewSigningAddr, err := chain.PubKeyAddress(rotateTargetPubKey)\n\turequire.NoError(t, err)\n\tuassert.Equal(t, newSigningAddr, v.SigningAddress)\n\n\t// New entry active in registry.\n\trawNew := signingRegistry.Get(newSigningAddr.String())\n\turequire.NotNil(t, rawNew, \"new signing addr in registry\")\n\tnewEntry := rawNew.(regEntry)\n\tuassert.Equal(t, info.Address, newEntry.OperatorAddress)\n\tuassert.Equal(t, int64(0), newEntry.RetiredAtHeight)\n\n\t// Old entry retired (still present, RetiredAtHeight \u003e 0).\n\toldSigningAddr, err := chain.PubKeyAddress(info.PubKey)\n\turequire.NoError(t, err)\n\trawOld := signingRegistry.Get(oldSigningAddr.String())\n\turequire.NotNil(t, rawOld, \"old signing addr retained as retired\")\n\toldEntry := rawOld.(regEntry)\n\tuassert.Equal(t, info.Address, oldEntry.OperatorAddress)\n\tuassert.True(t, oldEntry.RetiredAtHeight \u003e 0, \"old entry must be retired (RetiredAtHeight \u003e 0)\")\n}\n\nfunc TestUpdateSigningKey_ThrottleRejection(cur realm, t *testing.T) {\n\tinfo := registerForRotation(t, cur)\n\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\n\t// Try to rotate immediately, before throttle elapses.\n\tuassert.AbortsWithMessage(t, cur, ErrRotationThrottled.Error(), func() {\n\t\tUpdateSigningKey(cross(cur), info.Address, rotateTargetPubKey)\n\t})\n\n\t// Advance just shy of the threshold; still rejected.\n\ttesting.SkipHeights(testRotationPeriodBlocks - 1)\n\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\tuassert.AbortsWithMessage(t, cur, ErrRotationThrottled.Error(), func() {\n\t\tUpdateSigningKey(cross(cur), info.Address, rotateTargetPubKey)\n\t})\n\n\t// One more block — now exactly at the threshold; allowed.\n\ttesting.SkipHeights(1)\n\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\tuassert.NotAborts(t, cur, func() {\n\t\tUpdateSigningKey(cross(cur), info.Address, rotateTargetPubKey)\n\t})\n}\n\nfunc TestUpdateSigningKey_RejectsNonAuthListCaller(cur realm, t *testing.T) {\n\tinfo := registerForRotation(t, cur)\n\ttesting.SkipHeights(testRotationPeriodBlocks + 1)\n\n\t// Switch to a caller not on the auth list.\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"attacker\")))\n\n\t// Pin the exact authorizable error so this catches an auth\n\t// regression rather than any abort. Empty-substring match (the\n\t// previous form) accepted any panic, including unrelated ones.\n\tuassert.AbortsContains(t, cur, \"not in authorized list\", func() {\n\t\tUpdateSigningKey(cross(cur), info.Address, rotateTargetPubKey)\n\t})\n}\n\nfunc TestUpdateSigningKey_RejectsReuseOfActiveKey(cur realm, t *testing.T) {\n\tinfo := registerForRotation(t, cur)\n\ttesting.SkipHeights(testRotationPeriodBlocks + 1)\n\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\n\t// Try to \"rotate\" to the same key — already in registry.\n\tuassert.AbortsWithMessage(t, cur, ErrSigningKeyTaken.Error(), func() {\n\t\tUpdateSigningKey(cross(cur), info.Address, info.PubKey)\n\t})\n}\n\nfunc TestUpdateSigningKey_RejectsRotationOntoActiveValidator(cur realm, t *testing.T) {\n\t// Front-running guard: a rotation whose derived signing address is\n\t// already an active validator must be rejected. Mirrors the same\n\t// guard in Register (valopers.gno: ErrFrontrunValidator). Without\n\t// this, any valoper could rotate onto an unregistered (e.g.\n\t// genesis-seeded) validator slot — v3's executor would overwrite\n\t// the active validator's entry in the effective valset with this\n\t// operator's claim, then a subsequent govDAO remove-op proposal\n\t// would delete it. signingRegistry uniqueness alone doesn't catch\n\t// this case: a genesis-seeded validator never went through\n\t// Register or UpdateSigningKey, so its signing address is absent\n\t// from signingRegistry.\n\tinfo := registerForRotation(t, cur)\n\n\t// Seed v3's valset:current with the address that rotateTargetPubKey\n\t// derives to. ValsetEffective is read from valset:current when the\n\t// dirty flag is unset, which is the default.\n\ttesting.SetSysParamStrings(\"node\", \"valset\", \"current\",\n\t\t[]string{rotateTargetPubKey + \":1\"})\n\n\ttesting.SkipHeights(testRotationPeriodBlocks + 1)\n\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\n\tuassert.AbortsWithMessage(t, cur, ErrFrontrunValidator.Error(), func() {\n\t\tUpdateSigningKey(cross(cur), info.Address, rotateTargetPubKey)\n\t})\n\n\t// Cleanup: clear the seeded valset to avoid leaking into sibling\n\t// subtests if the runner doesn't reset package state between them.\n\ttesting.SetSysParamStrings(\"node\", \"valset\", \"current\", []string{})\n}\n\nfunc TestUpdateSigningKey_RejectsReuseOfRetiredKey(cur realm, t *testing.T) {\n\tinfo := registerForRotation(t, cur)\n\n\t// First rotation: info.PubKey -\u003e rotateTargetPubKey. info.PubKey\n\t// becomes retired.\n\ttesting.SkipHeights(testRotationPeriodBlocks + 1)\n\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\tUpdateSigningKey(cross(cur), info.Address, rotateTargetPubKey)\n\n\t// Second rotation back to info.PubKey must fail — it's retired\n\t// but signingRegistry retains it forever.\n\ttesting.SkipHeights(testRotationPeriodBlocks + 1)\n\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\tuassert.AbortsWithMessage(t, cur, ErrSigningKeyTaken.Error(), func() {\n\t\tUpdateSigningKey(cross(cur), info.Address, info.PubKey)\n\t})\n}\n\nfunc TestUpdateSigningKey_LastRotationHeightAdvances(cur realm, t *testing.T) {\n\tinfo := registerForRotation(t, cur)\n\ttesting.SkipHeights(testRotationPeriodBlocks + 1)\n\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\tUpdateSigningKey(cross(cur), info.Address, rotateTargetPubKey)\n\n\tv := GetByAddr(info.Address)\n\tuassert.True(t, v.LastRotationHeight \u003e 0, \"LastRotationHeight set on rotation\")\n\n\t// Immediately after, throttle rejects again.\n\tuassert.AbortsWithMessage(t, cur, ErrRotationThrottled.Error(), func() {\n\t\tUpdateSigningKey(cross(cur), info.Address, \"gpub1pgfj7ard9eg82cjtv4u4xetrwqer2dntxyfzxz3pqddddqg2glc8x4fl7vxjlnr7p5a3czm5kcdp4239sg6yqdc4rc2r5cjrffs\")\n\t})\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\"regexp\"\n\n\t\"gno.land/p/moul/realmpath\"\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/avl/v0/pager\"\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/combinederr/v0\"\n\t\"gno.land/p/nt/ownable/v0\"\n\t\"gno.land/p/nt/ownable/v0/exts/authorizable\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\tsysparams \"gno.land/r/sys/params\"\n\tvalidators \"gno.land/r/sys/validators/v3\"\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\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\nfunc (v Valoper) Auth() *authorizable.Authorizable {\n\treturn v.auth\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 (no IsUserCall): squatting\n// requires the attacker to be able to satisfy OriginCaller==victim,\n// which requires the victim's signing key. r/sys/namereg/v1.Register\n// also gates on IsUserCall, but that's because IT reads\n// unsafe.OriginSend() for the anti-squatting payment and IsUserCall\n// is needed to ensure the OriginSend envelope reflects what landed at\n// this realm rather than a phantom payment from a previous frame.\n// valopers.Register has no per-call payment-receipt check (fees are\n// validated against banker.OriginSend in a way that's symmetric to\n// IsUserCall via direct comparison), so the IsUserCall tightening\n// would only block legitimate `maketx run` flows (operator-authored\n// scripts that legitimately set OriginCaller==operator) without\n// adding identity-squat protection.\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\tminFee := chain.NewCoin(\"ugnot\", int64(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 v3'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 v3.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 v3'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; v3 emits\n// remove+add to sysparams via RotateValoperSigningKey; v3 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 v3.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\tminFee := chain.NewCoin(\"ugnot\", int64(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: v3.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 v3 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 v3, then refresh v3'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// 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"},{"name":"valopers_test.gno","body":"package valopers\n\nimport (\n\t\"chain\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/avl/v0\"\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/ownable/v0/exts/authorizable\"\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\n// Test-local fee constant. Production reads register_fee from sysparams;\n// these tests use this value as a reference Coin for OriginSend setup\n// and (when needed) seed it via testing.SetSysParamUint64.\nvar minFee = chain.NewCoin(\"ugnot\", 20*1_000_000)\n\n// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert dispatch helpers that gained an `rlm realm` param. These tests\n// pass `func()` callbacks (no crossing inside the callback), so rlm is\n// ignored — a nil realm here is safe.\nvar cur realm\n\n// resetState clears realm-level state and zeroes the valoper sys-params\n// so subtests don't leak through valopers (operator slots),\n// signingRegistry (signing-address uniqueness), or sys-param values.\nfunc resetState() {\n\tvalopers = avl.NewTree()\n\tsigningRegistry = bptree.NewBPTree32()\n\ttesting.SetSysParamUint64(\"node\", \"valoper\", \"register_fee\", 0)\n\ttesting.SetSysParamUint64(\"node\", \"valoper\", \"rotation_fee\", 0)\n\ttesting.SetSysParamInt64(\"node\", \"valoper\", \"rotation_period_blocks\", 600)\n}\n\n// enableRegisterFee seeds register_fee = minFee.Amount in sysparams\n// so the Register fee path fires. Subtests that exercise fee\n// rejection or sufficient-fee acceptance call this after resetState.\nfunc enableRegisterFee() {\n\ttesting.SetSysParamUint64(\"node\", \"valoper\", \"register_fee\", uint64(minFee.Amount))\n}\n\nfunc validValidatorInfo(t *testing.T) struct {\n\tMoniker     string\n\tDescription string\n\tServerType  string\n\tAddress     address\n\tPubKey      string\n} {\n\tt.Helper()\n\n\treturn struct {\n\t\tMoniker     string\n\t\tDescription string\n\t\tServerType  string\n\t\tAddress     address\n\t\tPubKey      string\n\t}{\n\t\tMoniker:     \"test-1\",\n\t\tDescription: \"test-1's description\",\n\t\tServerType:  ServerTypeOnPrem,\n\t\tAddress:     address(\"g1sp8v98h2gadm5jggtzz9w5ksexqn68ympsd68h\"),\n\t\tPubKey:      \"gpub1pggj7ard9eg82cjtv4u52epjx56nzwgjyg9zqwpdwpd0f9fvqla089ndw5g9hcsufad77fml2vlu73fk8q8sh8v72cza5p\",\n\t}\n}\n\nfunc TestValopers_Register(cur realm, t *testing.T) {\n\tt.Run(\"already a valoper\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\n\t\tv := Valoper{\n\t\t\tMoniker:         info.Moniker,\n\t\t\tDescription:     info.Description,\n\t\t\tServerType:      info.ServerType,\n\t\t\tOperatorAddress: info.Address,\n\t\t\tSigningPubKey:   info.PubKey,\n\t\t\tKeepRunning:     true,\n\t\t}\n\n\t\t// Add the valoper directly to the slot.\n\t\tvalopers.Set(v.OperatorAddress.String(), v)\n\n\t\t// Send coins.\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.AbortsWithMessage(t, cur, ErrValoperExists.Error(), func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\t})\n\n\tt.Run(\"no coins deposited\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\t\tenableRegisterFee()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\n\t\t// Send no coins.\n\t\ttesting.SetOriginSend(chain.Coins{chain.NewCoin(\"ugnot\", 0)})\n\n\t\tuassert.AbortsWithMessage(t, cur, ufmt.Sprintf(\"payment must not be less than %d%s\", minFee.Amount, minFee.Denom), func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\t})\n\n\tt.Run(\"insufficient coins amount deposited\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\t\tenableRegisterFee()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\n\t\t// Send invalid coins.\n\t\ttesting.SetOriginSend(chain.Coins{chain.NewCoin(\"ugnot\", minFee.Amount-1)})\n\n\t\tuassert.AbortsWithMessage(t, cur, ufmt.Sprintf(\"payment must not be less than %d%s\", minFee.Amount, minFee.Denom), func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\t})\n\n\tt.Run(\"coin amount deposited is not ugnot\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\t\tenableRegisterFee()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\n\t\t// Send invalid coins.\n\t\ttesting.SetOriginSend(chain.Coins{chain.NewCoin(\"gnogno\", minFee.Amount)})\n\n\t\tuassert.AbortsWithMessage(t, cur, \"incompatible coin denominations: gnogno, ugnot\", func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\t})\n\n\tt.Run(\"squat guard rejects mismatched OriginCaller\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\t// Caller is NOT info.Address: post-genesis squat guard fires.\n\t\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"attacker\")))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.AbortsWithMessage(t, cur, ErrOperatorSquatGuard.Error(), func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\t})\n\n\tt.Run(\"successful registration\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\n\t\t// Send coins.\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.NotAborts(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tvaloper := GetByAddr(info.Address)\n\n\t\t\tuassert.Equal(t, info.Moniker, valoper.Moniker)\n\t\t\tuassert.Equal(t, info.Description, valoper.Description)\n\t\t\tuassert.Equal(t, info.ServerType, valoper.ServerType)\n\t\t\tuassert.Equal(t, info.Address, valoper.OperatorAddress)\n\t\t\tuassert.Equal(t, info.PubKey, valoper.SigningPubKey)\n\t\t\tuassert.Equal(t, true, valoper.KeepRunning)\n\n\t\t\t// SigningAddress is derived from the pubkey and present.\n\t\t\tderived, err := chain.PubKeyAddress(info.PubKey)\n\t\t\tuassert.NoError(t, err)\n\t\t\tuassert.Equal(t, derived, valoper.SigningAddress)\n\n\t\t\t// signingRegistry tracks the active entry.\n\t\t\tuassert.True(t, signingRegistry.Has(derived.String()), \"signingRegistry must contain the active entry\")\n\t\t})\n\t})\n\n\tt.Run(\"signing-key reuse rejected\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\t// First registration succeeds.\n\t\tuassert.NotAborts(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\t// Second attempt with a different operator addr but the same\n\t\t// pubkey must fail signingRegistry uniqueness.\n\t\tother := testutils.TestAddress(\"other-op\")\n\t\ttesting.SetRealm(testing.NewUserRealm(other))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.AbortsWithMessage(t, cur, ErrSigningKeyTaken.Error(), func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, other, info.PubKey)\n\t\t})\n\t})\n\n\tt.Run(\"front-running guard rejects post-genesis if signing addr already validates\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\t// Seed v3's valset:current with the very signing address that\n\t\t// `info.PubKey` derives to (g1sp8v98...). Any post-genesis\n\t\t// Register attempting the same pubkey now trips\n\t\t// `ChainHeight()\u003e0 \u0026\u0026 validators.IsValidator(signingAddr)`.\n\t\ttesting.SetSysParamStrings(\"node\", \"valset\", \"current\", []string{info.PubKey + \":1\"})\n\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.AbortsWithMessage(t, cur, ErrFrontrunValidator.Error(), func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\t// Cleanup: clear the seeded valset to avoid leaking into\n\t\t// later subtests if the package state isn't reset between\n\t\t// them in this test runner mode.\n\t\ttesting.SetSysParamStrings(\"node\", \"valset\", \"current\", []string{})\n\t})\n}\n\nfunc TestValopers_Register_AuthOwnerIsOperatorAddress(cur realm, t *testing.T) {\n\t// Pin: the Authorizable owner is bound to the OperatorAddress\n\t// (the addr arg), NOT to OriginCaller. This matters in the\n\t// genesis-mode deployer pattern: one signer (e.g., the hardfork\n\t// ceremony deployer) registers profiles for many operators.\n\t// Each operator must end up on their own profile's auth list\n\t// so they can manage it post-genesis without depending on the\n\t// deployer.\n\tt.Run(\"genesis deployer pattern: operator (not deployer) is owner\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\tdeployer := testutils.TestAddress(\"deployer\")\n\n\t\t// Genesis mode: ChainHeight()==0 bypasses the squat guard so\n\t\t// deployer (OriginCaller) can register a profile for a\n\t\t// different operator addr.\n\t\ttesting.SetHeight(0)\n\t\ttesting.SetRealm(testing.NewUserRealm(deployer))\n\t\ttesting.SetOriginCaller(deployer)\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\t// Auth owner must be the operator addr (info.Address), NOT\n\t\t// the deployer.\n\t\tv := GetByAddr(info.Address)\n\t\tuassert.Equal(t, info.Address.String(), v.Auth().Owner().String(),\n\t\t\t\"auth owner must equal OperatorAddress, not OriginCaller\")\n\n\t\t// Operator can manage their own profile post-genesis.\n\t\ttesting.SetHeight(100)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginCaller(info.Address)\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tUpdateMoniker(cross(cur), info.Address, \"operator-renamed\")\n\t\t})\n\t\tuassert.Equal(t, \"operator-renamed\", GetByAddr(info.Address).Moniker)\n\n\t\t// Deployer cannot manage the operator's profile (not on the\n\t\t// auth list).\n\t\ttesting.SetRealm(testing.NewUserRealm(deployer))\n\t\ttesting.SetOriginCaller(deployer)\n\t\tuassert.AbortsContains(t, cur, \"caller is not in authorized list\", func() {\n\t\t\tUpdateMoniker(cross(cur), info.Address, \"deployer-attempt\")\n\t\t})\n\t})\n\n\tt.Run(\"post-genesis self-Register: operator is owner\", func(cur realm, t *testing.T) {\n\t\t// At H\u003e0 the squat guard forces OriginCaller==addr, so owner\n\t\t// would be the same regardless. This subtest pins that the\n\t\t// post-genesis behavior is unchanged.\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetHeight(100)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginCaller(info.Address)\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\tv := GetByAddr(info.Address)\n\t\tuassert.Equal(t, info.Address.String(), v.Auth().Owner().String())\n\t})\n}\n\nfunc TestValopers_UpdateAuthMembers(cur realm, t *testing.T) {\n\ttest2Address := testutils.TestAddress(\"test2\")\n\n\tt.Run(\"unauthorized member adds member\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\t// Add the valoper.\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\t// A different caller (not on the auth list) tries to add a member.\n\t\ttesting.SetRealm(testing.NewUserRealm(test2Address))\n\n\t\tuassert.AbortsWithMessage(t, cur, authorizable.ErrNotSuperuser.Error(), func() {\n\t\t\tAddToAuthList(cross(cur), info.Address, test2Address)\n\t\t})\n\t})\n\n\tt.Run(\"unauthorized member deletes member\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tAddToAuthList(cross(cur), info.Address, test2Address)\n\t\t})\n\n\t\t// A different caller tries to delete a member.\n\t\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"attacker\")))\n\n\t\tuassert.AbortsWithMessage(t, cur, authorizable.ErrNotSuperuser.Error(), func() {\n\t\t\tDeleteFromAuthList(cross(cur), info.Address, test2Address)\n\t\t})\n\t})\n\n\tt.Run(\"authorized member adds member\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tAddToAuthList(cross(cur), info.Address, test2Address)\n\t\t})\n\n\t\ttesting.SetRealm(testing.NewUserRealm(test2Address))\n\n\t\tnewMoniker := \"new moniker\"\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tUpdateMoniker(cross(cur), info.Address, newMoniker)\n\t\t})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tvaloper := GetByAddr(info.Address)\n\t\t\tuassert.Equal(t, newMoniker, valoper.Moniker)\n\t\t})\n\t})\n}\n\nfunc TestValopers_UpdateMoniker(cur realm, t *testing.T) {\n\ttest2Address := testutils.TestAddress(\"test2\")\n\n\tt.Run(\"non-existing valoper\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\n\t\tuassert.AbortsWithMessage(t, cur, ErrValoperMissing.Error(), func() {\n\t\t\tUpdateMoniker(cross(cur), info.Address, \"new moniker\")\n\t\t})\n\t})\n\n\tt.Run(\"invalid caller\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\t// Change the caller to someone not on the auth list.\n\t\ttesting.SetRealm(testing.NewUserRealm(test2Address))\n\n\t\tuassert.AbortsWithMessage(t, cur, authorizable.ErrNotInAuthList.Error(), func() {\n\t\t\tUpdateMoniker(cross(cur), info.Address, \"new moniker\")\n\t\t})\n\t})\n\n\tt.Run(\"invalid moniker\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\tinvalidMonikers := []string{\n\t\t\t\"\",     // Empty\n\t\t\t\"    \", // Whitespace\n\t\t\t\"a\",    // Too short\n\t\t\t\"a very long moniker that is longer than 32 characters\", // Too long\n\t\t\t\"!@#$%^\u0026*()+{}|:\u003c\u003e?/.,;'\",                               // Invalid characters\n\t\t\t\" space in front\",\n\t\t\t\"space in back \",\n\t\t}\n\n\t\tfor _, invalidMoniker := range invalidMonikers {\n\t\t\tuassert.AbortsWithMessage(t, cur, ErrInvalidMoniker.Error(), func() {\n\t\t\t\tUpdateMoniker(cross(cur), info.Address, invalidMoniker)\n\t\t\t})\n\t\t}\n\t})\n\n\tt.Run(\"too long moniker\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\tuassert.AbortsWithMessage(t, cur, ErrInvalidMoniker.Error(), func() {\n\t\t\tUpdateMoniker(cross(cur), info.Address, strings.Repeat(\"a\", MonikerMaxLength+1))\n\t\t})\n\t})\n\n\tt.Run(\"successful update\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\tnewMoniker := \"new moniker\"\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tUpdateMoniker(cross(cur), info.Address, newMoniker)\n\t\t})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tvaloper := GetByAddr(info.Address)\n\t\t\tuassert.Equal(t, newMoniker, valoper.Moniker)\n\t\t})\n\t})\n}\n\nfunc TestValopers_UpdateDescription(cur realm, t *testing.T) {\n\ttest2Address := testutils.TestAddress(\"test2\")\n\n\tt.Run(\"non-existing valoper\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tuassert.AbortsWithMessage(t, cur, ErrValoperMissing.Error(), func() {\n\t\t\tUpdateDescription(cross(cur), validValidatorInfo(t).Address, \"new description\")\n\t\t})\n\t})\n\n\tt.Run(\"invalid caller\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\ttesting.SetRealm(testing.NewUserRealm(test2Address))\n\n\t\tuassert.AbortsWithMessage(t, cur, authorizable.ErrNotInAuthList.Error(), func() {\n\t\t\tUpdateDescription(cross(cur), info.Address, \"new description\")\n\t\t})\n\t})\n\n\tt.Run(\"empty description\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\tuassert.AbortsWithMessage(t, cur, ErrInvalidDescription.Error(), func() {\n\t\t\tUpdateDescription(cross(cur), info.Address, \"\")\n\t\t})\n\t})\n\n\tt.Run(\"too long description\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\tuassert.AbortsWithMessage(t, cur, ErrInvalidDescription.Error(), func() {\n\t\t\tUpdateDescription(cross(cur), info.Address, strings.Repeat(\"a\", DescriptionMaxLength+1))\n\t\t})\n\t})\n\n\tt.Run(\"successful update\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\tnewDescription := \"new description\"\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tUpdateDescription(cross(cur), info.Address, newDescription)\n\t\t})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tvaloper := GetByAddr(info.Address)\n\t\t\tuassert.Equal(t, newDescription, valoper.Description)\n\t\t})\n\t})\n}\n\nfunc TestValopers_UpdateKeepRunning(cur realm, t *testing.T) {\n\ttest2Address := testutils.TestAddress(\"test2\")\n\n\tt.Run(\"non-existing valoper\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tuassert.AbortsWithMessage(t, cur, ErrValoperMissing.Error(), func() {\n\t\t\tUpdateKeepRunning(cross(cur), validValidatorInfo(t).Address, false)\n\t\t})\n\t})\n\n\tt.Run(\"invalid caller\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\ttesting.SetRealm(testing.NewUserRealm(test2Address))\n\n\t\tuassert.AbortsWithMessage(t, cur, authorizable.ErrNotInAuthList.Error(), func() {\n\t\t\tUpdateKeepRunning(cross(cur), info.Address, false)\n\t\t})\n\t})\n\n\tt.Run(\"successful update\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tUpdateKeepRunning(cross(cur), info.Address, false)\n\t\t})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tvaloper := GetByAddr(info.Address)\n\t\t\tuassert.Equal(t, false, valoper.KeepRunning)\n\t\t})\n\t})\n}\n\nfunc TestValopers_UpdateServerType(cur realm, t *testing.T) {\n\ttest2Address := testutils.TestAddress(\"test2\")\n\n\tt.Run(\"non-existing valoper\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tuassert.AbortsWithMessage(t, cur, ErrValoperMissing.Error(), func() {\n\t\t\tUpdateServerType(cross(cur), validValidatorInfo(t).Address, ServerTypeCloud)\n\t\t})\n\t})\n\n\tt.Run(\"invalid caller\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\ttesting.SetRealm(testing.NewUserRealm(test2Address))\n\n\t\tuassert.AbortsWithMessage(t, cur, authorizable.ErrNotInAuthList.Error(), func() {\n\t\t\tUpdateServerType(cross(cur), info.Address, ServerTypeCloud)\n\t\t})\n\t})\n\n\tt.Run(\"invalid server type\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\tinvalidServerTypes := []string{\n\t\t\t\"\",\n\t\t\t\"invalid\",\n\t\t\t\"Cloud\",      // case sensitive\n\t\t\t\"ON-PREM\",    // case sensitive\n\t\t\t\"datacenter\", // wrong format\n\t\t}\n\n\t\tfor _, invalidType := range invalidServerTypes {\n\t\t\tuassert.AbortsWithMessage(t, cur, ErrInvalidServerType.Error(), func() {\n\t\t\t\tUpdateServerType(cross(cur), info.Address, invalidType)\n\t\t\t})\n\t\t}\n\t})\n\n\tt.Run(\"successful update\", func(cur realm, t *testing.T) {\n\t\tresetState()\n\n\t\tinfo := validValidatorInfo(t)\n\t\ttesting.SetRealm(testing.NewUserRealm(info.Address))\n\t\ttesting.SetOriginSend(chain.Coins{minFee})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)\n\t\t})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tUpdateServerType(cross(cur), info.Address, ServerTypeCloud)\n\t\t})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tvaloper := GetByAddr(info.Address)\n\t\t\tuassert.Equal(t, ServerTypeCloud, valoper.ServerType)\n\t\t})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tUpdateServerType(cross(cur), info.Address, ServerTypeDataCenter)\n\t\t})\n\n\t\tuassert.NotPanics(t, cur, func() {\n\t\t\tvaloper := GetByAddr(info.Address)\n\t\t\tuassert.Equal(t, ServerTypeDataCenter, valoper.ServerType)\n\t\t})\n\t})\n}\n"},{"name":"z_1_filetest.gno","body":"// PKGPATH: gno.land/r/gnops/valopers/filetests/z_1\n// SEND: 20000000ugnot\n\npackage z_1\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/r/gnops/valopers\"\n)\n\nvar g1user = testutils.TestAddress(\"g1user\") // g1vuch2um9wf047h6lta047h6lta047h6l2ewm6w\n\nconst (\n\tvalidMoniker     = \"test-1\"\n\tvalidDescription = \"test-1's description\"\n\tvalidServerType  = valopers.ServerTypeOnPrem\n\tvalidAddress     = address(\"g1sp8v98h2gadm5jggtzz9w5ksexqn68ympsd68h\")\n\tvalidPubKey      = \"gpub1pggj7ard9eg82cjtv4u52epjx56nzwgjyg9zqwpdwpd0f9fvqla089ndw5g9hcsufad77fml2vlu73fk8q8sh8v72cza5p\"\n)\n\nfunc init(cur realm) {\n\t// OriginCaller must equal the operator address (post-genesis squat guard).\n\ttesting.SetOriginCaller(validAddress)\n\n\t// Register a validator and add the proposal\n\tvalopers.Register(cross(cur), validMoniker, validDescription, validServerType, validAddress, validPubKey)\n}\n\nfunc main() {\n\tprintln(valopers.Render(\"\"))\n}\n\n// Output:\n//\n// # Welcome to the **Valopers** realm\n//\n// ## 📌 Purpose of this Contract\n//\n// The **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//\n// By 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//\n// To add your validator node to the registry, use the [**Register**](/r/gnops/valopers$help\u0026func=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//\n// Please provide detailed answers to the following questions to ensure transparency and improve your chances of being accepted:\n//\n// 1. The name of your validator\n// 2. Networks you are currently validating and your total AuM (assets under management)\n// 3. 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.\n// 4. Contact details\n// 5. Why are you interested in validating on **gno.land**?\n// 6. What contributions have you made or are willing to make to **gno.land**?\n//\n// ---\n//\n// ## 🔄 Updating Your Validator Information\n//\n// After 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//\n// Once 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//\n// If you are a GovDAO member, you can nominate yourself by executing the following function: [**r/gnops/valopers/proposal.ProposeNewValidator**](/r/gnops/valopers/proposal$help\u0026func=ProposeNewValidator)\n//\n// This 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//\n// Read more: [How to become a validator](https://github.com/gnolang/gno/tree/master/gno.land/cmd/gnoland#become-a-validator)\n//\n// Disclaimer: 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//  * [test-1](/r/gnops/valopers:g1sp8v98h2gadm5jggtzz9w5ksexqn68ympsd68h) - [profile](/r/demo/profile:u/g1sp8v98h2gadm5jggtzz9w5ksexqn68ympsd68h)\n"},{"name":"z_2_filetest.gno","body":"// PKGPATH: gno.land/r/gnops/valopers/filetests/z_2\n// SEND: 20000000ugnot\n\npackage z_2\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/r/gnops/valopers\"\n)\n\nvar g1user = testutils.TestAddress(\"g1user\")\n\nconst (\n\tvalidMoniker     = \"test-1\"\n\tvalidDescription = \"test-1's description\"\n\tvalidServerType  = valopers.ServerTypeOnPrem\n\tvalidAddress     = address(\"g1sp8v98h2gadm5jggtzz9w5ksexqn68ympsd68h\")\n\tvalidPubKey      = \"gpub1pggj7ard9eg82cjtv4u52epjx56nzwgjyg9zqwpdwpd0f9fvqla089ndw5g9hcsufad77fml2vlu73fk8q8sh8v72cza5p\"\n)\n\nfunc init(cur realm) {\n\t// OriginCaller must equal the operator address (post-genesis squat guard).\n\t// validAddress here was chosen so that derive(validPubKey) == validAddress,\n\t// so OperatorAddress == SigningAddress in this fixture.\n\ttesting.SetOriginCaller(validAddress)\n\n\t// Register a validator and add the proposal\n\tvalopers.Register(cross(cur), validMoniker, validDescription, validServerType, validAddress, validPubKey)\n}\n\nfunc main() {\n\t// Simulate clicking on the validator\n\tprintln(valopers.Render(validAddress.String()))\n}\n\n// Output:\n// Valoper's details:\n// ## test-1\n// test-1's description\n//\n// - Operator Address: g1sp8v98h2gadm5jggtzz9w5ksexqn68ympsd68h\n// - Signing Address: g1sp8v98h2gadm5jggtzz9w5ksexqn68ympsd68h\n// - Signing PubKey: gpub1pggj7ard9eg82cjtv4u52epjx56nzwgjyg9zqwpdwpd0f9fvqla089ndw5g9hcsufad77fml2vlu73fk8q8sh8v72cza5p\n// - Server Type: on-prem\n//\n// [Profile link](/r/demo/profile:u/g1sp8v98h2gadm5jggtzz9w5ksexqn68ympsd68h)\n//\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"JAHGzwePXjk6QWuPD8bGYSw+svoK29iMdWscKsIZbascMd56sd/yrihq7qJPPu49hLZMW1Ub0MzJ04nDdyl5Pg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1g3lsfxhvaqgdv4ccemwpnms4fv6t3aq3p5z6u7","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/v3\"\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// v3's operator-keyed NewValidatorProposalRequest with a single-element\n// slice; v3'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 v3'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.\nfunc ProposeNewInstructionsProposalRequest(cur realm, newInstructions string) dao.ProposalRequest {\n\tcb := valopers.NewInstructionsProposalCallback(newInstructions)\n\t// Create a proposal\n\ttitle := \"/p/gnops/valopers: Update instructions\"\n\tdescription := ufmt.Sprintf(\"Update the instructions to: \\n\\n%s\", newInstructions)\n\n\te := dao.NewSimpleExecutor(0, cur, cb, \"\")\n\n\treturn dao.NewProposalRequest(title, description, e)\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"},{"name":"proposal_test.gno","body":"package proposal\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/p/nt/ufmt/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n\t\"gno.land/r/gnops/valopers\"\n\t\"gno.land/r/gov/dao\"\n\tdaoinit \"gno.land/r/gov/dao/v3/init\" // so that the govdao initializer is executed\n)\n\n// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\nvar g1user = testutils.TestAddress(\"g1user\")\n\nfunc init(cur realm) {\n\tdaoinit.InitWithUsers(cross(cur), g1user)\n}\n\nfunc TestValopers_ProposeNewValidator(cur realm, t *testing.T) {\n\tconst (\n\t\tregisterMinFee int64 = 20 * 1_000_000 // minimum gnot must be paid to register.\n\t\tproposalMinFee int64 = 100 * 1_000_000\n\n\t\tmoniker     string = \"moniker\"\n\t\tdescription string = \"description\"\n\t\tserverType  string = valopers.ServerTypeOnPrem\n\t\tpubKey             = \"gpub1pggj7ard9eg82cjtv4u52epjx56nzwgjyg9zqwpdwpd0f9fvqla089ndw5g9hcsufad77fml2vlu73fk8q8sh8v72cza5p\"\n\t)\n\n\t// signingAddr is derived from the pubkey and is what\n\t// v3.IsValidator/GetValidator return after a proposal lands\n\t// (parseEntry in r/sys/params canonicalizes from PubKey). Used\n\t// for the \"ErrSameValues\" subtest's post-execute check.\n\tsigningAddr, err := chain.PubKeyAddress(pubKey)\n\turequire.NoError(t, err, \"valid pubkey\")\n\n\t// The operator address is g1user (the GovDAO member); the\n\t// signing address is derived separately from pubKey. Splitting\n\t// them exercises the operator/signer separation.\n\topAddr := g1user\n\n\t// Set origin caller for valoper operations: must equal the\n\t// operator address (post-genesis squat guard in Register).\n\ttesting.SetRealm(testing.NewUserRealm(opAddr))\n\n\tt.Run(\"remove an unexisting validator\", func(t *testing.T) {\n\t\t// Send coins to be able to register a valoper\n\t\ttesting.SetOriginSend(chain.Coins{chain.NewCoin(\"ugnot\", registerMinFee)})\n\n\t\turequire.NotPanics(t, cur, func() {\n\t\t\tvalopers.Register(cross(cur), moniker, description, serverType, opAddr, pubKey)\n\t\t\tvalopers.UpdateKeepRunning(cross(cur), opAddr, false)\n\t\t})\n\n\t\turequire.NotPanics(t, cur, func() {\n\t\t\tvalopers.GetByAddr(opAddr)\n\t\t})\n\n\t\t// Send coins to be able to make a proposal\n\t\ttesting.SetOriginSend(chain.Coins{chain.NewCoin(\"ugnot\", proposalMinFee)})\n\n\t\turequire.AbortsWithMessage(t, cur, ErrValidatorMissing.Error(), func(cur realm) {\n\t\t\tpr := NewValidatorProposalRequest(cur, opAddr)\n\n\t\t\tdao.MustCreateProposal(cross(cur), pr)\n\t\t})\n\t})\n\n\tt.Run(\"proposal successfully created\", func(t *testing.T) {\n\t\t// Send coins to be able to register a valoper\n\t\ttesting.SetOriginSend(chain.Coins{chain.NewCoin(\"ugnot\", registerMinFee)})\n\n\t\turequire.NotPanics(t, cur, func() {\n\t\t\tvalopers.UpdateKeepRunning(cross(cur), opAddr, true)\n\t\t})\n\n\t\tvar valoper valopers.Valoper\n\n\t\turequire.NotPanics(t, cur, func() {\n\t\t\tvaloper = valopers.GetByAddr(opAddr)\n\t\t})\n\n\t\t// Send coins to be able to make a proposal\n\t\ttesting.SetOriginSend(chain.Coins{chain.NewCoin(\"ugnot\", proposalMinFee)})\n\n\t\tvar pid dao.ProposalID\n\t\turequire.NotPanics(t, cur, func(cur realm) {\n\t\t\ttesting.SetRealm(testing.NewUserRealm(g1user))\n\t\t\tpr := NewValidatorProposalRequest(cur, opAddr)\n\n\t\t\tpid = dao.MustCreateProposal(cross(cur), pr)\n\t\t})\n\n\t\tproposal, err := dao.GetProposal(pid) // index starts from 0\n\t\turequire.NoError(t, err, \"proposal not found\")\n\n\t\t// The proposal description is now operator-keyed (matches the\n\t\t// new v3.NewValidatorProposalRequest format): both the profile\n\t\t// link and the validator-updates section reference the\n\t\t// OPERATOR address with explicit power.\n\t\tdescription := ufmt.Sprintf(\n\t\t\t\"Valoper profile: [%s](/r/gnops/valopers:%s)\\n\\n%s\\n\\n## Validator Updates\\n- %s: add (power 1)\\n\",\n\t\t\tvaloper.Moniker,\n\t\t\tvaloper.OperatorAddress,\n\t\t\tvaloper.Render(),\n\t\t\tvaloper.OperatorAddress,\n\t\t)\n\n\t\t// Check that the proposal is correct\n\t\turequire.Equal(t, description, proposal.Description())\n\t})\n\n\tt.Run(\"try to update a validator with the same values\", func(t *testing.T) {\n\t\t// Send coins to be able to register a valoper\n\t\ttesting.SetOriginSend(chain.Coins{chain.NewCoin(\"ugnot\", registerMinFee)})\n\n\t\turequire.NotPanics(t, cur, func() {\n\t\t\tvalopers.GetByAddr(opAddr)\n\t\t})\n\n\t\turequire.NotPanics(t, cur, func() {\n\t\t\t// Vote the proposal created in the previous test\n\t\t\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(0)))\n\n\t\t\t// Execute the proposal — callback writes valset:proposed +\n\t\t\t// dirty=true. v3.IsValidator(signingAddr) below reads the\n\t\t\t// effective view (proposed-when-dirty) and finds the\n\t\t\t// just-added validator → enters the ErrSameValues branch.\n\t\t\tdao.ExecuteProposal(cross(cur), dao.ProposalID(0))\n\t\t})\n\n\t\t// Verify the just-added entry exists at the SIGNING address.\n\t\t_ = signingAddr\n\n\t\t// Send coins to be able to make a proposal\n\t\ttesting.SetOriginSend(chain.Coins{chain.NewCoin(\"ugnot\", proposalMinFee)})\n\n\t\turequire.AbortsWithMessage(t, cur, ErrSameValues.Error(), func() {\n\t\t\tpr := NewValidatorProposalRequest(cross(cur), opAddr)\n\t\t\tdao.MustCreateProposal(cross(cur), pr)\n\t\t})\n\t})\n}\n\nfunc TestValopers_ProposeNewInstructions(cur realm, t *testing.T) {\n\tconst proposalMinFee int64 = 100 * 1_000_000\n\n\tnewInstructions := \"new instructions\"\n\tdescription := ufmt.Sprintf(\"Update the instructions to: \\n\\n%s\", newInstructions)\n\n\t// Set origin caller\n\ttesting.SetRealm(testing.NewUserRealm(g1user))\n\n\t// Send coins to be able to make a proposal\n\ttesting.SetOriginSend(chain.Coins{chain.NewCoin(\"ugnot\", proposalMinFee)})\n\n\tvar pid dao.ProposalID\n\turequire.NotPanics(t, cur, func() {\n\t\tpr := ProposeNewInstructionsProposalRequest(cross(cur), newInstructions)\n\n\t\tpid = dao.MustCreateProposal(cross(cur), pr)\n\t})\n\n\tproposal, err := dao.GetProposal(pid) // index starts from 0\n\turequire.NoError(t, err, \"proposal not found\")\n\tif proposal == nil {\n\t\tpanic(\"PROPOSAL NOT FOUND\")\n\t}\n\n\t// Check that the proposal is correct\n\turequire.Equal(t, description, proposal.Description())\n}\n\nfunc TestValopers_ProposeNewMinFee(cur realm, t *testing.T) {\n\tconst proposalMinFee int64 = 100 * 1_000_000\n\tnewMinFee := int64(10)\n\t// ProposeNewMinFeeProposalRequest now delegates to the generic\n\t// sys/params factory; description is the standard one from\n\t// r/sys/params.newPropRequest, keyed on node:valoper:register_fee.\n\tdescription := \"This proposal wants to add a new key to sys/params: node:valoper:register_fee\"\n\n\t// Set origin caller\n\ttesting.SetRealm(testing.NewUserRealm(g1user))\n\n\t// Send coins to be able to make a proposal\n\ttesting.SetOriginSend(chain.Coins{chain.NewCoin(\"ugnot\", proposalMinFee)})\n\n\tvar pid dao.ProposalID\n\turequire.NotPanics(t, cur, func() {\n\t\tpr := ProposeNewMinFeeProposalRequest(cross(cur), newMinFee)\n\n\t\tpid = dao.MustCreateProposal(cross(cur), pr)\n\t})\n\n\tproposal, err := dao.GetProposal(pid) // index starts from 0\n\turequire.NoError(t, err, \"proposal not found\")\n\t// Check that the proposal is correct\n\turequire.Equal(t, description, proposal.Description())\n}\n\n/* TODO fix this @moul\nfunc TestValopers_ProposeNewValidator2(cur realm, t *testing.T) {\n\tconst (\n\t\tregisterMinFee int64 = 20 * 1_000_000 // minimum gnot must be paid to register.\n\t\tproposalMinFee int64 = 100 * 1_000_000\n\n\t\tmoniker     string = \"moniker\"\n\t\tdescription string = \"description\"\n\t\tpubKey             = \"gpub1pggj7ard9eg82cjtv4u52epjx56nzwgjyg9zqwpdwpd0f9fvqla089ndw5g9hcsufad77fml2vlu73fk8q8sh8v72cza5p\"\n\t)\n\n\t// Set origin caller\n\ttesting.SetRealm(std.NewUserRealm(g1user))\n\n\tt.Run(\"create valid proposal\", func(t *testing.T) {\n\t\t// Validator exists, should not panic\n\t\turequire.NotPanics(t, cur, func() {\n\t\t\t_ = valopers.MustGetValoper(g1user)\n\t\t})\n\n\t\t// Create the proposal\n\t\turequire.NotPanics(t, cur, func() {\n\t\t\tcross(valopers.Register)(moniker, description, g1user, pubKey)\n\t\t})\n\n\t\t// Verify proposal details\n\t\turequire.NotPanics(t, cur, func() {\n\t\t\tvaloper := valopers.MustGetValoper(g1user)\n\t\t\turequire.Equal(t, moniker, valoper.Moniker)\n\t\t\turequire.Equal(t, description, valoper.Description)\n\t\t})\n\t\t// Execute proposal with admin rights\n\t\turequire.NotPanics(t, cur, func() {\n\t\t\tstd.TestSetOrigCaller(std.Admin)\n\t\t\tcross(dao.ExecuteProposal)(dao.ProposalID(0))\n\t\t})\n\t\t// Check if valoper was updated\n\t\turequire.NotPanics(t, cur, func() {\n\t\t\tvaloper := valopers.MustGetValoper(g1user)\n\t\t\turequire.Equal(t, moniker, valoper.Moniker)\n\t\t\turequire.Equal(t, description, valoper.Description)\n\t\t})\n\n\t\t// Expect ExecuteProposal to pass\n\t\turequire.NotPanics(t, cur, func() {\n\t\t\tcross(dao.ExecuteProposal)(dao.ProposalID(0))\n\t\t})\n\t\t// Check if valoper was updated\n\t\turequire.NotPanics(t, cur, func() {\n\t\t\tvaloper := valopers.MustGetValoper(g1user)\n\t\t\turequire.Equal(t, moniker, valoper.Moniker)\n\t\t\turequire.Equal(t, description, valoper.Description)\n\t\t})\n\t\t// Execute proposal with admin rights\n\t\turequire.NotPanics(t, cur, func() {\n\t\t\tstd.TestSetOrigCaller(std.Admin)\n\t\t\tcross(dao.ExecuteProposal)(dao.ProposalID(0))\n\t\t})\n\t})\n}\n*/\n"},{"name":"z_0_a_filetest.gno","body":"// PKGPATH: gno.land/r/test/proposal\n// SEND: 20000000ugnot\n\npackage proposal\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/r/gnops/valopers\"\n\t\"gno.land/r/gnops/valopers/proposal\"\n\t\"gno.land/r/gov/dao\"\n\tdaoinit \"gno.land/r/gov/dao/v3/init\"\n)\n\nvar g1user = testutils.TestAddress(\"g1user\")\n\nconst (\n\tvalidMoniker     = \"test-1\"\n\tvalidDescription = \"test-1's description\"\n\tvalidServerType  = valopers.ServerTypeOnPrem\n\tvalidAddress     = address(\"g1sp8v98h2gadm5jggtzz9w5ksexqn68ympsd68h\")\n\totherAddress     = address(\"g1juz2yxmdsa6audkp6ep9vfv80c8p5u76e03vvh\")\n\tvalidPubKey      = \"gpub1pggj7ard9eg82cjtv4u52epjx56nzwgjyg9zqwpdwpd0f9fvqla089ndw5g9hcsufad77fml2vlu73fk8q8sh8v72cza5p\"\n)\n\nfunc init(cur realm) {\n\ttesting.SetOriginCaller(g1user)\n\tdaoinit.InitWithUsers(cross(cur), g1user)\n}\n\nfunc main(cur realm) {\n\t// Register a validator: OriginCaller must equal operator addr (squat guard).\n\ttesting.SetOriginCaller(validAddress)\n\tvalopers.Register(cross(cur), validMoniker, validDescription, validServerType, validAddress, validPubKey)\n\n\t// Switch back to g1user for the GovDAO proposal submission.\n\ttesting.SetOriginCaller(g1user)\n\n\t// Try to make a proposal for a non-existing validator\n\tif err := revive(func() {\n\t\tpr := proposal.NewValidatorProposalRequest(cross(cur), otherAddress)\n\t\tdao.MustCreateProposal(cross(cur), pr)\n\t}); err != nil {\n\t\tprintln(\"r: \", err)\n\t}\n}\n\n// Output:\n// r:  valoper does not exist\n"},{"name":"z_1_filetest.gno","body":"// PKGPATH: gno.land/r/test/proposal\n// SEND: 100000000ugnot\n\npackage proposal\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/r/gnops/valopers\"\n\t\"gno.land/r/gnops/valopers/proposal\"\n\t\"gno.land/r/gov/dao\"\n\tdaoinit \"gno.land/r/gov/dao/v3/init\" // so that the govdao initializer is executed\n)\n\nvar g1user = testutils.TestAddress(\"g1user\") // g1vuch2um9wf047h6lta047h6lta047h6l2ewm6w\n\nconst (\n\tvalidMoniker     = \"test-1\"\n\tvalidDescription = \"test-1's description\"\n\tvalidServerType  = valopers.ServerTypeOnPrem\n\tvalidAddress     = address(\"g1sp8v98h2gadm5jggtzz9w5ksexqn68ympsd68h\")\n\tvalidPubKey      = \"gpub1pggj7ard9eg82cjtv4u52epjx56nzwgjyg9zqwpdwpd0f9fvqla089ndw5g9hcsufad77fml2vlu73fk8q8sh8v72cza5p\"\n)\n\nfunc init(cur realm) {\n\ttesting.SetOriginCaller(g1user)\n\tdaoinit.InitWithUsers(cross(cur), g1user)\n\n\t// Register a validator: OriginCaller must equal operator addr (squat guard).\n\ttesting.SetOriginCaller(validAddress)\n\tvalopers.Register(cross(cur), validMoniker, validDescription, validServerType, validAddress, validPubKey)\n\n\t// Switch back to g1user for the GovDAO submission.\n\ttesting.SetOriginCaller(g1user)\n\n\tif err := revive(func() {\n\t\tpr := proposal.NewValidatorProposalRequest(cross(cur), validAddress)\n\t\tdao.MustCreateProposal(cross(cur), pr)\n\t}); err != nil {\n\t\tprintln(\"r: \", err)\n\t} else {\n\t\tprintln(\"OK\")\n\t}\n}\n\nfunc main(cur realm) {\n\tprintln(dao.Render(cross(cur), \"\"))\n}\n\n// Output:\n// OK\n// # GovDAO\n// ## Members\n// [\u003e Go to Memberstore \u003c](/r/gov/dao/v3/memberstore)\n// ## Proposals\n// ### [Prop #0 - Add valoper test\\-1 to the valset](/r/gov/dao:0)\n// Author: g1vuch2um9wf047h6lta047h6lta047h6l2ewm6w\n//\n// Status: ACTIVE\n//\n// Tiers eligible to vote: T1, T2, T3\n//\n// ---\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"RJ2NAQ/8z2fZz60cr7GTMV3mSDDZRN1zLo3hkFMRCghDYi46luX5wolqOcD16GswCIaT6XvdS1C84CYRKSCPUg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1g73v2anukg4ej7axwqpthsatzrxjsh0wk797da","package":{"name":"loader","path":"gno.land/r/gov/dao/v3/loader","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/gov/dao/v3/loader\"\ngno = \"0.9\"\n\n[addpkg]\n  creator = \"g1g73v2anukg4ej7axwqpthsatzrxjsh0wk797da\"\n"},{"name":"loader.gno","body":"// loader.gno initialises the govDAO v3 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/v3/impl\"\n\t\"gno.land/r/gov/dao/v3/memberstore\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"R4IT1YgsWqn/tmJPRBgV6e0loKqjsAYtiYE1ssd+8DFYvF04wdM2OL9jSCRvyt9O+TSz7avTwwoOb6ayLcuWeQ=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5","package":{"name":"test","path":"gno.land/r/gov/dao/v3/treasury/test","files":[{"name":"gnomod.toml","body":"module = \"gno.land/r/gov/dao/v3/treasury/test\"\ngno = \"0.9\"\n"},{"name":"treasury_test.gno","body":"package test\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"chain/runtime/unsafe\"\n\t\"sort\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/demo/tokens/grc20\"\n\t\"gno.land/p/nt/fqname/v0\"\n\t\"gno.land/p/nt/seqid/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\ttrs_pkg \"gno.land/p/nt/treasury/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\n\t\"gno.land/r/demo/defi/grc20reg\"\n\t\"gno.land/r/gov/dao\"\n\t\"gno.land/r/gov/dao/v3/impl\"\n\t\"gno.land/r/gov/dao/v3/treasury\"\n)\n\n// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\nvar nextTokenID seqid.ID\nvar (\n\tuser1Addr       = testutils.TestAddress(\"g1user1\")\n\tuser2Addr       = testutils.TestAddress(\"g1user2\")\n\ttreasuryAddr    = chain.PackageAddress(\"gno.land/r/gov/dao/v3/treasury\")\n\tallowedRealm    = testing.NewCodeRealm(\"gno.land/r/test/allowed\")\n\tnotAllowedRealm = testing.NewCodeRealm(\"gno.land/r/test/notallowed\")\n\tmintAmount      = int64(1000)\n)\n\n// Define a dummy trs_pkg.Payment type for testing purposes.\ntype dummyPayment struct {\n\tbankerID string\n\tstr      string\n}\n\nvar _ trs_pkg.Payment = (*dummyPayment)(nil)\n\nfunc (dp *dummyPayment) BankerID() string { return dp.bankerID }\nfunc (dp *dummyPayment) String() string   { return dp.str }\n\nfunc init(cur realm) {\n\t// Register allowed Realm path.\n\tdao.UpdateImpl(cross(cur), dao.NewUpdateRequest(impl.NewGovDAO(), []string{allowedRealm.PkgPath()}))\n}\n\nfunc ugnotCoins(t *testing.T, amount int64) chain.Coins {\n\tt.Helper()\n\n\t// Create a new coin with the ugnot denomination.\n\treturn chain.NewCoins(chain.NewCoin(\"ugnot\", amount))\n}\n\nfunc ugnotBalance(t *testing.T, addr address) int64 {\n\tt.Helper()\n\n\t// Get the balance of ugnot coins for the given address.\n\tbanker_ := banker.NewReadonlyBanker()\n\tcoins := banker_.GetCoins(addr)\n\n\treturn coins.AmountOf(\"ugnot\")\n}\n\n// Define a keyedToken type to hold the token and its key.\ntype keyedToken struct {\n\tkey   string\n\ttoken *grc20.Token\n}\n\nfunc registerGRC20Tokens(_ int, rlm realm, t *testing.T, tokenNames []string, toMint address) []keyedToken {\n\tt.Helper()\n\n\tvar (\n\t\tkeyedTokens = make([]keyedToken, 0, len(tokenNames))\n\t\tkeys        = make([]string, 0, len(tokenNames))\n\t)\n\n\tfor _, name := range tokenNames {\n\t\t// Create the token.\n\t\tsymbol := strings.ToUpper(name)\n\t\ttoken, ledger := grc20.NewToken(name, symbol, 0, nextTokenID.Next(), rlm)\n\n\t\t// Register the token.\n\t\tgrc20reg.Register(cross(rlm), token, symbol)\n\n\t\t// Mint tokens to the specified address.\n\t\tledger.Mint(toMint, mintAmount)\n\n\t\t// Add the token and key to the lists.\n\t\tkey := fqname.Construct(unsafe.CurrentRealm().PkgPath(), symbol)\n\t\tkeyedTokens = append(keyedTokens, keyedToken{key: key, token: token})\n\t\tkeys = append(keys, key)\n\t}\n\n\t// Set the token keys in the treasury.\n\ttreasury.SetTokenKeys(cross(rlm), keys)\n\n\treturn keyedTokens\n}\n\nfunc TestAllowedDAOs(cur realm, t *testing.T) {\n\t// Set the current Realm to the not allowed one.\n\ttesting.SetRealm(notAllowedRealm)\n\n\t// Define a dummy payment to test sending.\n\tdummyP := \u0026dummyPayment{bankerID: \"Dummy\"}\n\n\t// Try to send, it should abort because the Realm is not allowed.\n\tuassert.AbortsWithMessage(\n\t\tt, cur,\n\t\t\"this Realm is not allowed to send payment: \"+notAllowedRealm.PkgPath(),\n\t\tfunc() { treasury.Send(cross(cur), dummyP) },\n\t)\n\n\t// Set the current Realm to the allowed one.\n\ttesting.SetRealm(allowedRealm)\n\n\t// Try to send, it should not abort because the Realm is allowed,\n\t// but because the dummy banker ID is not registered.\n\tuassert.AbortsWithMessage(\n\t\tt, cur,\n\t\t\"banker not found: \"+dummyP.BankerID(),\n\t\tfunc() { treasury.Send(cross(cur), dummyP) },\n\t)\n}\n\nfunc TestRegisteredBankers(t *testing.T) {\n\t// Set the current Realm to the allowed one.\n\ttesting.SetRealm(allowedRealm)\n\n\t// Define the expected banker IDs.\n\texpectedBankerIDs := []string{\n\t\ttrs_pkg.CoinsBanker{}.ID(),\n\t\ttrs_pkg.GRC20Banker{}.ID(),\n\t}\n\n\t// Get the registered bankers from the treasury and compare their lengths.\n\tregistered := treasury.ListBankerIDs()\n\tuassert.Equal(t, len(registered), len(expectedBankerIDs))\n\n\t// The treasury-returned slice is foreign-readonly; copy locally\n\t// before sorting in place.\n\tregisteredBankerIDs := append([]string(nil), registered...)\n\n\t// Sort both slices then compare them.\n\tsort.StringSlice(expectedBankerIDs).Sort()\n\tsort.StringSlice(registeredBankerIDs).Sort()\n\n\tfor i := range expectedBankerIDs {\n\t\tuassert.Equal(t, expectedBankerIDs[i], registeredBankerIDs[i])\n\t}\n\n\t// Test HasBanker method.\n\tfor _, bankerID := range expectedBankerIDs {\n\t\tuassert.True(t, treasury.HasBanker(bankerID))\n\t}\n\tuassert.False(t, treasury.HasBanker(\"UnknownBankerID\"))\n\n\t// Test Address method.\n\tfor _, bankerID := range expectedBankerIDs {\n\t\t// The two bankers used for now should have the treasury Realm address.\n\t\tuassert.Equal(t, treasury.Address(bankerID), treasuryAddr.String())\n\t}\n}\n\nfunc TestSendGRC20Payment(cur realm, t *testing.T) {\n\t// Set the current Realm to the allowed one.\n\ttesting.SetRealm(allowedRealm)\n\n\t// Try to send a GRC20 payment with a not registered token, it should abort.\n\tuassert.AbortsWithMessage(\n\t\tt, cur,\n\t\t\"failed to send payment: GRC20 token not found: UNKNOW\",\n\t\tfunc() {\n\t\t\ttreasury.Send(cross(cur), trs_pkg.NewGRC20Payment(\"UNKNOW\", 100, user1Addr))\n\t\t},\n\t)\n\n\t// Create 3 GRC20 tokens and register them.\n\tkeyedTokens := registerGRC20Tokens(\n\t\t0, cur,\n\t\tt,\n\t\t[]string{\"TestToken0\", \"TestToken1\", \"TestToken2\"},\n\t\ttreasuryAddr,\n\t)\n\n\tconst txAmount = 42\n\n\t// For each token-user pair.\n\tfor i, userAddr := range []address{user1Addr, user2Addr} {\n\t\tfor _, keyed := range keyedTokens {\n\t\t\t// Check that the treasury has the expected balance before sending.\n\t\t\tuassert.Equal(t, keyed.token.BalanceOf(treasuryAddr), mintAmount-int64(txAmount*i))\n\n\t\t\t// Check that the user has no balance before sending.\n\t\t\tuassert.Equal(t, keyed.token.BalanceOf(userAddr), int64(0))\n\n\t\t\t// Try to send a GRC20 payment with a registered token, it should not abort.\n\t\t\tuassert.NotAborts(t, cur, func() {\n\t\t\t\ttreasury.Send(\n\t\t\t\t\tcross(cur),\n\t\t\t\t\ttrs_pkg.NewGRC20Payment(\n\t\t\t\t\t\tkeyed.key,\n\t\t\t\t\t\ttxAmount,\n\t\t\t\t\t\tuserAddr,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t})\n\n\t\t\t// Check that the user has the expected balance after sending.\n\t\t\tuassert.Equal(t, keyed.token.BalanceOf(userAddr), int64(txAmount))\n\n\t\t\t// Check that the treasury has the expected balance after sending.\n\t\t\tuassert.Equal(t, keyed.token.BalanceOf(treasuryAddr), mintAmount-int64(txAmount*(i+1)))\n\t\t}\n\t}\n\n\t// Get the GRC20Banker ID.\n\tgrc20BankerID := trs_pkg.GRC20Banker{}.ID()\n\n\t// Test Balances method for the GRC20Banker.\n\tbalances := treasury.Balances(grc20BankerID)\n\tuassert.Equal(t, len(balances), len(keyedTokens))\n\n\tcompared := 0\n\tfor _, balance := range balances {\n\t\tfor _, keyed := range keyedTokens {\n\t\t\tif balance.Denom == keyed.key {\n\t\t\t\tuassert.Equal(t, balance.Amount, keyed.token.BalanceOf(treasuryAddr))\n\t\t\t\tcompared++\n\t\t\t}\n\t\t}\n\t}\n\tuassert.Equal(t, compared, len(keyedTokens))\n\n\t// Check the history of the GRC20Banker.\n\thistory := treasury.History(grc20BankerID, 1, 10)\n\tuassert.Equal(t, len(history), 6)\n\n\t// Try to send a dummy payment with the GRC20 banker ID, it should abort.\n\tuassert.AbortsWithMessage(\n\t\tt, cur,\n\t\t\"failed to send payment: invalid payment type\",\n\t\tfunc() {\n\t\t\ttreasury.Send(cross(cur), \u0026dummyPayment{bankerID: grc20BankerID})\n\t\t},\n\t)\n\n\t// Try to send a GRC20 payment without enough balance, it should abort.\n\tuassert.AbortsWithMessage(\n\t\tt, cur,\n\t\t\"failed to send payment: insufficient balance\",\n\t\tfunc() {\n\t\t\ttreasury.Send(\n\t\t\t\tcross(cur),\n\t\t\t\ttrs_pkg.NewGRC20Payment(\n\t\t\t\t\tkeyedTokens[0].key,\n\t\t\t\t\tmintAmount*42, // Try to send more than the treasury has.\n\t\t\t\t\tuser1Addr,\n\t\t\t\t),\n\t\t\t)\n\t\t},\n\t)\n\n\t// Check the history of the GRC20Banker.\n\thistory = treasury.History(grc20BankerID, 1, 10)\n\tuassert.Equal(t, len(history), 6)\n}\n\nfunc TestSendCoinPayment(cur realm, t *testing.T) {\n\t// Set the current Realm to the allowed one.\n\ttesting.SetRealm(allowedRealm)\n\n\t// Issue initial ugnot coins to the treasury address.\n\ttesting.IssueCoins(treasuryAddr, ugnotCoins(t, mintAmount))\n\n\t// Get the CoinsBanker ID.\n\tbankerID := trs_pkg.CoinsBanker{}.ID()\n\n\t// Define helper function to check balances and history.\n\tvar (\n\t\texpectedTreasuryBalance = mintAmount\n\t\texpectedUser1Balance    = int64(0)\n\t\texpectedUser2Balance    = int64(0)\n\t\texpectedHistoryLen      = 0\n\t\tcheckHistoryAndBalances = func() {\n\t\t\tt.Helper()\n\n\t\t\tuassert.Equal(t, ugnotBalance(t, treasuryAddr), expectedTreasuryBalance)\n\t\t\tuassert.Equal(t, ugnotBalance(t, user1Addr), expectedUser1Balance)\n\t\t\tuassert.Equal(t, ugnotBalance(t, user2Addr), expectedUser2Balance)\n\n\t\t\t// Check treasury.Balances returned value.\n\t\t\tbalances := treasury.Balances(bankerID)\n\t\t\tuassert.Equal(t, len(balances), 1)\n\t\t\tuassert.Equal(t, balances[0].Denom, \"ugnot\")\n\t\t\tuassert.Equal(t, balances[0].Amount, expectedTreasuryBalance)\n\n\t\t\t// Check treasury.History returned value.\n\t\t\thistory := treasury.History(bankerID, 1, expectedHistoryLen+1)\n\t\t\tuassert.Equal(t, len(history), expectedHistoryLen)\n\t\t}\n\t)\n\n\t// Check initial balances and history.\n\tcheckHistoryAndBalances()\n\n\tconst txAmount = int64(42)\n\n\t// Treasury send coins.\n\tfor i := int64(0); i \u003c 3; i++ {\n\t\t// Send ugnot coins to user1 and user2.\n\t\tuassert.NotAborts(t, cur, func() {\n\t\t\ttreasury.Send(\n\t\t\t\tcross(cur),\n\t\t\t\ttrs_pkg.NewCoinsPayment(ugnotCoins(t, txAmount), user1Addr),\n\t\t\t)\n\t\t\ttreasury.Send(\n\t\t\t\tcross(cur),\n\t\t\t\ttrs_pkg.NewCoinsPayment(ugnotCoins(t, txAmount), user2Addr),\n\t\t\t)\n\t\t})\n\n\t\t// Update expected balances and history length.\n\t\texpectedTreasuryBalance = mintAmount - txAmount*2*(i+1)\n\t\texpectedUser1Balance = txAmount * (i + 1)\n\t\texpectedUser2Balance = expectedUser1Balance\n\t\texpectedHistoryLen = int(2 * (i + 1))\n\n\t\t// Check balances and history after sending.\n\t\tcheckHistoryAndBalances()\n\t}\n}\n\n// The allowlist is the only thing standing between an arbitrary realm and the\n// treasury: treasury.Send and treasury.SetTokenKeys gate on\n// dao.InAllowedDAOs, and that helper returns true for EVERY caller while the\n// list is empty (the genesis bootstrap window). UpdateImpl used to store an\n// empty list, so a single implementation-only upgrade — dao.UpdateImpl with\n// NewUpdateRequest(d, nil), which copies nil into a non-nil empty slice —\n// silently reopened that window and handed the treasury to the whole chain.\n//\n// TestAllowedDAOs above proves the gate rejects an outsider in the normal\n// state. This proves the gate cannot be switched off, which is the property\n// that actually protects the funds.\nfunc TestTreasuryLockdownCannotBeReopened(cur realm, t *testing.T) {\n\tsavedDAOs := dao.AllowedDAOs()\n\n\t// An allowlisted realm attempts the reopen. NewUpdateRequest(d, nil) is the\n\t// production spelling — it copies nil into a non-nil empty slice, which is\n\t// exactly what the old `!= nil` test accepted. (A bare UpdateRequest struct\n\t// literal cannot be built here: allocating another realm's struct type from\n\t// this realm is rejected by the VM. That path is covered by\n\t// r/gov/dao/allowlist_test.gno, which lives in the same package.)\n\ttesting.SetRealm(allowedRealm)\n\tdao.UpdateImpl(cross(cur), dao.NewUpdateRequest(nil, nil))\n\n\t// The outsider must still be refused at the treasury. Reaching\n\t// \"banker not found\" would mean authorization had been cleared — that\n\t// error comes from AFTER the InAllowedDAOs check.\n\ttesting.SetRealm(notAllowedRealm)\n\tdummyP := \u0026dummyPayment{bankerID: \"Dummy\"}\n\n\tuassert.AbortsWithMessage(\n\t\tt, cur,\n\t\t\"this Realm is not allowed to send payment: \"+notAllowedRealm.PkgPath(),\n\t\tfunc() { treasury.Send(cross(cur), dummyP) },\n\t)\n\n\t// SetTokenKeys reuses Send's message verbatim (\"...to send payment...\")\n\t// rather than naming its own operation — a copy-paste slip in\n\t// treasury.gno:65, asserted here as-is. Worth correcting separately; it is\n\t// operator-visible text, not a security property, so it is not changed as\n\t// part of this fix.\n\tuassert.AbortsWithMessage(\n\t\tt, cur,\n\t\t\"this Realm is not allowed to send payment: \"+notAllowedRealm.PkgPath(),\n\t\tfunc() { treasury.SetTokenKeys(cross(cur), []string{\"evil/key\"}) },\n\t)\n\n\t// Restore explicitly rather than via defer: the assertions above leave the\n\t// current realm set to notAllowedRealm, and a deferred UpdateImpl would run\n\t// under it and be refused. uassert.AbortsWithMessage recovers the abort, so\n\t// control always reaches here.\n\ttesting.SetRealm(allowedRealm)\n\tdao.UpdateImpl(cross(cur), dao.NewUpdateRequest(nil, savedDAOs))\n\tuassert.True(t, dao.InAllowedDAOs(allowedRealm.PkgPath()), \"allowlist restored\")\n}\n\nfunc TestRenderEscapesUnknownBankerID(t *testing.T) {\n\t// The {banker} route reflects an unknown banker id into the page; a crafted\n\t// id must be escaped so it cannot inject markdown/HTML.\n\tout := treasury.Render(\"evil[x](y)\")\n\tuassert.True(t, strings.Contains(out, `\\[x\\]`), \"reflected banker id must be escaped\")\n\tuassert.False(t, strings.Contains(out, \"[x](y)\"), \"must not render a live link\")\n}\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"HkC+WwCjoz4lMH7R7IzASqS251cYluoaQWac7oxWjWl1dOW+TlRdLtaoc3W9Y1Z12cSKixbvtYLn38eGtxuWzg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g15ge0ae9077eh40erwrn2eq0xw6wupwqthpv34l","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\"\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\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\", // @devx\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\"\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_bylaws_test.gno","body":"package commondao\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/bylaws/v0\"\n\t\"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nvar (\n\t_ commondao.ProposalDefinition = amendBylawsProposal{}\n\t_ commondao.Validable          = amendBylawsProposal{}\n\t_ commondao.Executable         = amendBylawsProposal{}\n\t_ trustedMarkdownBody          = amendBylawsProposal{}\n)\n\n// TestAmendBylawsKindNew pins the amend-bylaws factory: args validation,\n// the host-identity pin, the stale-at-create fail-fast, the no-op reject,\n// and the malformed-script reject. Without this, removing any of those\n// guards is invisible to the suite.\nfunc TestAmendBylawsKindNew(t *testing.T) {\n\tdao := newTestDAO(t, \"BylawsHost\")\n\tother := newTestDAO(t, \"BylawsOther\")\n\tset := bylawsOf(dao.ID())\n\n\t// Wrong args type is a realm bug, reported as invalid args.\n\t_, err := amendBylawsKind{}.New(dao.Readonly(), textArgs{})\n\tuassert.ErrorIs(t, err, errInvalidProposalArgs)\n\n\t// A nil document set is a realm bug too.\n\tfreshPatch := func(text string) bylaws.Patch {\n\t\tt.Helper()\n\t\tp, err := set.Diff(\"bylaws/a.md\", text)\n\t\turequire.NoError(t, err)\n\t\treturn p\n\t}\n\t_, err = amendBylawsKind{}.New(dao.Readonly(), amendBylawsProposal{daoID: dao.ID(), patch: freshPatch(\"one\")})\n\tuassert.ErrorIs(t, err, errInvalidProposalArgs)\n\n\t// Host-identity pin: a set/daoID for a different DAO than the one being\n\t// proposed on is rejected.\n\t_, err = amendBylawsKind{}.New(other.Readonly(), amendBylawsProposal{daoID: dao.ID(), set: set, patch: freshPatch(\"one\")})\n\tuassert.ErrorIs(t, err, errInvalidProposalArgs)\n\n\t// Set-identity pin: the args-captured set must be the host's canonical\n\t// set — a matching daoID with a different DAO's set is rejected, so a\n\t// wrapper can never validate one DAO's documents and amend another's.\n\totherSet := bylawsOf(other.ID())\n\t_, err = amendBylawsKind{}.New(dao.Readonly(), amendBylawsProposal{daoID: dao.ID(), set: otherSet, patch: freshPatch(\"one\")})\n\tuassert.ErrorIs(t, err, errInvalidProposalArgs)\n\n\t// Invalid document paths fail fast at creation.\n\tbadPath := bylaws.Patch{Path: \"bad path\", Base: \"\", Ops: []bylaws.Op{{Type: bylaws.OpInsert, Text: \"x\"}}}\n\t_, err = amendBylawsKind{}.New(dao.Readonly(), amendBylawsProposal{daoID: dao.ID(), set: set, patch: badPath})\n\tuassert.ErrorIs(t, err, bylaws.ErrInvalidPath)\n\n\t// The mandates/ folder is reserved: mandates are set at creation or by\n\t// an ancestor, never by the council's own amendment power.\n\tmandate, err := bylaws.DiffTexts(\"mandates/spend.md\", \"\", \"Spend only by vote.\", false)\n\turequire.NoError(t, err)\n\t_, err = amendBylawsKind{}.New(dao.Readonly(), amendBylawsProposal{daoID: dao.ID(), set: set, patch: mandate})\n\turequire.Error(t, err)\n\tuassert.True(t, strings.Contains(err.Error(), \"mandates are not council-amendable\"), \"expect the mandates reservation\")\n\tbare, err := bylaws.DiffTexts(\"mandates\", \"\", \"x\", false)\n\turequire.NoError(t, err)\n\t_, err = amendBylawsKind{}.New(dao.Readonly(), amendBylawsProposal{daoID: dao.ID(), set: set, patch: bare})\n\turequire.Error(t, err)\n\tuassert.True(t, strings.Contains(err.Error(), \"mandates are not council-amendable\"), \"expect the bare-path reservation\")\n\n\t// Stale-at-create: a patch whose base does not match the current\n\t// document is rejected up front.\n\tstale := bylaws.Patch{Path: \"bylaws/a.md\", Base: bylaws.HashText(\"not the base\"), Ops: []bylaws.Op{{Type: bylaws.OpInsert, Text: \"x\"}}}\n\t_, err = amendBylawsKind{}.New(dao.Readonly(), amendBylawsProposal{daoID: dao.ID(), set: set, patch: stale})\n\tuassert.ErrorIs(t, err, bylaws.ErrStalePatch)\n\n\t// No-op amendments are rejected: a council vote is always about an\n\t// actual change.\n\tnoop, err := bylaws.DiffTexts(\"bylaws/a.md\", \"\", \"\", false)\n\turequire.NoError(t, err)\n\t_, err = amendBylawsKind{}.New(dao.Readonly(), amendBylawsProposal{daoID: dao.ID(), set: set, patch: noop})\n\turequire.Error(t, err)\n\tuassert.Equal(t, \"bylaws amendment must change the document\", err.Error())\n\n\t// A fresh-base patch with a script that does not fit the document is\n\t// rejected (Format validates the script while rendering the display).\n\t// The op must not be Keep-only, or the no-op check fires first.\n\tbroken := bylaws.Patch{Path: \"bylaws/a.md\", Base: \"\", Ops: []bylaws.Op{{Type: bylaws.OpDelete, N: 5}}}\n\t_, err = amendBylawsKind{}.New(dao.Readonly(), amendBylawsProposal{daoID: dao.ID(), set: set, patch: broken})\n\tuassert.ErrorIs(t, err, bylaws.ErrInvalidPatch)\n\n\t// Happy path: the definition renders the change, titles by action, and\n\t// applies the supermajority default threshold.\n\tdef, err := amendBylawsKind{}.New(dao.Readonly(), amendBylawsProposal{daoID: dao.ID(), set: set, patch: freshPatch(\"Quorum is half.\")})\n\turequire.NoError(t, err)\n\tabp, ok := def.(amendBylawsProposal)\n\turequire.True(t, ok, \"expect an amendBylawsProposal\")\n\tuassert.Equal(t, \"Add Bylaws Document: bylaws/a.md\", abp.Title())\n\tuassert.True(t, strings.Contains(abp.Body(), \"Quorum is half.\"), \"expect body to show the inserted text\")\n\tuassert.True(t, strings.Contains(abp.Body(), \"bylaws/a\\\\.md\"), \"expect the path escaped in the body\")\n\tuassert.True(t, abp.Threshold() == commondao.ThresholdSupermajority, \"expect the supermajority default\")\n\turequire.True(t, abp.Executor() != nil, \"expect a non-nil executor\")\n}\n\n// TestAmendBylawsIsolation pins that amendments are keyed per DAO: two\n// DAOs hold the same path independently and amending one never touches\n// the other.\nfunc TestAmendBylawsIsolation(t *testing.T) {\n\tdao1 := newTestDAO(t, \"IsoOne\")\n\tdao2 := newTestDAO(t, \"IsoTwo\")\n\tset1, set2 := bylawsOf(dao1.ID()), bylawsOf(dao2.ID())\n\n\tp1, err := set1.Diff(\"bylaws/x.md\", \"text one\")\n\turequire.NoError(t, err)\n\turequire.NoError(t, set1.Apply(p1))\n\n\tp2, err := set2.Diff(\"bylaws/x.md\", \"text two\")\n\turequire.NoError(t, err)\n\turequire.NoError(t, set2.Apply(p2))\n\n\tt1, _ := set1.Get(\"bylaws/x.md\")\n\tt2, _ := set2.Get(\"bylaws/x.md\")\n\tuassert.Equal(t, \"text one\", t1)\n\tuassert.Equal(t, \"text two\", t2)\n\n\t// Amend one; the other is untouched.\n\tp1b, err := set1.Diff(\"bylaws/x.md\", \"\")\n\turequire.NoError(t, err)\n\turequire.NoError(t, set1.Apply(p1b))\n\tuassert.False(t, set1.Has(\"bylaws/x.md\"))\n\tt2, _ = set2.Get(\"bylaws/x.md\")\n\tuassert.Equal(t, \"text two\", t2)\n}\n\n// TestAmendBylawsLifecycle pins the executor and the stale re-check: the\n// definition applies its patch on execution, and a competing amendment\n// that lost the race fails cleanly without clobbering.\nfunc TestAmendBylawsLifecycle(t *testing.T) {\n\tdao := newTestDAO(t, \"BylawsLifecycle\")\n\tset := bylawsOf(dao.ID())\n\n\tnewDef := func(text string) amendBylawsProposal {\n\t\tt.Helper()\n\t\tp, err := set.Diff(\"bylaws/spend.md\", text)\n\t\turequire.NoError(t, err)\n\t\tdef, err := amendBylawsKind{}.New(dao.Readonly(), amendBylawsProposal{daoID: dao.ID(), set: set, patch: p})\n\t\turequire.NoError(t, err)\n\t\treturn def.(amendBylawsProposal)\n\t}\n\n\t// Create the document through the executor.\n\tcreate := newDef(\"Spend only by vote.\")\n\tuassert.NoError(t, create.Validate())\n\turequire.NoError(t, create.execute(0, nil))\n\ttext, _ := set.Get(\"bylaws/spend.md\")\n\tuassert.Equal(t, \"Spend only by vote.\", text)\n\n\t// Two amendments race from the same base: the first applies, the\n\t// second is stale at Validate AND at execute, and clobbers nothing.\n\twinner := newDef(\"Spend only by supermajority vote.\")\n\tloser := newDef(\"Spend freely.\")\n\turequire.NoError(t, winner.execute(0, nil))\n\tuassert.ErrorIs(t, loser.Validate(), bylaws.ErrStalePatch)\n\tuassert.ErrorIs(t, loser.execute(0, nil), bylaws.ErrStalePatch)\n\ttext, _ = set.Get(\"bylaws/spend.md\")\n\tuassert.Equal(t, \"Spend only by supermajority vote.\", text)\n\n\t// Removal: an empty proposed text removes the document.\n\tremove := newDef(\"\")\n\tuassert.Equal(t, \"Remove Bylaws Document: bylaws/spend.md\", remove.Title())\n\turequire.NoError(t, remove.execute(0, nil))\n\tuassert.False(t, set.Has(\"bylaws/spend.md\"))\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\"\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_council_test.gno","body":"package commondao\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nvar (\n\t_ commondao.ProposalDefinition = (*councilUpdatePropDefinition)(nil)\n\t_ commondao.CapExempt          = (*councilUpdatePropDefinition)(nil)\n)\n\nfunc TestCouncilUpdatePropDefinitionNew(cur realm, t *testing.T) {\n\tvar member address = \"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\"\n\n\tdao := commondao.New(commondao.WithCouncilMember(member))\n\n\turequire.PanicsWithMessage(t, cur, \"DAO is required\", func() {\n\t\tnewCouncilUpdatePropDefinition(nil, nil, nil)\n\t})\n\n\turequire.PanicsWithMessage(t, cur, \"no council members were specified to be added or removed\", func() {\n\t\tnewCouncilUpdatePropDefinition(dao, nil, nil)\n\t})\n\n\tdef := newCouncilUpdatePropDefinition(dao, []address{member}, nil)\n\n\tuassert.Equal(t, \"Council Update\", def.Title())\n\tuassert.Equal(t, int(commondao.ThresholdSupermajority), int(def.Threshold()))\n\tuassert.NotEmpty(t, def.Body())\n}\n\nfunc TestCouncilUpdatePropDefinitionValidate(t *testing.T) {\n\tvar (\n\t\tmemberA address = \"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\"\n\t\tmemberB address = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n\t)\n\n\tdao := commondao.New(commondao.WithCouncilMember(memberA))\n\n\t// Membership is not validated: adding an existing member or removing a\n\t// stranger is legal (idempotent set semantics)\n\tdef := newCouncilUpdatePropDefinition(dao, []address{memberA}, []address{memberB})\n\tuassert.NoError(t, def.Validate())\n\n\t// Adding and removing the same address is rejected\n\tdef = newCouncilUpdatePropDefinition(dao, []address{memberB}, []address{memberB})\n\tuassert.ErrorContains(t, def.Validate(), \"address is added and removed at once\")\n}\n\nfunc TestCouncilUpdatePropDefinitionExecute(cur realm, t *testing.T) {\n\tvar (\n\t\tmemberA address = \"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\"\n\t\tmemberB address = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n\t)\n\n\tt.Run(\"add and remove\", func(t *testing.T) {\n\t\tdao := commondao.New(commondao.WithCouncilMember(memberA))\n\n\t\tdef := newCouncilUpdatePropDefinition(dao, []address{memberB}, []address{memberA})\n\n\t\turequire.NotPanics(t, cur, func() {\n\t\t\tif err := def.Executor()(0, cur); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t})\n\t\tuassert.True(t, dao.Council().Has(memberB))\n\t\tuassert.False(t, dao.Council().Has(memberA))\n\t\tuassert.Equal(t, 1, dao.Council().Size())\n\t})\n\n\tt.Run(\"emptying the council fails\", func(t *testing.T) {\n\t\tdao := commondao.New(commondao.WithCouncilMember(memberA))\n\n\t\tdef := newCouncilUpdatePropDefinition(dao, nil, []address{memberA})\n\n\t\terr := def.execute(0, cur)\n\t\tuassert.ErrorIs(t, err, commondao.ErrEmptyCouncil)\n\t\tuassert.Equal(t, 1, dao.Council().Size())\n\t})\n}\n\nfunc TestAncestorCouncilUpdatePropDefinition(cur realm, t *testing.T) {\n\tvar member address = \"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\"\n\n\troot := commondao.New(commondao.WithID(201), commondao.WithName(\"Root\"))\n\tmid := commondao.New(commondao.WithID(202), commondao.WithName(\"Mid\"), commondao.WithParent(root))\n\tleaf := commondao.New(commondao.WithID(203), commondao.WithName(\"Leaf\"), commondao.WithParent(mid), commondao.WithCouncilMember(member))\n\n\turequire.PanicsWithMessage(t, cur, \"DAO is required\", func() {\n\t\tnewAncestorCouncilUpdatePropDefinition(nil, leaf, []address{member}, nil)\n\t})\n\turequire.PanicsWithMessage(t, cur, \"target DAO is required\", func() {\n\t\tnewAncestorCouncilUpdatePropDefinition(root, nil, []address{member}, nil)\n\t})\n\turequire.PanicsWithMessage(t, cur, \"no council members were specified to be added or removed\", func() {\n\t\tnewAncestorCouncilUpdatePropDefinition(root, leaf, nil, nil)\n\t})\n\n\tdef := newAncestorCouncilUpdatePropDefinition(root, leaf, []address{member}, nil)\n\tuassert.Equal(t, \"Ancestor Council Update\", def.Title())\n\tuassert.Equal(t, int(commondao.ThresholdSupermajority), int(def.Threshold()))\n\tuassert.NotEmpty(t, def.Body())\n\n\t// Any proper ancestor qualifies (parent or grandparent); self and\n\t// descendants do not.\n\tuassert.NoError(t, newAncestorCouncilUpdatePropDefinition(root, leaf, []address{member}, nil).Validate())\n\tuassert.NoError(t, newAncestorCouncilUpdatePropDefinition(mid, leaf, []address{member}, nil).Validate())\n\tuassert.ErrorContains(t,\n\t\tnewAncestorCouncilUpdatePropDefinition(leaf, leaf, []address{member}, nil).Validate(),\n\t\t\"a DAO cannot target itself\")\n\tuassert.ErrorContains(t,\n\t\tnewAncestorCouncilUpdatePropDefinition(leaf, root, []address{member}, nil).Validate(),\n\t\t\"DAO is not an ancestor of the target DAO\")\n\n\t// A contradictory same-address add+remove is rejected.\n\tuassert.ErrorContains(t,\n\t\tnewAncestorCouncilUpdatePropDefinition(root, leaf, []address{member}, []address{member}).Validate(),\n\t\t\"is added and removed at once\")\n\n\t// The executor mutates the target's council.\n\tvar newMember address = \"g1manfred47kzduec920z88wfr64ylksmdcedlf5\"\n\turequire.NoError(t, newAncestorCouncilUpdatePropDefinition(root, leaf, []address{newMember}, []address{member}).Executor()(0, cur))\n\tuassert.True(t, leaf.Council().Has(newMember))\n\tuassert.False(t, leaf.Council().Has(member))\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\"\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_kinds_test.gno","body":"package commondao\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nvar (\n\t_ commondao.ProposalDefinition = manageKindsProposal{}\n\t_ commondao.Validable          = manageKindsProposal{}\n\t_ commondao.Executable         = manageKindsProposal{}\n)\n\nfunc TestManageKindsKindNew(t *testing.T) {\n\t// The test DAO registers the default kinds; deregister the text kind so\n\t// the table has an absent catalog kind to register and to reject\n\t// deregistering.\n\tdao := newTestDAO(t, \"KindsHost\")\n\turequire.NoError(t, dao.DeregisterKind(kindText))\n\n\tcases := []struct {\n\t\tname string\n\t\targs manageKindsProposal\n\t\terr  string\n\t}{\n\t\t// Register by name.\n\t\t{\"register unknown kind\", manageKindsProposal{dao: dao, name: \"unknown\"}, \"unknown proposal kind\"},\n\t\t{\"register a registered kind\", manageKindsProposal{dao: dao, name: kindCouncilUpdate}, \"proposal kind is already registered\"},\n\t\t{\"register a catalog kind\", manageKindsProposal{dao: dao, name: kindText}, \"\"},\n\t\t{\"register the opt-in execution kind\", manageKindsProposal{dao: dao, name: kindExecution}, \"\"},\n\t\t// Deregister by name.\n\t\t{\"deregister an absent kind\", manageKindsProposal{dao: dao, remove: true, name: kindText}, \"proposal kind is not registered: \" + kindText},\n\t\t{\"deregister the manage-kinds kind\", manageKindsProposal{dao: dao, remove: true, name: kindManageKinds}, \"the manage-kinds kind cannot be deregistered\"},\n\t\t{\"deregister a registered kind\", manageKindsProposal{dao: dao, remove: true, name: kindCouncilUpdate}, \"\"},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tdef, err := manageKindsKind{}.New(dao.Readonly(), tc.args)\n\n\t\t\tif tc.err != \"\" {\n\t\t\t\turequire.Error(t, err)\n\t\t\t\tuassert.Equal(t, tc.err, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turequire.NoError(t, err)\n\t\t\t// New returns the args value unchanged as the definition (the\n\t\t\t// collapsed args/definition type): the two must be equal.\n\t\t\td, ok := def.(manageKindsProposal)\n\t\t\turequire.True(t, ok, \"expect a manageKindsProposal\")\n\t\t\tuassert.True(t, d.dao == dao, \"expect the definition to keep the host DAO\")\n\t\t\tuassert.Equal(t, tc.args.remove, d.remove)\n\t\t\tuassert.Equal(t, tc.args.name, d.name)\n\t\t})\n\t}\n}\n\n// TestExecutionKindNew pins the realm execution kind's factory: args\n// validation, the nil-closure guard, and the Validable freeze policy that\n// blocks execution while the host treasury is frozen. Without this, removing\n// the nil-fn check or the freeze read from executionKind is invisible to the\n// suite (no filetest constructs the kind directly).\nfunc TestExecutionKindNew(t *testing.T) {\n\tdao := newTestDAO(t, \"ExecHost\")\n\tfn := commondao.ExecFunc(func(_ int, _ realm) error { return nil })\n\n\t// Wrong args type is a realm bug, reported as invalid args.\n\t_, err := executionKind{}.New(dao.Readonly(), textArgs{})\n\tuassert.ErrorIs(t, err, errInvalidProposalArgs)\n\n\t// A nil closure is rejected with the /p/ sentinel.\n\t_, err = executionKind{}.New(dao.Readonly(), executionArgs{title: \"T\", body: \"B\", fn: nil})\n\tuassert.ErrorIs(t, err, commondao.ErrExecutionFuncRequired)\n\n\t// Happy path: the definition carries the title, body and closure and\n\t// defaults to a supermajority threshold.\n\tdef, err := executionKind{}.New(dao.Readonly(), executionArgs{title: \"T\", body: \"B\", fn: fn})\n\turequire.NoError(t, err)\n\tepd, ok := def.(executionPropDefinition)\n\turequire.True(t, ok, \"expect an executionPropDefinition\")\n\tuassert.Equal(t, \"T\", epd.Title())\n\t// The body is self-assembled: the realm's arbitrary-code disclosure\n\t// followed by the proposer's (escaped) description.\n\tuassert.True(t, strings.Contains(epd.Body(), \"runs arbitrary code with the DAO's own authority\"),\n\t\t\"expect the arbitrary-code disclosure\")\n\tuassert.True(t, strings.Contains(epd.Body(), \"B\"), \"expect the proposer description\")\n\tuassert.True(t, epd.Threshold() == commondao.ThresholdSupermajority)\n\turequire.True(t, epd.Executor() != nil, \"expect a non-nil executor\")\n\n\t// Freeze policy: Validate passes while unfrozen and blocks once the host\n\t// treasury is frozen (the definition holds the live readonly host view).\n\tuassert.NoError(t, epd.Validate())\n\tdao.SetTreasuryFrozen(true)\n\tuassert.ErrorIs(t, epd.Validate(), errTreasuryFrozen)\n}\n\n// TestManageKindsKindNewHostPin pins the manage-kinds host-identity guard:\n// the kind captures a mutable host handle from args but validates against the\n// readonly host Propose passes, so a handle for a different DAO than the one\n// being proposed on is rejected — a wrapper can never validate one registry\n// and mutate another.\nfunc TestManageKindsKindNewHostPin(t *testing.T) {\n\thost := newTestDAO(t, \"PinHost\")\n\tother := newTestDAO(t, \"PinOther\")\n\n\t_, err := manageKindsKind{}.New(host.Readonly(), manageKindsProposal{dao: other, name: kindText})\n\tuassert.ErrorIs(t, err, errInvalidProposalArgs)\n\n\t// Matching handles pass the pin and then the normal register/deregister\n\t// checks (deregistering a registered default validates cleanly).\n\t_, err = manageKindsKind{}.New(host.Readonly(), manageKindsProposal{dao: host, remove: true, name: kindText})\n\tuassert.NoError(t, err)\n}\n\n// TestManageKindsValidateSelfBrick pins the second (Execute-time) self-brick\n// layer: Validate rejects deregistering the manage-kinds kind even though\n// the /p/ package no longer locks any name. Validate reruns inside Execute.\nfunc TestManageKindsValidateSelfBrick(t *testing.T) {\n\tdao := newTestDAO(t, \"ValidateHost\")\n\n\t// A manage-kinds deregister slips past New (constructed directly here);\n\t// Validate is the backstop that still rejects it.\n\tbrick := manageKindsProposal{dao: dao, remove: true, name: kindManageKinds}\n\terr := brick.Validate()\n\turequire.Error(t, err)\n\tuassert.Equal(t, \"the manage-kinds kind cannot be deregistered\", err.Error())\n\n\t// Deregistering any other kind validates cleanly.\n\tok := manageKindsProposal{dao: dao, remove: true, name: kindText}\n\tuassert.NoError(t, ok.Validate())\n\n\t// A register never trips the self-brick regardless of name.\n\treg := manageKindsProposal{dao: dao, name: kindManageKinds}\n\tuassert.NoError(t, reg.Validate())\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\"\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_subdao_test.gno","body":"package commondao\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nvar (\n\t_ commondao.ProposalDefinition = (*subDAOPropDefinition)(nil)\n\t_ commondao.ProposalDefinition = (*dissolvePropDefinition)(nil)\n)\n\n// newTestDAO registers a DAO in the realm state so definitions that read\n// realm options can be tested.\nfunc newTestDAO(t *testing.T, name string, members ...address) *commondao.CommonDAO {\n\tt.Helper()\n\n\tid := daoID.Next()\n\topts := []commondao.Option{\n\t\tcommondao.WithID(uint64(id)),\n\t\tcommondao.WithName(name),\n\t}\n\tfor _, m := range members {\n\t\topts = append(opts, commondao.WithCouncilMember(m))\n\t}\n\tfor _, k := range defaultProposalKinds {\n\t\topts = append(opts, commondao.WithProposalKind(k))\n\t}\n\n\tdao := commondao.New(opts...)\n\tdaos.Set(id.String(), dao)\n\treturn dao\n}\n\nfunc TestSubDAOPropDefinitionNew(cur realm, t *testing.T) {\n\tvar member address = \"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\"\n\n\tdao := newTestDAO(t, \"Root\", member)\n\n\turequire.PanicsWithMessage(t, cur, \"parent DAO is required\", func() {\n\t\tnewSubDAOPropDefinition(nil, \"Sub\", \"Purpose\", \"\", []address{member})\n\t})\n\n\turequire.PanicsWithMessage(t, cur, \"DAO name is empty\", func() {\n\t\tnewSubDAOPropDefinition(dao, \"  \", \"Purpose\", \"\", []address{member})\n\t})\n\n\turequire.PanicsWithMessage(t, cur, \"a SubDAO requires at least one initial council member\", func() {\n\t\tnewSubDAOPropDefinition(dao, \"Sub\", \"Purpose\", \"\", nil)\n\t})\n\n\tdef := newSubDAOPropDefinition(dao, \"Sub\", \"Purpose\", \"\", []address{member})\n\tuassert.Equal(t, \"New SubDAO: Sub\", def.Title())\n\tuassert.Equal(t, int(commondao.ThresholdSimpleMajority), int(def.Threshold()))\n\tuassert.NotEmpty(t, def.Body())\n\tuassert.NoError(t, def.Validate())\n}\n\nfunc TestSubDAOPropDefinitionExecute(cur realm, t *testing.T) {\n\tvar member address = \"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\"\n\n\tdao := newTestDAO(t, \"Root2\", member)\n\n\tdef := newSubDAOPropDefinition(dao, \"Sub\", \"Purpose\", \"\", []address{member})\n\n\turequire.NoError(t, def.Executor()(0, cur))\n\n\turequire.Equal(t, 1, dao.ChildrenCount(), \"expect one SubDAO\")\n\tvar sub *commondao.CommonDAO\n\tdao.IterateChildren(func(child *commondao.CommonDAO) bool {\n\t\tsub = child\n\t\treturn true\n\t})\n\tuassert.Equal(t, \"Sub\", sub.Name())\n\tuassert.True(t, sub.Council().Has(member))\n\tuassert.Equal(t, 1, sub.Council().Size())\n\n\t// A second SubDAO with the same name is rejected at validation\n\tuassert.ErrorContains(t, def.Validate(), \"a SubDAO with the same name already exists\")\n}\n\nfunc TestDissolvePropDefinitionExecute(cur realm, t *testing.T) {\n\tvar member address = \"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\"\n\n\tdao := newTestDAO(t, \"Root3\", member)\n\n\turequire.PanicsWithMessage(t, cur, \"SubDAO is required\", func() {\n\t\tnewDissolvePropDefinition(nil, \"\")\n\t})\n\n\tdef := newDissolvePropDefinition(dao, member)\n\tuassert.Equal(t, \"Dissolve DAO: Root3\", def.Title())\n\tuassert.Equal(t, int(commondao.ThresholdSupermajority), int(def.Threshold()))\n\tuassert.NoError(t, def.Validate())\n\n\t// Dissolution voids in-flight proposals before soft deleting the DAO\n\tp, err := dao.Propose(member, kindText, textArgs{\n\t\ttitle:        \"Pending\",\n\t\tbody:         \"pending\",\n\t\tvotingPeriod: time.Hour * 24,\n\t})\n\turequire.NoError(t, err)\n\n\turequire.NoError(t, def.Executor()(0, cur))\n\n\tuassert.True(t, dao.IsDeleted())\n\tuassert.Equal(t, 0, dao.ActiveProposalsSize())\n\tuassert.Equal(t, string(commondao.StatusDismissed), string(p.Status()))\n\tuassert.Equal(t, \"DAO dissolved\", p.StatusReason())\n\n\t// Dissolved DAOs cannot be dissolved again\n\tuassert.ErrorContains(t, def.Validate(), \"has already been dissolved\")\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_text_test.gno","body":"package commondao\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nvar (\n\t_ commondao.ProposalDefinition = (*textPropDefinition)(nil)\n)\n\nfunc TestTextPropDefinitionNew(cur realm, t *testing.T) {\n\turequire.PanicsWithMessage(t, cur, \"proposal title is empty\", func() {\n\t\tnewTextPropDefinition(\"  \", \"body\", time.Hour*24)\n\t})\n\n\turequire.PanicsWithMessage(t, cur, \"proposal title is too long, max length is 255 chars\", func() {\n\t\tnewTextPropDefinition(strings.Repeat(\"a\", maxTextTitle+1), \"body\", time.Hour*24)\n\t})\n\n\turequire.PanicsWithMessage(t, cur, \"proposal body is empty\", func() {\n\t\tnewTextPropDefinition(\"title\", \"  \", time.Hour*24)\n\t})\n\n\turequire.PanicsWithMessage(t, cur, \"proposal body is too long, max length is 15000 chars\", func() {\n\t\tnewTextPropDefinition(\"title\", strings.Repeat(\"a\", maxTextBody+1), time.Hour*24)\n\t})\n\n\turequire.PanicsWithMessage(t, cur, \"minimum proposal voting period is one day\", func() {\n\t\tnewTextPropDefinition(\"title\", \"body\", time.Hour)\n\t})\n\n\tdef := newTextPropDefinition(\" title \", \" body \", time.Hour*48)\n\tuassert.Equal(t, \"title\", def.Title())\n\tuassert.Equal(t, \"body\", def.Body())\n\tuassert.Equal(t, int64(time.Hour*48), int64(def.VotingPeriod()))\n\tuassert.Equal(t, int(commondao.ThresholdSupermajority), int(def.Threshold()))\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\"\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":"proposal_treasury_test.gno","body":"package commondao\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/p/nt/uassert/v0\"\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\nvar (\n\t_ commondao.ProposalDefinition = (*treasurySpendPropDefinition)(nil)\n\t_ commondao.ProposalDefinition = (*treasuryClawbackPropDefinition)(nil)\n\t_ commondao.ProposalDefinition = (*treasuryFreezePropDefinition)(nil)\n)\n\n// newTestTree builds an in-memory root -\u003e mid -\u003e leaf DAO chain.\nfunc newTestTree() (root, mid, leaf *commondao.CommonDAO) {\n\troot = commondao.New(commondao.WithID(101), commondao.WithName(\"Root\"))\n\tmid = commondao.New(commondao.WithID(102), commondao.WithName(\"Mid\"), commondao.WithParent(root))\n\tleaf = commondao.New(commondao.WithID(103), commondao.WithName(\"Leaf\"), commondao.WithParent(mid))\n\treturn\n}\n\nfunc TestTreasurySpendPropDefinition(cur realm, t *testing.T) {\n\tvar member address = \"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\"\n\n\tdao := commondao.New(\n\t\tcommondao.WithID(100),\n\t\tcommondao.WithName(\"Foo\"),\n\t\tcommondao.WithAddress(member), // any valid, unfunded address\n\t)\n\tcoin := chain.NewCoin(\"ugnot\", 100)\n\n\turequire.PanicsWithMessage(t, cur, \"DAO is required\", func() {\n\t\tnewTreasurySpendPropDefinition(nil, member, coin)\n\t})\n\turequire.PanicsWithMessage(t, cur, \"invalid recipient address\", func() {\n\t\tnewTreasurySpendPropDefinition(dao, \"invalid\", coin)\n\t})\n\turequire.PanicsWithMessage(t, cur, \"coin denomination is empty\", func() {\n\t\tnewTreasurySpendPropDefinition(dao, member, chain.Coin{Amount: 1})\n\t})\n\turequire.PanicsWithMessage(t, cur, \"spend amount must be positive\", func() {\n\t\tnewTreasurySpendPropDefinition(dao, member, chain.NewCoin(\"ugnot\", 0))\n\t})\n\n\tdef := newTreasurySpendPropDefinition(dao, member, coin)\n\tuassert.Equal(t, \"Treasury Spend\", def.Title())\n\tuassert.Equal(t, int(commondao.ThresholdSupermajority), int(def.Threshold()))\n\tuassert.NotEmpty(t, def.Body())\n\n\t// The treasury is unfunded\n\tuassert.ErrorContains(t, def.Validate(), \"insufficient treasury balance\")\n\n\t// Frozen treasuries reject spends before the balance check\n\tdao.SetTreasuryFrozen(true)\n\tuassert.ErrorContains(t, def.Validate(), \"DAO treasury is frozen\")\n\tdao.SetTreasuryFrozen(false)\n\n\t// Dissolved DAOs reject spends\n\tdao.Dissolve(\"test\")\n\tuassert.ErrorContains(t, def.Validate(), \"DAO has already been dissolved\")\n}\n\nfunc TestTreasuryClawbackPropDefinition(cur realm, t *testing.T) {\n\troot, mid, leaf := newTestTree()\n\n\turequire.PanicsWithMessage(t, cur, \"DAO is required\", func() {\n\t\tnewTreasuryClawbackPropDefinition(nil, leaf)\n\t})\n\turequire.PanicsWithMessage(t, cur, \"target DAO is required\", func() {\n\t\tnewTreasuryClawbackPropDefinition(root, nil)\n\t})\n\n\tdef := newTreasuryClawbackPropDefinition(root, leaf)\n\tuassert.Equal(t, \"Treasury Clawback\", def.Title())\n\tuassert.Equal(t, int(commondao.ThresholdSimpleMajority), int(def.Threshold()))\n\tuassert.NotEmpty(t, def.Body())\n\n\t// Any proper ancestor qualifies, not just the direct parent\n\tuassert.NoError(t, newTreasuryClawbackPropDefinition(root, mid).Validate())\n\tuassert.NoError(t, newTreasuryClawbackPropDefinition(root, leaf).Validate())\n\tuassert.NoError(t, newTreasuryClawbackPropDefinition(mid, leaf).Validate())\n\n\t// A DAO can never target itself, and descendants and strangers have\n\t// no clawback authority\n\tuassert.ErrorContains(t,\n\t\tnewTreasuryClawbackPropDefinition(root, root).Validate(),\n\t\t\"a DAO cannot target itself\")\n\tuassert.ErrorContains(t,\n\t\tnewTreasuryClawbackPropDefinition(leaf, root).Validate(),\n\t\t\"DAO is not an ancestor of the target DAO\")\n\tuassert.ErrorContains(t,\n\t\tnewTreasuryClawbackPropDefinition(commondao.New(commondao.WithID(999)), leaf).Validate(),\n\t\t\"DAO is not an ancestor of the target DAO\")\n}\n\nfunc TestTreasuryFreezePropDefinition(cur realm, t *testing.T) {\n\troot, mid, leaf := newTestTree()\n\n\turequire.PanicsWithMessage(t, cur, \"DAO is required\", func() {\n\t\tnewTreasuryFreezePropDefinition(nil, leaf, true)\n\t})\n\turequire.PanicsWithMessage(t, cur, \"target DAO is required\", func() {\n\t\tnewTreasuryFreezePropDefinition(root, nil, true)\n\t})\n\n\tfreeze := newTreasuryFreezePropDefinition(root, leaf, true)\n\tuassert.Equal(t, \"Treasury Freeze\", freeze.Title())\n\tuassert.Equal(t, int(commondao.ThresholdSimpleMajority), int(freeze.Threshold()))\n\tuassert.NotEmpty(t, freeze.Body())\n\n\tunfreeze := newTreasuryFreezePropDefinition(root, leaf, false)\n\tuassert.Equal(t, \"Treasury Unfreeze\", unfreeze.Title())\n\tuassert.NotEmpty(t, unfreeze.Body())\n\n\tuassert.NoError(t, freeze.Validate())\n\tuassert.NoError(t, newTreasuryFreezePropDefinition(mid, leaf, true).Validate())\n\tuassert.ErrorContains(t,\n\t\tnewTreasuryFreezePropDefinition(leaf, leaf, false).Validate(),\n\t\t\"a DAO cannot target itself\")\n\tuassert.ErrorContains(t,\n\t\tnewTreasuryFreezePropDefinition(leaf, mid, true).Validate(),\n\t\t\"DAO is not an ancestor of the target DAO\")\n}\n\n// TestTreasuryFreezeBlastRadius pins that a freeze touches exactly its\n// target. Freezing is deliberately not transitive — an ancestor freezes\n// each descendant explicitly — so a change that made it cascade would\n// let one vote lock a whole subtree's treasuries, and one that let it\n// reach upward would let a descendant's freeze bind its own parent.\n// Neither direction was covered.\nfunc TestTreasuryFreezeBlastRadius(cur realm, t *testing.T) {\n\troot, mid, leaf := newTestTree()\n\n\t// Downward: freezing the middle DAO leaves its descendant alone.\n\turequire.NoError(t, newTreasuryFreezePropDefinition(root, mid, true).Executor()(0, cur))\n\tuassert.True(t, mid.IsTreasuryFrozen(), \"target must be frozen\")\n\tuassert.False(t, leaf.IsTreasuryFrozen(), \"freeze must not cascade to descendants\")\n\tuassert.False(t, root.IsTreasuryFrozen(), \"freeze must not touch the proposing ancestor\")\n\n\turequire.NoError(t, newTreasuryFreezePropDefinition(root, mid, false).Executor()(0, cur))\n\tuassert.False(t, mid.IsTreasuryFrozen(), \"unfreeze must clear the target\")\n\n\t// Upward: freezing a grandchild leaves the DAO in between alone. The\n\t// grandchild leg is what catches an upward reach — with root-\u003emid the\n\t// target's parent IS the proposing ancestor, so the two are\n\t// indistinguishable.\n\turequire.NoError(t, newTreasuryFreezePropDefinition(root, leaf, true).Executor()(0, cur))\n\tuassert.True(t, leaf.IsTreasuryFrozen(), \"target must be frozen\")\n\tuassert.False(t, mid.IsTreasuryFrozen(), \"freeze must not touch the target's parent\")\n\tuassert.False(t, root.IsTreasuryFrozen(), \"freeze must not touch the proposing ancestor\")\n}\n"},{"name":"public.gno","body":"package commondao\n\nimport (\n\t// unsafe is used in two places, both reading the frame (never for\n\t// authorization by pkgpath): OriginCaller in New (invitations target\n\t// EOAs, so the invite is keyed to the transaction origin) and\n\t// CurrentRealm in assertRunningPath (deploy-time path check). Caller\n\t// authentication everywhere 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// 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// An invitation is required to start creating DAOs: the transaction\n// origin (an EOA) must hold an invite, which is consumed on its first\n// creation; afterwards that origin may create further DAOs freely. The\n// caller becomes a council member, optionally together with a newline\n// separated list of additional member addresses. Sub-DAOs are created\n// through proposals (see CreateSubDAOProposal).\nfunc New(cur realm, name, purpose, description, members string) uint64 {\n\tassertCurrent(cur)\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 right to create DAOs is granted to invited EOAs, so gate on the\n\t// transaction origin. The invite is consumed once; the origin is then\n\t// recorded so it can create further DAOs without another invite.\n\torig := unsafe.OriginCaller()\n\tif !isCreator(orig) {\n\t\tassertIsInvited(orig)\n\t\tinvites.Remove(orig.String())\n\t\tcreators.Set(orig.String(), struct{}{})\n\t}\n\n\tcaller := cur.Previous().Address()\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":"public_test.gno","body":"package commondao\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/urequire/v0\"\n)\n\n// TestAssertRunningPath pins the deploy-time guard on the package path.\n// Treasury addresses derive from the pkgPath const while Execute mints\n// cur.Sub under the path the realm is actually running at, so a copy\n// deployed elsewhere would read balances at one address family and send\n// from another. The guard turns that into a genesis abort; nothing else\n// in the suite notices if it stops doing so.\nfunc TestAssertRunningPath(cur realm, t *testing.T) {\n\tassertRunningPath() // running at pkgPath: must not panic\n\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/nt/commondao/v1\"))\n\turequire.PanicsWithMessage(t, cur,\n\t\t\"commondao: realm deployed at gno.land/r/nt/commondao/v1, expected gno.land/r/nt/commondao/v0\",\n\t\tfunc() { assertRunningPath() })\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":"reentrancy_test.gno","body":"package commondao\n\nimport \"testing\"\n\n// TestExecuteReentrancyLatch pins the latch mechanism directly: a nested\n// enterExecute (which is what a re-entrant Execute reaches) must panic, and\n// leaveExecute must clear the latch so the next execution can proceed. The\n// end-to-end re-entry through a real proposal closure that crosses back into\n// Execute is covered by the z_20_i filetest.\nfunc TestExecuteReentrancyLatch(t *testing.T) {\n\tleaveExecute() // ensure a clean starting state\n\n\t// First entry raises the latch.\n\tenterExecute()\n\tif !executing {\n\t\tt.Fatal(\"expected the latch to be raised after enterExecute\")\n\t}\n\n\t// A nested entry (the re-entrant Execute) must panic.\n\tfunc() {\n\t\tdefer func() {\n\t\t\tif r := recover(); r == nil {\n\t\t\t\tt.Fatal(\"expected a nested enterExecute to panic\")\n\t\t\t}\n\t\t}()\n\t\tenterExecute()\n\t\tt.Fatal(\"unreachable: the nested enterExecute must panic\")\n\t}()\n\n\t// The rejected re-entry must not have lowered the latch.\n\tif !executing {\n\t\tt.Fatal(\"the latch must stay raised after a rejected re-entry\")\n\t}\n\n\t// Leaving lowers it; the next execution may then proceed.\n\tleaveExecute()\n\tif executing {\n\t\tt.Fatal(\"expected the latch to be lowered after leaveExecute\")\n\t}\n\tenterExecute()\n\tleaveExecute()\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\"\n\t\"gno.land/p/moul/md\"\n\t\"gno.land/p/moul/mdtable\"\n\t\"gno.land/p/moul/realmpath\"\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"},{"name":"z_10_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_10_a_filetest\n\npackage z_10_a_filetest\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"*Pwn* [link](https://evil.example) # H1\", \"Purpose\", \"\", \"\")\n}\n\nfunc main() {\n\t// DAO names are user controlled: markdown metacharacters must\n\t// render escaped, never as markup\n\tprintln(commondao.Render(strconv.FormatUint(daoID, 10)))\n}\n\n// Output:\n// # \\*Pwn\\* \\[link\\]\\(https://evil\\.example\\) \\# H1\n// **Purpose:** Purpose\n//\n// [View Proposals](/r/nt/commondao/v0:2/proposals) • [View Settings](/r/nt/commondao/v0:2/settings)\n//\n// ---\n// | Council |\n// | --- |\n// | g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 |\n//\n//\n// ## Treasury\n// - Address: g1vpah5sslxspfdvj9vk07rukek327dzmtxqkmk2\n// - Balance: (empty)\n// ## Create Proposal\n// These are the proposal supported by this DAO:\n//\n// \u003cgno-columns\u003e\n// [General Proposal](/r/nt/commondao/v0$help\u0026func=CreateTextProposal\u0026body=\u0026daoID=2\u0026title=\u0026votingDays=7)\n//\n// This type of proposal is also known as text proposal which can be used for example to get consensus on initiatives without actually making any change on-chain.\n//\n//\n// \u003cgno-columns-sep\u003e\n// [Update Council](/r/nt/commondao/v0$help\u0026func=CreateCouncilUpdateProposal\u0026daoID=2\u0026newMembers=\u0026removeMembers=)\n//\n// This type of proposal can be used to add new council members to this DAO and also to remove existing ones.\n//\n// A single proposal allows new council members to be added and any number of existing ones removed within the same proposal.\n//\n//\n// \u003cgno-columns-sep\u003e\n// [Ancestor Council Update](/r/nt/commondao/v0$help\u0026func=CreateAncestorCouncilUpdateProposal\u0026daoID=2\u0026newMembers=\u0026removeMembers=\u0026targetID=)\n//\n// This type of proposal lets this DAO, as an ancestor, add or remove council members of one of its descendant DAOs — the rescue path for a descendant whose council is stuck or empty.\n//\n//\n// \u003c/gno-columns\u003e\n// \u003cgno-columns\u003e\n// [Dissolve DAO](/r/nt/commondao/v0$help\u0026func=CreateDissolutionProposal\u0026daoID=2\u0026destination=)\n//\n// This type of proposal can be used to dissolve DAOs and SubDAOs.\n//\n// Dissolving a DAO can't be undone, once the dissolution proposal passes and is executed DAO will be readonly.\n//\n//\n// \u003cgno-columns-sep\u003e\n// [Treasury Spend](/r/nt/commondao/v0$help\u0026func=CreateTreasurySpendProposal\u0026amount=\u0026daoID=2\u0026denom=ugnot\u0026to=)\n//\n// This type of proposal sends coins from the DAO's own treasury when it passes and is executed.\n//\n//\n// \u003cgno-columns-sep\u003e\n// [Treasury Clawback](/r/nt/commondao/v0$help\u0026func=CreateTreasuryClawbackProposal\u0026daoID=2\u0026targetID=)\n//\n// This type of proposal sweeps a descendant DAO's treasury to the descendant's parent DAO.\n//\n//\n// \u003c/gno-columns\u003e\n// \u003cgno-columns\u003e\n// [Treasury Freeze](/r/nt/commondao/v0$help\u0026func=CreateTreasuryFreezeProposal\u0026daoID=2\u0026frozen=true\u0026targetID=)\n//\n// This type of proposal freezes or unfreezes a descendant DAO's treasury. While frozen, no funds can leave the treasury.\n//\n//\n// \u003cgno-columns-sep\u003e\n// [New SubDAO](/r/nt/commondao/v0$help\u0026func=CreateSubDAOProposal\u0026daoID=2\u0026description=\u0026members=\u0026name=\u0026purpose=)\n//\n// This type of proposal is used to create SubDAOs, which are used to create tree based DAOs.\n//\n//\n// \u003cgno-columns-sep\u003e\n// [Register Proposal Kind](/r/nt/commondao/v0$help\u0026func=CreateRegisterKindProposal\u0026daoID=2\u0026kindName=) • [Deregister Proposal Kind](/r/nt/commondao/v0$help\u0026func=CreateDeregisterKindProposal\u0026daoID=2\u0026kindName=)\n//\n// This type of proposal registers one of the realm's catalog proposal kinds on this DAO by name, or deregisters a kind. Deregistering a kind blocks new proposals of that kind while in-flight ones still vote and execute. The manage-kinds kind itself cannot be deregistered.\n//\n//\n// \u003c/gno-columns\u003e\n// \u003cgno-columns\u003e\n// [Amend Bylaws](/r/nt/commondao/v0$help\u0026func=CreateAmendBylawsProposal\u0026daoID=2\u0026payload=)\n//\n// This type of proposal adds, amends or removes one of the DAO's bylaws documents with a diff patch pinned to the current document text (the mandates folder is reserved: mandates are set from above, not by the council). Build the payload with the AmendBylawsPayload query function.\n//\n//\n// \u003c/gno-columns\u003e\n"},{"name":"z_10_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_10_b_filetest\n\npackage z_10_b_filetest\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoID        uint64\n\tproposalPath string\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\tpID := commondao.CreateTextProposal(cross(cur), daoID, \"*Title* [t](https://evil.example)\", \"**Body** with \u003cimg src=x\u003e and [b](https://evil.example)\", 0)\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"*reason* [r](https://evil.example)\")\n\tproposalPath = strconv.FormatUint(daoID, 10) + \"/proposals/\" + strconv.FormatUint(pID, 10)\n}\n\nfunc main() {\n\t// Proposal titles, bodies and vote reasons are user controlled:\n\t// markdown metacharacters must render escaped, never as markup\n\tprintln(commondao.Render(proposalPath))\n\tprintln(commondao.Render(proposalPath + \"/vote/\" + string(user)))\n}\n\n// Output:\n// # #1 \\*Title\\* \\[t\\]\\(https://evil\\.example\\)\n// [Go to DAO](/r/nt/commondao/v0:2) • [Execute](/r/nt/commondao/v0$help\u0026func=Execute\u0026daoID=2\u0026proposalID=1)\n//\n// ---\n// ## Details\n// - Proposer: g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// - Submit Time: Fri, 13 Feb 2009 23:31:30 UTC\n// - Status: **passed**\n// ## Description\n// \\*\\*Body\\*\\* with \\\u003cimg src=x\\\u003e and \\[b\\]\\(https://evil\\.example\\)\n//\n// ## Stats\n// | Vote Choices | Percentage of Votes |\n// | --- | --- |\n// | YES | 100.00% |\n//\n//\n// ## Votes\n// Total number of votes: **1**\n// | Users | Votes |\n// | --- | --- |\n// | g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 | [YES](/r/nt/commondao/v0:2/proposals/1/vote/g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5) with a reason |\n//\n//\n//\n// # Vote: Proposal #1\n// [Go to DAO](/r/nt/commondao/v0:2) • [Go to Proposal](/r/nt/commondao/v0:2/proposals/1)\n//\n// ---\n// ## Details\n// - User: g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// - Vote: YES\n// ## Reason\n// \\*reason\\* \\[r\\]\\(https://evil\\.example\\)\n"},{"name":"z_10_c_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_10_c_filetest\n\npackage z_10_c_filetest\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar proposalPath string\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID := commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\t// The SubDAO name is user controlled; the proposal body is pre-built\n\t// markdown chrome that must render formatted, with the name escaped.\n\tpID := commondao.CreateSubDAOProposal(cross(cur), daoID, \"*Evil* [x](https://evil.example)\", \"Purpose\", \"\", string(owner))\n\tproposalPath = strconv.FormatUint(daoID, 10) + \"/proposals/\" + strconv.FormatUint(pID, 10)\n}\n\nfunc main() {\n\tprintln(commondao.Render(proposalPath))\n}\n\n// Output:\n//\n// \u003e Voting ends on **Fri, 20 Feb 2009 11:31pm UTC**\n//\n// # #1 New SubDAO: \\*Evil\\* \\[x\\]\\(https://evil\\.example\\)\n// [Go to DAO](/r/nt/commondao/v0:2) • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=1\u0026reason=\u0026vote=)\n//\n// ---\n// ## Details\n// - Proposer: g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// - Submit Time: Fri, 13 Feb 2009 23:31:30 UTC\n// - Expected Outcome: **pending** ⏳\n// - Status: **active**\n// ## Description\n// **Parent DAO:**\n// [Foo](/r/nt/commondao/v0:2)\n//\n// **SubDAO Name:**\n// \\*Evil\\* \\[x\\]\\(https://evil\\.example\\)\n//\n// **SubDAO Purpose:**\n// Purpose\n//\n// **Council Members:**\n// - g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\n"},{"name":"z_10_d_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_10_d_filetest\n\npackage z_10_d_filetest\n\nimport (\n\t\"chain\"\n\t\"strconv\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar subID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID := commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubID = 3\n\n\ttesting.IssueCoins(commondao.GetView(subID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 1234)))\n\n\tfID := commondao.CreateTreasuryFreezeProposal(cross(cur), rootID, subID, true)\n\tcommondao.Vote(cross(cur), rootID, fID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, fID)\n}\n\nfunc main() {\n\t// The DAO page shows the funded balance and the frozen warning; the\n\t// settings page shows the treasury proposals flag\n\tprintln(commondao.Render(strconv.FormatUint(subID, 10)))\n\tprintln(commondao.Render(strconv.FormatUint(subID, 10) + \"/settings\"))\n}\n\n// Output:\n// # Sub\n// **Purpose:** Purpose\n//\n// [View Proposals](/r/nt/commondao/v0:3/proposals) • [View Settings](/r/nt/commondao/v0:3/settings) • [Go to Parent DAO](/r/nt/commondao/v0:2)\n//\n// ---\n// | Council |\n// | --- |\n// | g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 |\n//\n//\n// ## Treasury\n// - Address: g17pr3grpaag8ketn84dl2y0nncef6u3jw8ca9gl\n// - Balance: 1234ugnot\n//\n// \u003e ⚠ The treasury is frozen: no proposal can move funds until a proper ancestor DAO unfreezes it.\n//\n// ## Create Proposal\n// These are the proposal supported by this DAO:\n//\n// \u003cgno-columns\u003e\n// [General Proposal](/r/nt/commondao/v0$help\u0026func=CreateTextProposal\u0026body=\u0026daoID=3\u0026title=\u0026votingDays=7)\n//\n// This type of proposal is also known as text proposal which can be used for example to get consensus on initiatives without actually making any change on-chain.\n//\n//\n// \u003cgno-columns-sep\u003e\n// [Update Council](/r/nt/commondao/v0$help\u0026func=CreateCouncilUpdateProposal\u0026daoID=3\u0026newMembers=\u0026removeMembers=)\n//\n// This type of proposal can be used to add new council members to this DAO and also to remove existing ones.\n//\n// A single proposal allows new council members to be added and any number of existing ones removed within the same proposal.\n//\n//\n// \u003cgno-columns-sep\u003e\n// [Ancestor Council Update](/r/nt/commondao/v0$help\u0026func=CreateAncestorCouncilUpdateProposal\u0026daoID=3\u0026newMembers=\u0026removeMembers=\u0026targetID=)\n//\n// This type of proposal lets this DAO, as an ancestor, add or remove council members of one of its descendant DAOs — the rescue path for a descendant whose council is stuck or empty.\n//\n//\n// \u003c/gno-columns\u003e\n// \u003cgno-columns\u003e\n// [Dissolve DAO](/r/nt/commondao/v0$help\u0026func=CreateDissolutionProposal\u0026daoID=3\u0026destination=)\n//\n// This type of proposal can be used to dissolve DAOs and SubDAOs.\n//\n// Dissolving a DAO can't be undone, once the dissolution proposal passes and is executed DAO will be readonly.\n//\n//\n// \u003cgno-columns-sep\u003e\n// [Treasury Spend](/r/nt/commondao/v0$help\u0026func=CreateTreasurySpendProposal\u0026amount=\u0026daoID=3\u0026denom=ugnot\u0026to=)\n//\n// This type of proposal sends coins from the DAO's own treasury when it passes and is executed.\n//\n//\n// \u003cgno-columns-sep\u003e\n// [Treasury Clawback](/r/nt/commondao/v0$help\u0026func=CreateTreasuryClawbackProposal\u0026daoID=3\u0026targetID=)\n//\n// This type of proposal sweeps a descendant DAO's treasury to the descendant's parent DAO.\n//\n//\n// \u003c/gno-columns\u003e\n// \u003cgno-columns\u003e\n// [Treasury Freeze](/r/nt/commondao/v0$help\u0026func=CreateTreasuryFreezeProposal\u0026daoID=3\u0026frozen=true\u0026targetID=)\n//\n// This type of proposal freezes or unfreezes a descendant DAO's treasury. While frozen, no funds can leave the treasury.\n//\n//\n// \u003cgno-columns-sep\u003e\n// [New SubDAO](/r/nt/commondao/v0$help\u0026func=CreateSubDAOProposal\u0026daoID=3\u0026description=\u0026members=\u0026name=\u0026purpose=)\n//\n// This type of proposal is used to create SubDAOs, which are used to create tree based DAOs.\n//\n//\n// \u003cgno-columns-sep\u003e\n// [Register Proposal Kind](/r/nt/commondao/v0$help\u0026func=CreateRegisterKindProposal\u0026daoID=3\u0026kindName=) • [Deregister Proposal Kind](/r/nt/commondao/v0$help\u0026func=CreateDeregisterKindProposal\u0026daoID=3\u0026kindName=)\n//\n// This type of proposal registers one of the realm's catalog proposal kinds on this DAO by name, or deregisters a kind. Deregistering a kind blocks new proposals of that kind while in-flight ones still vote and execute. The manage-kinds kind itself cannot be deregistered.\n//\n//\n// \u003c/gno-columns\u003e\n// \u003cgno-columns\u003e\n// [Amend Bylaws](/r/nt/commondao/v0$help\u0026func=CreateAmendBylawsProposal\u0026daoID=3\u0026payload=)\n//\n// This type of proposal adds, amends or removes one of the DAO's bylaws documents with a diff patch pinned to the current document text (the mandates folder is reserved: mandates are set from above, not by the council). Build the payload with the AmendBylawsPayload query function.\n//\n//\n// \u003c/gno-columns\u003e\n//\n// # Sub: Settings\n// [Go to DAO](/r/nt/commondao/v0:3)\n//\n// ---\n// ## Info\n// | Setting | Value |\n// | --- | --- |\n// | Listed | false |\n// | Max active proposals | 32 |\n// | Proposal kinds | amend\\-bylaws, ancestor\\-council\\-update, council\\-update, dissolve, manage\\-kinds, subdao, text, treasury\\-clawback, treasury\\-freeze, treasury\\-spend |\n"},{"name":"z_10_e_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_10_e_filetest\n\npackage z_10_e_filetest\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoID uint64\n\tpID   uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\t// A 3-member council keeps the proposal active after one vote, so the\n\t// voter can change their choice.\n\tmembers := \"g1cyh9qm4y43w38gfk77qxczrhqj2asdr8l7uk54\\ng1x95kxqpwvqjf98qpkvsay7tppkh6zs9fr7wwda\"\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", members)\n\tpID = commondao.CreateTextProposal(cross(cur), daoID, \"Title\", \"Body\", 30)\n\n\t// Vote YES, then change to NO: the vote stats must show only NO,\n\t// never a stale \"YES | 0.00%\" row from the zeroed counter.\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceNo, \"\")\n}\n\nfunc main() {\n\tprintln(commondao.Render(strconv.FormatUint(daoID, 10) + \"/proposals/\" + strconv.FormatUint(pID, 10)))\n}\n\n// Output:\n//\n// \u003e Voting ends on **Sun, 15 Mar 2009 11:31pm UTC**\n//\n// # #1 Title\n// [Go to DAO](/r/nt/commondao/v0:2) • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=1\u0026reason=\u0026vote=)\n//\n// ---\n// ## Details\n// - Proposer: g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// - Submit Time: Fri, 13 Feb 2009 23:31:30 UTC\n// - Expected Outcome: **pending** ⏳\n// - Status: **active**\n// ## Description\n// Body\n//\n// ## Stats\n// | Vote Choices | Percentage of Votes |\n// | --- | --- |\n// | NO | 100.00% |\n//\n//\n// ## Votes\n// Total number of votes: **1**\n// | Users | Votes |\n// | --- | --- |\n// | g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 | [NO](/r/nt/commondao/v0:2/proposals/1/vote/g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5) |\n"},{"name":"z_11_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_11_a_filetest\n\npackage z_11_a_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoID uint64\n\tpID   uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\ttesting.IssueCoins(commondao.GetView(daoID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\n\tpID = commondao.CreateTreasurySpendProposal(cross(cur), daoID, owner, \"ugnot\", 400)\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.Execute(cross(cur), daoID, pID)\n\n\tview := commondao.GetView(daoID)\n\tp, _ := view.GetProposal(pID)\n\tprintln(\"status:\", string(p.Status()))\n\n\tb := banker.NewReadonlyBanker()\n\tprintln(\"treasury:\", b.GetCoins(view.Address()).String())\n\tprintln(\"recipient:\", b.GetCoins(owner).String())\n}\n\n// Output:\n// status: executed\n// treasury: 600ugnot\n// recipient: 400ugnot\n"},{"name":"z_11_c_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_11_c_filetest\n\npackage z_11_c_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\t// Call as a user which is not a council member\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tcommondao.CreateTreasurySpendProposal(cross(cur), daoID, owner, \"ugnot\", 1)\n}\n\n// Error:\n// caller is not a council member\n"},{"name":"z_11_d_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_11_d_filetest\n\npackage z_11_d_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// The treasury is empty, so validation fails at proposal creation\n\tcommondao.CreateTreasurySpendProposal(cross(cur), daoID, owner, \"ugnot\", 1)\n}\n\n// Error:\n// insufficient treasury balance\n"},{"name":"z_11_e_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_11_e_filetest\n\npackage z_11_e_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID  uint64\n\tsubID   uint64\n\tspendID uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubID = 3\n\n\ttesting.IssueCoins(commondao.GetView(subID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 500)))\n\n\t// Pass a spend on the sub-DAO but do not execute it yet\n\tspendID = commondao.CreateTreasurySpendProposal(cross(cur), subID, owner, \"ugnot\", 500)\n\tcommondao.Vote(cross(cur), subID, spendID, pdao.ChoiceYes, \"\")\n\n\t// The ancestor freezes the sub-DAO treasury before the spend executes\n\tfID := commondao.CreateTreasuryFreezeProposal(cross(cur), rootID, subID, true)\n\tcommondao.Vote(cross(cur), rootID, fID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, fID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// The standing passed spend fails cleanly once the treasury is frozen\n\tcommondao.Execute(cross(cur), subID, spendID)\n\n\tview := commondao.GetView(subID)\n\tp, _ := view.GetProposal(spendID)\n\tprintln(\"status:\", string(p.Status()))\n\tprintln(\"reason:\", p.StatusReason())\n\tprintln(\"frozen:\", view.IsTreasuryFrozen())\n\tprintln(\"treasury:\", banker.NewReadonlyBanker().GetCoins(view.Address()).String())\n}\n\n// Output:\n// status: failed\n// reason: DAO treasury is frozen\n// frozen: true\n// treasury: 500ugnot\n"},{"name":"z_11_f_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_11_f_filetest\n\npackage z_11_f_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoID uint64\n\tp1    uint64\n\tp2    uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\ttesting.IssueCoins(commondao.GetView(daoID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\n\t// Two passed spends over-commit the 1000ugnot balance\n\tp1 = commondao.CreateTreasurySpendProposal(cross(cur), daoID, owner, \"ugnot\", 800)\n\tcommondao.Vote(cross(cur), daoID, p1, pdao.ChoiceYes, \"\")\n\tp2 = commondao.CreateTreasurySpendProposal(cross(cur), daoID, owner, \"ugnot\", 800)\n\tcommondao.Vote(cross(cur), daoID, p2, pdao.ChoiceYes, \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.Execute(cross(cur), daoID, p1)\n\tcommondao.Execute(cross(cur), daoID, p2)\n\n\tview := commondao.GetView(daoID)\n\tv1, _ := view.GetProposal(p1)\n\tv2, _ := view.GetProposal(p2)\n\tprintln(\"first:\", string(v1.Status()))\n\tprintln(\"second:\", string(v2.Status()), \"-\", v2.StatusReason())\n\tprintln(\"treasury:\", banker.NewReadonlyBanker().GetCoins(view.Address()).String())\n}\n\n// Output:\n// first: executed\n// second: failed - insufficient treasury balance\n// treasury: 200ugnot\n"},{"name":"z_11_g_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_11_g_filetest\n\npackage z_11_g_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tsubID  uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubID = 3\n\n\tfID := commondao.CreateTreasuryFreezeProposal(cross(cur), rootID, subID, true)\n\tcommondao.Vote(cross(cur), rootID, fID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, fID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.CreateTreasurySpendProposal(cross(cur), subID, owner, \"ugnot\", 1)\n}\n\n// Error:\n// DAO treasury is frozen\n"},{"name":"z_11_h_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_11_h_filetest\n\npackage z_11_h_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"strings\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\n// A treasury spend requires a Supermajority (\u003e= 2/3), not a simple\n// majority. A 5-member council splitting 3 YES / 2 NO clears a simple\n// majority (2*3 \u003e 5) but NOT a supermajority (3*3 \u003c 2*5), so at the\n// deadline the spend is dismissed and the treasury is untouched. This\n// pins the spend threshold behaviourally: flipping it to SimpleMajority\n// would let this same vote pass and spend the funds.\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\tmoul  = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\") // @moul\n\tmF    = address(\"g1cyh9qm4y43w38gfk77qxczrhqj2asdr8l7uk54\")\n\tmG    = address(\"g1x95kxqpwvqjf98qpkvsay7tppkh6zs9fr7wwda\")\n)\n\nvar (\n\tdaoID uint64\n\tpID   uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// A 5-member council (caller + 4 additional members).\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tmembers := strings.Join([]string{owner.String(), moul.String(), mF.String(), mG.String()}, \"\\n\")\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", members)\n\n\ttesting.IssueCoins(commondao.GetView(daoID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 1000)))\n\n\tpID = commondao.CreateTreasurySpendProposal(cross(cur), daoID, owner, \"ugnot\", 400)\n\n\t// 3 YES / 2 NO from distinct council members. NO votes first so a\n\t// (would-be) simple-majority pass under a mutated threshold lands on\n\t// the last vote, never on an already-decided proposal.\n\ttesting.SetRealm(testing.NewUserRealm(mF))\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceNo, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(mG))\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceNo, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(moul))\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SkipHeights(121000) // 5s blocks: pass the 7 day voting deadline\n\n\tcommondao.Execute(cross(cur), daoID, pID)\n\n\tview := commondao.GetView(daoID)\n\tp, _ := view.GetProposal(pID)\n\tprintln(\"status:\", string(p.Status()))\n\tprintln(\"treasury:\", banker.NewReadonlyBanker().GetCoins(view.Address()).String())\n}\n\n// Output:\n// status: dismissed\n// treasury: 1000ugnot\n"},{"name":"z_12_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_12_a_filetest\n\npackage z_12_a_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tsubID  uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubID = 3\n\n\ttesting.IssueCoins(commondao.GetView(subID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 750)))\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// The ancestor claws back the sub-DAO treasury at simple majority\n\tpID := commondao.CreateTreasuryClawbackProposal(cross(cur), rootID, subID)\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, pID)\n\n\tb := banker.NewReadonlyBanker()\n\tprintln(\"sub treasury:\", b.GetCoins(commondao.GetView(subID).Address()).String())\n\tprintln(\"root treasury:\", b.GetCoins(commondao.GetView(rootID).Address()).String())\n\n\t// Clawing back an already-empty treasury executes as a no-op\n\tpID = commondao.CreateTreasuryClawbackProposal(cross(cur), rootID, subID)\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, pID)\n\tp, _ := commondao.GetView(rootID).GetProposal(pID)\n\tprintln(\"empty clawback:\", string(p.Status()))\n\tprintln(\"root treasury:\", b.GetCoins(commondao.GetView(rootID).Address()).String())\n}\n\n// Output:\n// sub treasury:\n// root treasury: 750ugnot\n// empty clawback: executed\n// root treasury: 750ugnot\n"},{"name":"z_12_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_12_b_filetest\n\npackage z_12_b_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// A DAO can never claw back its own treasury\n\tcommondao.CreateTreasuryClawbackProposal(cross(cur), daoID, daoID)\n}\n\n// Error:\n// a DAO cannot target itself\n"},{"name":"z_12_c_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_12_c_filetest\n\npackage z_12_c_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tsubA uint64\n\tsubB uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID := commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"A\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubA = 3\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"B\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubB = 4\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Siblings have no authority over each other\n\tcommondao.CreateTreasuryClawbackProposal(cross(cur), subA, subB)\n}\n\n// Error:\n// DAO is not an ancestor of the target DAO\n"},{"name":"z_12_d_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_12_d_filetest\n\npackage z_12_d_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tsubID  uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubID = 3\n\n\t// Freeze the sub-DAO, then dissolve it (the dissolution sweep runs on\n\t// an empty treasury), then fund its address afterwards: coins landing\n\t// on a dead DAO remain rescuable by an ancestor clawback.\n\tfID := commondao.CreateTreasuryFreezeProposal(cross(cur), rootID, subID, true)\n\tcommondao.Vote(cross(cur), rootID, fID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, fID)\n\n\tdID := commondao.CreateDissolutionProposal(cross(cur), subID, \"\")\n\tcommondao.Vote(cross(cur), rootID, dID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, dID)\n\n\ttesting.IssueCoins(commondao.GetView(subID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 300)))\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tpID := commondao.CreateTreasuryClawbackProposal(cross(cur), rootID, subID)\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, pID)\n\n\tview := commondao.GetView(subID)\n\tprintln(\"deleted:\", view.IsDeleted())\n\tprintln(\"frozen:\", view.IsTreasuryFrozen())\n\tb := banker.NewReadonlyBanker()\n\tprintln(\"sub treasury:\", b.GetCoins(view.Address()).String())\n\tprintln(\"root treasury:\", b.GetCoins(commondao.GetView(rootID).Address()).String())\n}\n\n// Output:\n// deleted: true\n// frozen: true\n// sub treasury:\n// root treasury: 300ugnot\n"},{"name":"z_12_e_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_12_e_filetest\n\npackage z_12_e_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tmidID  uint64\n\tleafID uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Mid\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tmidID = 3\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), midID, \"Leaf\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), midID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), midID, pID)\n\t}\n\tleafID = 4\n\n\ttesting.IssueCoins(commondao.GetView(leafID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 420)))\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// The grandparent proposes; swept funds must land on the target's\n\t// parent (one step up the tree), never on the proposing DAO\n\tpID := commondao.CreateTreasuryClawbackProposal(cross(cur), rootID, leafID)\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, pID)\n\n\tb := banker.NewReadonlyBanker()\n\tprintln(\"leaf treasury:\", b.GetCoins(commondao.GetView(leafID).Address()).String())\n\tprintln(\"mid treasury:\", b.GetCoins(commondao.GetView(midID).Address()).String())\n\tprintln(\"root treasury:\", b.GetCoins(commondao.GetView(rootID).Address()).String())\n}\n\n// Output:\n// leaf treasury:\n// mid treasury: 420ugnot\n// root treasury:\n"},{"name":"z_12_f_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_12_f_filetest\n\npackage z_12_f_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"strings\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\n// Treasury clawback passes by SIMPLE majority. A 5-member ancestor council\n// splitting 3 YES / 2 NO clears a simple majority (2*3 \u003e 5) but not a\n// supermajority (3*3 \u003c 2*5), so under the correct Simple threshold the\n// clawback executes and empties the target; a mutated Super threshold would\n// dismiss it, leaving the funds.\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\tmoul  = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\") // @moul\n\tmF    = address(\"g1cyh9qm4y43w38gfk77qxczrhqj2asdr8l7uk54\")\n\tmG    = address(\"g1x95kxqpwvqjf98qpkvsay7tppkh6zs9fr7wwda\")\n)\n\nvar (\n\trootID uint64\n\tsubID  uint64\n\tpID    uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tmembers := strings.Join([]string{owner.String(), moul.String(), mF.String(), mG.String()}, \"\\n\")\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", members)\n\n\t// Create a funded sub-DAO of root (sub creation itself is simple\n\t// majority: 3 of 5 YES passes).\n\tsp := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tcommondao.Vote(cross(cur), rootID, sp, pdao.ChoiceYes, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Vote(cross(cur), rootID, sp, pdao.ChoiceYes, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(moul))\n\tcommondao.Vote(cross(cur), rootID, sp, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, sp)\n\tsubID = 3\n\ttesting.IssueCoins(commondao.GetView(subID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 500)))\n\n\t// Clawback proposal, hosted in the ancestor (root), 3 YES / 2 NO.\n\tpID = commondao.CreateTreasuryClawbackProposal(cross(cur), rootID, subID)\n\ttesting.SetRealm(testing.NewUserRealm(mF))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceNo, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(mG))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceNo, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(moul))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SkipHeights(121000)\n\n\tcommondao.Execute(cross(cur), rootID, pID)\n\n\tp, _ := commondao.GetView(rootID).GetProposal(pID)\n\tprintln(\"status:\", string(p.Status()))\n\tprintln(\"sub treasury:\", banker.NewReadonlyBanker().GetCoins(commondao.GetView(subID).Address()).String())\n}\n\n// Output:\n// status: executed\n// sub treasury:\n"},{"name":"z_12_g_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_12_g_filetest\n\npackage z_12_g_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.CreateTreasuryClawbackProposal(cross(cur), daoID, 404)\n}\n\n// Error:\n// DAO not found\n"},{"name":"z_12_h_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_12_h_filetest\n\npackage z_12_h_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID  uint64\n\tsubID   uint64\n\tspendID uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubID = 3\n\n\ttesting.IssueCoins(commondao.GetView(subID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 500)))\n\n\t// Pass a spend on the sub-DAO but do not execute it yet\n\tspendID = commondao.CreateTreasurySpendProposal(cross(cur), subID, owner, \"ugnot\", 500)\n\tcommondao.Vote(cross(cur), subID, spendID, pdao.ChoiceYes, \"\")\n\n\t// The parent claws back the full balance before the spend executes\n\tcID := commondao.CreateTreasuryClawbackProposal(cross(cur), rootID, subID)\n\tcommondao.Vote(cross(cur), rootID, cID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, cID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// The standing passed spend fails cleanly on the drained treasury\n\tcommondao.Execute(cross(cur), subID, spendID)\n\n\tp, _ := commondao.GetView(subID).GetProposal(spendID)\n\tprintln(\"status:\", string(p.Status()))\n\tprintln(\"reason:\", p.StatusReason())\n\tb := banker.NewReadonlyBanker()\n\tprintln(\"sub treasury:\", b.GetCoins(commondao.GetView(subID).Address()).String())\n\tprintln(\"root treasury:\", b.GetCoins(commondao.GetView(rootID).Address()).String())\n\tprintln(\"recipient:\", b.GetCoins(owner).String())\n}\n\n// Output:\n// status: failed\n// reason: insufficient treasury balance\n// sub treasury:\n// root treasury: 500ugnot\n// recipient:\n"},{"name":"z_12_i_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_12_i_filetest\n\npackage z_12_i_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tmidID  uint64\n\tleafID uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Mid\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tmidID = 3\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), midID, \"Leaf\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), midID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), midID, pID)\n\t}\n\tleafID = 4\n\n\ttesting.IssueCoins(commondao.GetView(leafID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 900)))\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Root and mid both pass clawbacks against the same leaf\n\trID := commondao.CreateTreasuryClawbackProposal(cross(cur), rootID, leafID)\n\tcommondao.Vote(cross(cur), rootID, rID, pdao.ChoiceYes, \"\")\n\tmID := commondao.CreateTreasuryClawbackProposal(cross(cur), midID, leafID)\n\tcommondao.Vote(cross(cur), midID, mID, pdao.ChoiceYes, \"\")\n\n\t// Funds move exactly once, to the leaf's parent; the second clawback\n\t// executes as an empty no-op and does not hoist mid's new balance\n\tcommondao.Execute(cross(cur), rootID, rID)\n\tcommondao.Execute(cross(cur), midID, mID)\n\n\trp, _ := commondao.GetView(rootID).GetProposal(rID)\n\tmp, _ := commondao.GetView(midID).GetProposal(mID)\n\tprintln(\"root clawback:\", string(rp.Status()))\n\tprintln(\"mid clawback:\", string(mp.Status()))\n\tb := banker.NewReadonlyBanker()\n\tprintln(\"leaf treasury:\", b.GetCoins(commondao.GetView(leafID).Address()).String())\n\tprintln(\"mid treasury:\", b.GetCoins(commondao.GetView(midID).Address()).String())\n\tprintln(\"root treasury:\", b.GetCoins(commondao.GetView(rootID).Address()).String())\n}\n\n// Output:\n// root clawback: executed\n// mid clawback: executed\n// leaf treasury:\n// mid treasury: 900ugnot\n// root treasury:\n"},{"name":"z_12_j_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_12_j_filetest\n\npackage z_12_j_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tsubID  uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubID = 3\n\n\ttesting.IssueCoins(commondao.GetView(subID).Address(), chain.NewCoins(\n\t\tchain.NewCoin(\"ugnot\", 100),\n\t\tchain.NewCoin(\"zzfoo\", 50),\n\t))\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Clawback sweeps the full multi-denomination balance\n\tpID := commondao.CreateTreasuryClawbackProposal(cross(cur), rootID, subID)\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, pID)\n\n\tb := banker.NewReadonlyBanker()\n\tprintln(\"sub treasury:\", b.GetCoins(commondao.GetView(subID).Address()).String())\n\tprintln(\"root treasury:\", b.GetCoins(commondao.GetView(rootID).Address()).String())\n}\n\n// Output:\n// sub treasury:\n// root treasury: 100ugnot,50zzfoo\n"},{"name":"z_12_k_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_12_k_filetest\n\n// Only a council member may propose an ancestor clawback.\n//\n// The ancestry check authorizes which treasury may be swept; it says\n// nothing about who may ask. Without this gate a stranger could fill a\n// DAO's active-proposal cap with clawback items it never chose to\n// consider.\npackage z_12_k_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx, genesis council only\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1, owns the tree below\n)\n\nvar (\n\trootID uint64\n\tsubID  uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\n\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, pID)\n\tsubID = 3\n}\n\nfunc main(cur realm) {\n\t// A valid ancestry (root over sub) proposed by a non-member.\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tcommondao.CreateTreasuryClawbackProposal(cross(cur), rootID, subID)\n}\n\n// Error:\n// caller is not a council member\n"},{"name":"z_13_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_13_a_filetest\n\npackage z_13_a_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tsubID  uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubID = 3\n\n\ttesting.IssueCoins(commondao.GetView(subID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 900)))\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tpID := commondao.CreateDissolutionProposal(cross(cur), subID, \"\")\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, pID)\n\n\tview := commondao.GetView(subID)\n\tprintln(\"deleted:\", view.IsDeleted())\n\tb := banker.NewReadonlyBanker()\n\tprintln(\"sub treasury:\", b.GetCoins(view.Address()).String())\n\tprintln(\"root treasury:\", b.GetCoins(commondao.GetView(rootID).Address()).String())\n}\n\n// Output:\n// deleted: true\n// sub treasury:\n// root treasury: 900ugnot\n"},{"name":"z_13_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_13_b_filetest\n\npackage z_13_b_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.CreateDissolutionProposal(cross(cur), daoID, \"\")\n}\n\n// Error:\n// root DAO dissolution requires a valid sweep destination\n"},{"name":"z_13_c_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_13_c_filetest\n\npackage z_13_c_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tsubID  uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubID = 3\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.CreateDissolutionProposal(cross(cur), subID, owner)\n}\n\n// Error:\n// sub-DAO dissolution sweeps to the parent DAO; destination must be empty\n"},{"name":"z_13_d_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_13_d_filetest\n\npackage z_13_d_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tmidID  uint64\n\tleafID uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Mid\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tmidID = 3\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), midID, \"Leaf\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), midID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), midID, pID)\n\t}\n\tleafID = 4\n\n\ttesting.IssueCoins(commondao.GetView(leafID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 150)))\n\n\t// Dissolve the middle DAO first, orphaning the leaf\n\tpID := commondao.CreateDissolutionProposal(cross(cur), midID, \"\")\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, pID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// The leaf's dissolution proposal is hosted in the nearest live\n\t// ancestor (the root), because its parent is already dissolved\n\tpID := commondao.CreateDissolutionProposal(cross(cur), leafID, \"\")\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, pID)\n\n\tprintln(\"mid deleted:\", commondao.GetView(midID).IsDeleted())\n\tprintln(\"leaf deleted:\", commondao.GetView(leafID).IsDeleted())\n\n\t// The orphan's sweep skips the dissolved parent and lands on the\n\t// nearest LIVE ancestor. Sweeping onto the dead mid would leave the\n\t// funds usable only through a further clawback — and lost outright\n\t// once the root is dissolved too, since a deleted DAO cannot be\n\t// clawed back.\n\tb := banker.NewReadonlyBanker()\n\tprintln(\"leaf treasury:\", b.GetCoins(commondao.GetView(leafID).Address()).String())\n\tprintln(\"mid treasury (dissolved, skipped):\", b.GetCoins(commondao.GetView(midID).Address()).String())\n\tprintln(\"root treasury (nearest live ancestor):\", b.GetCoins(commondao.GetView(rootID).Address()).String())\n}\n\n// Output:\n// mid deleted: true\n// leaf deleted: true\n// leaf treasury:\n// mid treasury (dissolved, skipped):\n// root treasury (nearest live ancestor): 150ugnot\n"},{"name":"z_13_e_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_13_e_filetest\n\npackage z_13_e_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\ttesting.IssueCoins(commondao.GetView(daoID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 650)))\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tpID := commondao.CreateDissolutionProposal(cross(cur), daoID, owner)\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n\n\tview := commondao.GetView(daoID)\n\tprintln(\"deleted:\", view.IsDeleted())\n\tb := banker.NewReadonlyBanker()\n\tprintln(\"treasury:\", b.GetCoins(view.Address()).String())\n\tprintln(\"destination:\", b.GetCoins(owner).String())\n}\n\n// Output:\n// deleted: true\n// treasury:\n// destination: 650ugnot\n"},{"name":"z_13_f_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_13_f_filetest\n\npackage z_13_f_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tsubID  uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubID = 3\n\n\ttesting.IssueCoins(commondao.GetView(subID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 800)))\n\n\tfID := commondao.CreateTreasuryFreezeProposal(cross(cur), rootID, subID, true)\n\tcommondao.Vote(cross(cur), rootID, fID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, fID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// A frozen treasury does not block dissolution: the sweep sends the\n\t// funds where a clawback would put them\n\tpID := commondao.CreateDissolutionProposal(cross(cur), subID, \"\")\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, pID)\n\n\tview := commondao.GetView(subID)\n\tprintln(\"deleted:\", view.IsDeleted())\n\tprintln(\"frozen:\", view.IsTreasuryFrozen())\n\tb := banker.NewReadonlyBanker()\n\tprintln(\"sub treasury:\", b.GetCoins(view.Address()).String())\n\tprintln(\"root treasury:\", b.GetCoins(commondao.GetView(rootID).Address()).String())\n}\n\n// Output:\n// deleted: true\n// frozen: true\n// sub treasury:\n// root treasury: 800ugnot\n"},{"name":"z_13_g_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_13_g_filetest\n\npackage z_13_g_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID  uint64\n\tsubID   uint64\n\tspendID uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubID = 3\n\n\ttesting.IssueCoins(commondao.GetView(subID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 700)))\n\n\t// Pass a spend on the sub-DAO but do not execute it\n\tspendID = commondao.CreateTreasurySpendProposal(cross(cur), subID, owner, \"ugnot\", 700)\n\tcommondao.Vote(cross(cur), subID, spendID, pdao.ChoiceYes, \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Dissolution dismisses the passed-but-unexecuted spend and sweeps the\n\t// full balance to the parent; the recipient never receives anything\n\tdID := commondao.CreateDissolutionProposal(cross(cur), subID, \"\")\n\tcommondao.Vote(cross(cur), rootID, dID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, dID)\n\n\tp, _ := commondao.GetView(subID).GetProposal(spendID)\n\tprintln(\"spend:\", string(p.Status()))\n\tprintln(\"reason:\", p.StatusReason())\n\tb := banker.NewReadonlyBanker()\n\tprintln(\"sub treasury:\", b.GetCoins(commondao.GetView(subID).Address()).String())\n\tprintln(\"root treasury:\", b.GetCoins(commondao.GetView(rootID).Address()).String())\n\tprintln(\"recipient:\", b.GetCoins(owner).String())\n}\n\n// Output:\n// spend: dismissed\n// reason: DAO dissolved\n// sub treasury:\n// root treasury: 700ugnot\n// recipient:\n"},{"name":"z_14_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_14_a_filetest\n\npackage z_14_a_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tsubID  uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubID = 3\n\n\ttesting.IssueCoins(commondao.GetView(subID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 100)))\n\n\tfID := commondao.CreateTreasuryFreezeProposal(cross(cur), rootID, subID, true)\n\tcommondao.Vote(cross(cur), rootID, fID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, fID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tprintln(\"frozen:\", commondao.GetView(subID).IsTreasuryFrozen())\n\n\t// The ancestor unfreezes the treasury, re-enabling spends\n\tuID := commondao.CreateTreasuryFreezeProposal(cross(cur), rootID, subID, false)\n\tcommondao.Vote(cross(cur), rootID, uID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, uID)\n\tprintln(\"frozen:\", commondao.GetView(subID).IsTreasuryFrozen())\n\n\tsID := commondao.CreateTreasurySpendProposal(cross(cur), subID, owner, \"ugnot\", 100)\n\tcommondao.Vote(cross(cur), subID, sID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), subID, sID)\n\tprintln(\"recipient:\", banker.NewReadonlyBanker().GetCoins(owner).String())\n}\n\n// Output:\n// frozen: true\n// frozen: false\n// recipient: 100ugnot\n"},{"name":"z_14_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_14_b_filetest\n\npackage z_14_b_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tsubID  uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubID = 3\n\n\tfID := commondao.CreateTreasuryFreezeProposal(cross(cur), rootID, subID, true)\n\tcommondao.Vote(cross(cur), rootID, fID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, fID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// The frozen DAO cannot target itself: only a proper ancestor unfreezes\n\tcommondao.CreateTreasuryFreezeProposal(cross(cur), subID, subID, false)\n}\n\n// Error:\n// a DAO cannot target itself\n"},{"name":"z_14_c_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_14_c_filetest\n\npackage z_14_c_filetest\n\nimport (\n\t\"chain\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tmidID  uint64\n\tleafID uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Mid\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tmidID = 3\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), midID, \"Leaf\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), midID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), midID, pID)\n\t}\n\tleafID = 4\n\n\ttesting.IssueCoins(commondao.GetView(leafID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 100)))\n\n\t// The root (grandparent) freezes the leaf, then only the middle DAO\n\t// is dissolved. The root remains a live proper ancestor.\n\tfID := commondao.CreateTreasuryFreezeProposal(cross(cur), rootID, leafID, true)\n\tcommondao.Vote(cross(cur), rootID, fID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, fID)\n\n\tdID := commondao.CreateDissolutionProposal(cross(cur), midID, \"\")\n\tcommondao.Vote(cross(cur), rootID, dID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, dID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Self-unfreeze is still forbidden: a live proper ancestor (the root)\n\t// remains, so the orphan-rescue path does not open. The rescue\n\t// requires ALL proper ancestors dissolved, not just the parent.\n\tcommondao.CreateTreasuryFreezeProposal(cross(cur), leafID, leafID, false)\n}\n\n// Error:\n// a DAO cannot target itself\n"},{"name":"z_14_d_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_14_d_filetest\n\npackage z_14_d_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tmidID  uint64\n\tleafID uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Mid\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tmidID = 3\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), midID, \"Leaf\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), midID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), midID, pID)\n\t}\n\tleafID = 4\n\n\t// Dissolve the leaf's entire ancestor chain\n\tdID := commondao.CreateDissolutionProposal(cross(cur), midID, \"\")\n\tcommondao.Vote(cross(cur), rootID, dID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, dID)\n\n\tdID = commondao.CreateDissolutionProposal(cross(cur), rootID, owner)\n\tcommondao.Vote(cross(cur), rootID, dID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, dID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Even a full orphan may only UNFREEZE itself, never freeze itself:\n\t// the rescue branch is guarded on !frozen.\n\tcommondao.CreateTreasuryFreezeProposal(cross(cur), leafID, leafID, true)\n}\n\n// Error:\n// a DAO cannot target itself\n"},{"name":"z_14_e_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_14_e_filetest\n\npackage z_14_e_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tmidID  uint64\n\tleafID uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Mid\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tmidID = 3\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), midID, \"Leaf\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), midID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), midID, pID)\n\t}\n\tleafID = 4\n\n\ttesting.IssueCoins(commondao.GetView(leafID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 100)))\n\n\t// The middle DAO freezes the leaf, then the root dissolves the middle\n\tfID := commondao.CreateTreasuryFreezeProposal(cross(cur), midID, leafID, true)\n\tcommondao.Vote(cross(cur), midID, fID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), midID, fID)\n\n\tdID := commondao.CreateDissolutionProposal(cross(cur), midID, \"\")\n\tcommondao.Vote(cross(cur), rootID, dID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, dID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Freeze state lives on the target: any live proper ancestor can\n\t// unfreeze it after the freezing ancestor is gone\n\tuID := commondao.CreateTreasuryFreezeProposal(cross(cur), rootID, leafID, false)\n\tcommondao.Vote(cross(cur), rootID, uID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, uID)\n\tprintln(\"frozen:\", commondao.GetView(leafID).IsTreasuryFrozen())\n\n\tsID := commondao.CreateTreasurySpendProposal(cross(cur), leafID, owner, \"ugnot\", 100)\n\tcommondao.Vote(cross(cur), leafID, sID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), leafID, sID)\n\tprintln(\"recipient:\", banker.NewReadonlyBanker().GetCoins(owner).String())\n}\n\n// Output:\n// frozen: false\n// recipient: 100ugnot\n"},{"name":"z_14_f_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_14_f_filetest\n\npackage z_14_f_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tmidID  uint64\n\tleafID uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Mid\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tmidID = 3\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), midID, \"Leaf\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), midID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), midID, pID)\n\t}\n\tleafID = 4\n\n\ttesting.IssueCoins(commondao.GetView(leafID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 300)))\n\n\t// Freeze the leaf, then dissolve its whole ancestor chain\n\tfID := commondao.CreateTreasuryFreezeProposal(cross(cur), rootID, leafID, true)\n\tcommondao.Vote(cross(cur), rootID, fID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, fID)\n\n\tdID := commondao.CreateDissolutionProposal(cross(cur), midID, \"\")\n\tcommondao.Vote(cross(cur), rootID, dID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, dID)\n\n\tdID = commondao.CreateDissolutionProposal(cross(cur), rootID, owner)\n\tcommondao.Vote(cross(cur), rootID, dID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, dID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Orphan rescue: every proper ancestor is dissolved, so the freezing\n\t// authority class is extinct and the leaf's own council may unfreeze\n\t// itself, restoring access to its funds\n\tuID := commondao.CreateTreasuryFreezeProposal(cross(cur), leafID, leafID, false)\n\tcommondao.Vote(cross(cur), leafID, uID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), leafID, uID)\n\tprintln(\"frozen:\", commondao.GetView(leafID).IsTreasuryFrozen())\n\n\tsID := commondao.CreateTreasurySpendProposal(cross(cur), leafID, owner, \"ugnot\", 300)\n\tcommondao.Vote(cross(cur), leafID, sID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), leafID, sID)\n\tprintln(\"recipient:\", banker.NewReadonlyBanker().GetCoins(owner).String())\n}\n\n// Output:\n// frozen: false\n// recipient: 300ugnot\n"},{"name":"z_14_g_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_14_g_filetest\n\npackage z_14_g_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\n// Treasury freeze passes by SIMPLE majority. A 5-member ancestor council\n// splitting 3 YES / 2 NO clears a simple majority (2*3 \u003e 5) but not a\n// supermajority (3*3 \u003c 2*5), so under the correct Simple threshold the\n// target is frozen; a mutated Super threshold would dismiss it.\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\tmoul  = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\") // @moul\n\tmF    = address(\"g1cyh9qm4y43w38gfk77qxczrhqj2asdr8l7uk54\")\n\tmG    = address(\"g1x95kxqpwvqjf98qpkvsay7tppkh6zs9fr7wwda\")\n)\n\nvar (\n\trootID uint64\n\tsubID  uint64\n\tpID    uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tmembers := strings.Join([]string{owner.String(), moul.String(), mF.String(), mG.String()}, \"\\n\")\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", members)\n\n\tsp := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tcommondao.Vote(cross(cur), rootID, sp, pdao.ChoiceYes, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Vote(cross(cur), rootID, sp, pdao.ChoiceYes, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(moul))\n\tcommondao.Vote(cross(cur), rootID, sp, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, sp)\n\tsubID = 3\n\n\t// Freeze proposal, hosted in the ancestor (root), 3 YES / 2 NO.\n\tpID = commondao.CreateTreasuryFreezeProposal(cross(cur), rootID, subID, true)\n\ttesting.SetRealm(testing.NewUserRealm(mF))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceNo, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(mG))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceNo, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(moul))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SkipHeights(121000)\n\n\tcommondao.Execute(cross(cur), rootID, pID)\n\n\tp, _ := commondao.GetView(rootID).GetProposal(pID)\n\tprintln(\"status:\", string(p.Status()))\n\tprintln(\"frozen:\", commondao.GetView(subID).IsTreasuryFrozen())\n}\n\n// Output:\n// status: executed\n// frozen: true\n"},{"name":"z_14_h_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_14_h_filetest\n\npackage z_14_h_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.CreateTreasuryFreezeProposal(cross(cur), daoID, 404, true)\n}\n\n// Error:\n// DAO not found\n"},{"name":"z_14_i_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_14_i_filetest\n\n// Only a council member may propose an ancestor treasury freeze.\n//\n// Freeze is the containment lever an ancestor holds over a descendant,\n// so who may put it on the agenda matters as much as who may pass it.\npackage z_14_i_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx, genesis council only\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1, owns the tree below\n)\n\nvar (\n\trootID uint64\n\tsubID  uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\n\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, pID)\n\tsubID = 3\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tcommondao.CreateTreasuryFreezeProposal(cross(cur), rootID, subID, true)\n}\n\n// Error:\n// caller is not a council member\n"},{"name":"z_15_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_15_a_filetest\n\npackage z_15_a_filetest\n\nimport (\n\t\"chain\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoA uint64\n\tdaoB uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoA = commondao.New(cross(cur), \"A\", \"Purpose\", \"\", \"\")\n\tdaoB = commondao.New(cross(cur), \"B\", \"Purpose\", \"\", \"\")\n}\n\nfunc main() {\n\ta := commondao.GetView(daoA).Address()\n\tb := commondao.GetView(daoB).Address()\n\n\tprintln(\"valid:\", a.IsValid() \u0026\u0026 b.IsValid())\n\tprintln(\"distinct:\", a != b)\n\n\t// The address is a pure derivation from the realm path and DAO ID\n\tderived := chain.DerivePkgSubAddr(\"gno.land/r/nt/commondao/v0\", \"dao/\"+strconv.FormatUint(daoA, 10))\n\tprintln(\"derived:\", a == derived)\n\n\t// The genesis DAO carries a derived address too\n\tg := commondao.GetView(1).Address()\n\tprintln(\"genesis:\", g == chain.DerivePkgSubAddr(\"gno.land/r/nt/commondao/v0\", \"dao/1\"))\n}\n\n// Output:\n// valid: true\n// distinct: true\n// derived: true\n// genesis: true\n"},{"name":"z_16_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_16_a_filetest\n\npackage z_16_a_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\t// Listing defaults off\n\tprintln(\"default:\", commondao.IsListed(daoID))\n\n\t// A council member lists the DAO\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tcommondao.SetListed(cross(cur), daoID, true)\n\tprintln(\"after list:\", commondao.IsListed(daoID))\n\n\t// ...and can unlist it\n\tcommondao.SetListed(cross(cur), daoID, false)\n\tprintln(\"after unlist:\", commondao.IsListed(daoID))\n}\n\n// Output:\n// default: false\n// after list: true\n// after unlist: false\n"},{"name":"z_16_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_16_b_filetest\n\npackage z_16_b_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner  = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser   = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\tnonMbr = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\") // @moul\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\t// A non-council member cannot change listing\n\ttesting.SetRealm(testing.NewUserRealm(nonMbr))\n\tcommondao.SetListed(cross(cur), daoID, true)\n}\n\n// Error:\n// caller is not a council member\n"},{"name":"z_16_c_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_16_c_filetest\n\npackage z_16_c_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\tcommondao.SetListed(cross(cur), daoID, true)\n\n\t// Dissolve the DAO through a passed proposal\n\tpID := commondao.CreateDissolutionProposal(cross(cur), daoID, user)\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n}\n\nfunc main() {\n\t// Dissolution auto-unlists the DAO from the home index.\n\tprintln(\"listed before dissolve was true; after dissolve:\", commondao.IsListed(daoID))\n}\n\n// Output:\n// listed before dissolve was true; after dissolve: false\n"},{"name":"z_16_d_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_16_d_filetest\n\npackage z_16_d_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tlistedID := commondao.New(cross(cur), \"Shown\", \"Purpose\", \"\", \"\")\n\tcommondao.New(cross(cur), \"Hidden\", \"Purpose\", \"\", \"\")\n\n\tcommondao.SetListed(cross(cur), listedID, true)\n}\n\nfunc main() {\n\t// The home index shows only listed DAOs: \"Shown\" appears, \"Hidden\"\n\t// (default unlisted) does not.\n\tprintln(commondao.Render(\"\"))\n}\n\n// Output:\n// # Common DAO\n// ---\n// This realm can be used to create CommonDAO instances based on [commondao](/p/nt/commondao/v0/) package.\n//\n// Here is a list of some of the DAOs that were created:\n//\n// - [Shown](/r/nt/commondao/v0:2)\n// - [Common DAO](/r/nt/commondao/v0:1)\n"},{"name":"z_16_e_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_16_e_filetest\n\npackage z_16_e_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\tpID := commondao.CreateDissolutionProposal(cross(cur), daoID, user)\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// A dissolved DAO cannot be listed.\n\tcommondao.SetListed(cross(cur), daoID, true)\n}\n\n// Error:\n// DAO is deleted\n"},{"name":"z_16_f_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_16_f_filetest\n\npackage z_16_f_filetest\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\t// Dissolve the root (root dissolution names a destination).\n\tpID := commondao.CreateDissolutionProposal(cross(cur), daoID, owner)\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n}\n\nfunc main() {\n\t// A dissolved root has no live ancestor, so its page carries both the\n\t// dissolved banner and the unrecoverable-deposit warning.\n\tprintln(commondao.Render(strconv.FormatUint(daoID, 10)))\n}\n\n// Output:\n//\n// \u003e ⚠ This DAO has been dissolved\n//\n//\n// \u003e ⚠ No live ancestor DAO remains: coins sent to this treasury address can no longer be recovered.\n//\n// # Foo\n// **Purpose:** Purpose\n//\n// [View Proposals](/r/nt/commondao/v0:2/proposals) • [View Settings](/r/nt/commondao/v0:2/settings)\n//\n// ---\n// | Council |\n// | --- |\n// | g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 |\n//\n//\n// ## Treasury\n// - Address: g1vpah5sslxspfdvj9vk07rukek327dzmtxqkmk2\n// - Balance: (empty)\n"},{"name":"z_16_g_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_16_g_filetest\n\npackage z_16_g_filetest\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tleafID uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\n\t// A sub-DAO of the (still-live) root.\n\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Leaf\", \"Purpose\", \"\", string(user))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, pID)\n\tleafID = 3\n\n\t// Dissolve the leaf (the proposal is hosted in its parent, the root).\n\tdID := commondao.CreateDissolutionProposal(cross(cur), leafID, \"\")\n\tcommondao.Vote(cross(cur), rootID, dID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, dID)\n}\n\nfunc main() {\n\t// The leaf is dissolved but its root is alive, so the page shows the\n\t// dissolved banner WITHOUT the unrecoverable-treasury warning: a live\n\t// proper ancestor can still claw back the leaf's funds. This pins the\n\t// !hasLiveProperAncestor gate's negative branch.\n\tprintln(commondao.Render(strconv.FormatUint(leafID, 10)))\n}\n\n// Output:\n//\n// \u003e ⚠ This DAO has been dissolved\n//\n// # Leaf\n// **Purpose:** Purpose\n//\n// [View Proposals](/r/nt/commondao/v0:3/proposals) • [View Settings](/r/nt/commondao/v0:3/settings) • [Go to Parent DAO](/r/nt/commondao/v0:2)\n//\n// ---\n// | Council |\n// | --- |\n// | g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 |\n//\n//\n// ## Treasury\n// - Address: g17pr3grpaag8ketn84dl2y0nncef6u3jw8ca9gl\n// - Balance: (empty)\n"},{"name":"z_17_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_17_a_filetest\n\npackage z_17_a_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner  = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser   = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\trescue = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\") // @moul\n)\n\nvar (\n\trootID uint64\n\tsubID  uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\n\t// A sub-DAO whose only council member is `user`\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubID = 3\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// The parent (root), as a proper ancestor, adds a new member to the\n\t// sub-DAO's council and removes the original — the spec's rescue path\n\t// (:1531-1532). Hosted and voted in the root at supermajority.\n\tpID := commondao.CreateAncestorCouncilUpdateProposal(cross(cur), rootID, subID, string(rescue), string(user))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, pID)\n\n\tview := commondao.GetView(subID)\n\tcouncil := view.Council()\n\tprintln(\"size:\", council.Size())\n\tprintln(\"has rescue:\", council.Has(rescue))\n\tprintln(\"has old:\", council.Has(user))\n}\n\n// Output:\n// size: 1\n// has rescue: true\n// has old: false\n"},{"name":"z_17_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_17_b_filetest\n\npackage z_17_b_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// A DAO cannot modify its own council through the ancestor path\n\t// (self-mutation goes through CreateCouncilUpdateProposal instead).\n\tcommondao.CreateAncestorCouncilUpdateProposal(cross(cur), daoID, daoID, string(owner), \"\")\n}\n\n// Error:\n// a DAO cannot target itself\n"},{"name":"z_17_c_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_17_c_filetest\n\npackage z_17_c_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tsubID  uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubID = 3\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// An ancestor update that would empty the descendant's council fails\n\t// cleanly (the package would-empty guard applies through the ancestor\n\t// path too): the proposal ends Failed and the council is unchanged.\n\tpID := commondao.CreateAncestorCouncilUpdateProposal(cross(cur), rootID, subID, \"\", string(user))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, pID)\n\n\tp, _ := commondao.GetView(rootID).GetProposal(pID)\n\tprintln(\"status:\", string(p.Status()))\n\tprintln(\"reason:\", p.StatusReason())\n\tprintln(\"sub council size:\", commondao.GetView(subID).Council().Size())\n}\n\n// Output:\n// status: failed\n// reason: council update would remove every council member\n// sub council size: 1\n"},{"name":"z_18_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_18_a_filetest\n\npackage z_18_a_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// A Charter requires a purpose: an empty purpose is rejected.\n\tcommondao.New(cross(cur), \"Foo\", \"\", \"\", \"\")\n}\n\n// Error:\n// DAO purpose is empty\n"},{"name":"z_18_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_18_b_filetest\n\npackage z_18_b_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Purpose is capped at 250 characters.\n\tcommondao.New(cross(cur), \"Foo\", strings.Repeat(\"A\", 251), \"\", \"\")\n}\n\n// Error:\n// DAO purpose is too long, max length is 250 characters\n"},{"name":"z_18_c_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_18_c_filetest\n\npackage z_18_c_filetest\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\t// The Purpose is user-controlled Charter text: markdown metacharacters\n\t// must render escaped, never as live markup.\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"*Evil* [x](https://evil.example) # H1\", \"\", \"\")\n}\n\nfunc main() {\n\tprintln(commondao.Render(strconv.FormatUint(daoID, 10)))\n}\n\n// Output:\n// # Foo\n// **Purpose:** \\*Evil\\* \\[x\\]\\(https://evil\\.example\\) \\# H1\n//\n// [View Proposals](/r/nt/commondao/v0:2/proposals) • [View Settings](/r/nt/commondao/v0:2/settings)\n//\n// ---\n// | Council |\n// | --- |\n// | g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 |\n//\n//\n// ## Treasury\n// - Address: g1vpah5sslxspfdvj9vk07rukek327dzmtxqkmk2\n// - Balance: (empty)\n// ## Create Proposal\n// These are the proposal supported by this DAO:\n//\n// \u003cgno-columns\u003e\n// [General Proposal](/r/nt/commondao/v0$help\u0026func=CreateTextProposal\u0026body=\u0026daoID=2\u0026title=\u0026votingDays=7)\n//\n// This type of proposal is also known as text proposal which can be used for example to get consensus on initiatives without actually making any change on-chain.\n//\n//\n// \u003cgno-columns-sep\u003e\n// [Update Council](/r/nt/commondao/v0$help\u0026func=CreateCouncilUpdateProposal\u0026daoID=2\u0026newMembers=\u0026removeMembers=)\n//\n// This type of proposal can be used to add new council members to this DAO and also to remove existing ones.\n//\n// A single proposal allows new council members to be added and any number of existing ones removed within the same proposal.\n//\n//\n// \u003cgno-columns-sep\u003e\n// [Ancestor Council Update](/r/nt/commondao/v0$help\u0026func=CreateAncestorCouncilUpdateProposal\u0026daoID=2\u0026newMembers=\u0026removeMembers=\u0026targetID=)\n//\n// This type of proposal lets this DAO, as an ancestor, add or remove council members of one of its descendant DAOs — the rescue path for a descendant whose council is stuck or empty.\n//\n//\n// \u003c/gno-columns\u003e\n// \u003cgno-columns\u003e\n// [Dissolve DAO](/r/nt/commondao/v0$help\u0026func=CreateDissolutionProposal\u0026daoID=2\u0026destination=)\n//\n// This type of proposal can be used to dissolve DAOs and SubDAOs.\n//\n// Dissolving a DAO can't be undone, once the dissolution proposal passes and is executed DAO will be readonly.\n//\n//\n// \u003cgno-columns-sep\u003e\n// [Treasury Spend](/r/nt/commondao/v0$help\u0026func=CreateTreasurySpendProposal\u0026amount=\u0026daoID=2\u0026denom=ugnot\u0026to=)\n//\n// This type of proposal sends coins from the DAO's own treasury when it passes and is executed.\n//\n//\n// \u003cgno-columns-sep\u003e\n// [Treasury Clawback](/r/nt/commondao/v0$help\u0026func=CreateTreasuryClawbackProposal\u0026daoID=2\u0026targetID=)\n//\n// This type of proposal sweeps a descendant DAO's treasury to the descendant's parent DAO.\n//\n//\n// \u003c/gno-columns\u003e\n// \u003cgno-columns\u003e\n// [Treasury Freeze](/r/nt/commondao/v0$help\u0026func=CreateTreasuryFreezeProposal\u0026daoID=2\u0026frozen=true\u0026targetID=)\n//\n// This type of proposal freezes or unfreezes a descendant DAO's treasury. While frozen, no funds can leave the treasury.\n//\n//\n// \u003cgno-columns-sep\u003e\n// [New SubDAO](/r/nt/commondao/v0$help\u0026func=CreateSubDAOProposal\u0026daoID=2\u0026description=\u0026members=\u0026name=\u0026purpose=)\n//\n// This type of proposal is used to create SubDAOs, which are used to create tree based DAOs.\n//\n//\n// \u003cgno-columns-sep\u003e\n// [Register Proposal Kind](/r/nt/commondao/v0$help\u0026func=CreateRegisterKindProposal\u0026daoID=2\u0026kindName=) • [Deregister Proposal Kind](/r/nt/commondao/v0$help\u0026func=CreateDeregisterKindProposal\u0026daoID=2\u0026kindName=)\n//\n// This type of proposal registers one of the realm's catalog proposal kinds on this DAO by name, or deregisters a kind. Deregistering a kind blocks new proposals of that kind while in-flight ones still vote and execute. The manage-kinds kind itself cannot be deregistered.\n//\n//\n// \u003c/gno-columns\u003e\n// \u003cgno-columns\u003e\n// [Amend Bylaws](/r/nt/commondao/v0$help\u0026func=CreateAmendBylawsProposal\u0026daoID=2\u0026payload=)\n//\n// This type of proposal adds, amends or removes one of the DAO's bylaws documents with a diff patch pinned to the current document text (the mandates folder is reserved: mandates are set from above, not by the council). Build the payload with the AmendBylawsPayload query function.\n//\n//\n// \u003c/gno-columns\u003e\n"},{"name":"z_19_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_19_a_filetest\n\npackage z_19_a_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Single-member council: one YES decides any proposal immediately\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\t// Governance-deregister the text kind\n\tpID := commondao.CreateDeregisterKindProposal(cross(cur), daoID, \"text\")\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// The text kind is deregistered while every other kind still works\n\tprintln(\"text registered:\", commondao.HasProposalKind(daoID, \"text\"))\n\tpID := commondao.CreateCouncilUpdateProposal(cross(cur), daoID, string(owner), \"\")\n\tprintln(\"council update created:\", pID)\n\n\t// Creating a proposal of the deregistered kind is rejected\n\tcommondao.CreateTextProposal(cross(cur), daoID, \"Title\", \"Body\", 0)\n}\n\n// Output:\n// text registered: false\n// council update created: 2\n\n// Error:\n// proposal kind not found\n"},{"name":"z_19_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_19_b_filetest\n\npackage z_19_b_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoID uint64\n\tpID   uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\t// A text proposal is created while its kind is still registered\n\tpID = commondao.CreateTextProposal(cross(cur), daoID, \"Title\", \"Body\", 0)\n\n\t// Governance-deregister the text kind after the proposal exists\n\tgID := commondao.CreateDeregisterKindProposal(cross(cur), daoID, \"text\")\n\tcommondao.Vote(cross(cur), daoID, gID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, gID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// The kind registry is read only at Propose, so the in-flight proposal\n\t// created before the kind was deregistered still votes and executes\n\tprintln(\"text registered:\", commondao.HasProposalKind(daoID, \"text\"))\n\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n\n\tp, _ := commondao.GetView(daoID).GetProposal(pID)\n\tprintln(\"status:\", string(p.Status()))\n}\n\n// Output:\n// text registered: false\n// status: executed\n"},{"name":"z_19_c_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_19_c_filetest\n\npackage z_19_c_filetest\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\t// Governance-deregister the text kind: new text proposals are blocked\n\t// (see z_19_a for the terminal rejection)\n\tpID := commondao.CreateDeregisterKindProposal(cross(cur), daoID, \"text\")\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tprintln(\"after deregister:\", commondao.HasProposalKind(daoID, \"text\"))\n\n\t// The DAO page drops the deregistered kind's create link\n\tout := commondao.Render(strconv.FormatUint(daoID, 10))\n\tprintln(\"create link after deregister:\", strings.Contains(out, \"CreateTextProposal\"))\n\n\t// ...and the settings kinds row drops the kind name (sorted row would\n\t// read \"subdao, text, treasury\\-clawback\" when registered)\n\tout = commondao.Render(strconv.FormatUint(daoID, 10) + \"/settings\")\n\tprintln(\"settings row lists text after deregister:\", strings.Contains(out, \"subdao, text\"))\n\n\t// Re-register the kind by name through a second governance proposal\n\tpID := commondao.CreateRegisterKindProposal(cross(cur), daoID, \"text\")\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n\tprintln(\"after re-register:\", commondao.HasProposalKind(daoID, \"text\"))\n\n\t// ...and shows it again once the kind is re-registered\n\tout = commondao.Render(strconv.FormatUint(daoID, 10))\n\tprintln(\"create link after re-register:\", strings.Contains(out, \"CreateTextProposal\"))\n\n\t// Text proposals can be created again\n\ttID := commondao.CreateTextProposal(cross(cur), daoID, \"Title\", \"Body\", 0)\n\tprintln(\"created:\", tID)\n}\n\n// Output:\n// after deregister: false\n// create link after deregister: false\n// settings row lists text after deregister: false\n// after re-register: true\n// create link after re-register: true\n// created: 3\n"},{"name":"z_19_d_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_19_d_filetest\n\npackage z_19_d_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\n// Manage-kinds proposals are decided by SUPERMAJORITY: with a 5-member\n// council, 3 YES votes (a simple majority) settle nothing (3*3 \u003c 2*5), so\n// the proposal stays active and cannot be executed before its deadline. A\n// mutant deciding it by simple majority would pass it early here.\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\tmoul  = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\") // @moul\n\tmemD  = address(\"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\") // @test2\n\tmemE  = address(\"g1cyh9qm4y43w38gfk77qxczrhqj2asdr8l7uk54\")\n)\n\nvar (\n\tdaoID uint64\n\tpID   uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Council is {user, owner, moul, memD, memE}\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tmembers := strings.Join([]string{owner.String(), moul.String(), memD.String(), memE.String()}, \"\\n\")\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", members)\n\n\tpID = commondao.CreateDeregisterKindProposal(cross(cur), daoID, \"text\")\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(moul))\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n}\n\nfunc main(cur realm) {\n\t// 3 of 5 YES: passed under a simple majority, undecided under the\n\t// required supermajority\n\tp, _ := commondao.GetView(daoID).GetProposal(pID)\n\tif p.Status() != pdao.StatusActive {\n\t\tpanic(\"expected the proposal to remain active\")\n\t}\n\n\t// An undecided proposal cannot be executed before its voting deadline\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tcommondao.Execute(cross(cur), daoID, pID)\n}\n\n// Error:\n// voting deadline not met\n"},{"name":"z_19_e_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_19_e_filetest\n\npackage z_19_e_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner    = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser     = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\tstranger = address(\"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\") // @test2\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\t// Only council members can propose kind changes\n\ttesting.SetRealm(testing.NewUserRealm(stranger))\n\tcommondao.CreateDeregisterKindProposal(cross(cur), daoID, \"text\")\n}\n\n// Error:\n// caller is not a council member\n"},{"name":"z_19_f_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_19_f_filetest\n\npackage z_19_f_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\t// Self-brick guard: deregistering the manage-kinds kind itself would\n\t// leave the DAO unable to ever manage its kinds, so it fails at creation\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tcommondao.CreateDeregisterKindProposal(cross(cur), daoID, \"manage-kinds\")\n}\n\n// Error:\n// the manage-kinds kind cannot be deregistered\n"},{"name":"z_1_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_1_a_filetest\n\npackage z_1_a_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tcommondao.Invite(cross(cur), user)\n\n\tprintln(commondao.IsInvited(user))\n}\n\n// Output:\n// true\n"},{"name":"z_1_b_filetest.gno","body":"package main\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nfunc main() {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tprintln(commondao.IsInvited(user))\n}\n\n// Output:\n// false\n"},{"name":"z_1_c_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_1_c_filetest\n\npackage z_1_c_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\tuser    = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\tinvitee = address(\"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\") // @test2\n)\n\nfunc main(cur realm) {\n\t// Call as a user which is not a Common DAO member\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.Invite(cross(cur), invitee)\n}\n\n// Error:\n// unauthorized\n"},{"name":"z_20_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_20_a_filetest\n\npackage z_20_a_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoID uint64\n\tran   bool\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Single-member council: one YES decides any proposal immediately\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\t// The execution kind is opt-in: register it by name through governance first.\n\tpID := commondao.CreateRegisterKindProposal(cross(cur), daoID, \"execution\")\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tprintln(\"execution registered:\", commondao.HasProposalKind(daoID, \"execution\"))\n\n\t// The closure is authored in this persistent realm, so it survives\n\t// Propose-\u003eExecute. It sets a package var so execution is observable.\n\tpID := commondao.CreateExecutionProposal(cross(cur), daoID, \"Run it\", \"Body\", func(_ int, _ realm) error {\n\t\tran = true\n\t\treturn nil\n\t})\n\tprintln(\"created:\", pID)\n\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n\tprintln(\"closure ran:\", ran)\n}\n\n// Output:\n// execution registered: true\n// created: 2\n// closure ran: true\n"},{"name":"z_20_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_20_b_filetest\n\npackage z_20_b_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// The execution kind is NOT seeded on new DAOs. Creating an execution\n\t// proposal before the DAO registers the kind is refused by the opt-in\n\t// register-gate (assertKindRegistered). Removing that gate would let this\n\t// call reach Propose, which rejects the unregistered kind with a\n\t// different message (\"proposal kind not found\") — this golden pins the\n\t// gate.\n\tprintln(\"execution registered:\", commondao.HasProposalKind(daoID, \"execution\"))\n\tcommondao.CreateExecutionProposal(cross(cur), daoID, \"Run it\", \"Body\", func(_ int, _ realm) error {\n\t\treturn nil\n\t})\n}\n\n// Output:\n// execution registered: false\n\n// Error:\n// proposal kind is not registered: execution\n"},{"name":"z_20_c_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_20_c_filetest\n\npackage z_20_c_filetest\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\tpID := commondao.CreateRegisterKindProposal(cross(cur), daoID, \"execution\")\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// The execution kind's title and body are raw, user-supplied text\n\t// (executionDef, a package type that cannot implement the realm's\n\t// trustedMarkdownBody marker). The renderer must escape both so\n\t// markdown metacharacters render as text, never as markup.\n\tpID := commondao.CreateExecutionProposal(\n\t\tcross(cur),\n\t\tdaoID,\n\t\t\"*Pwn* # H1\",\n\t\t\"[link](https://evil.example) # Injected\",\n\t\tfunc(_ int, _ realm) error { return nil },\n\t)\n\n\tout := commondao.Render(strconv.FormatUint(daoID, 10) + \"/proposals/\" + strconv.FormatUint(pID, 10))\n\n\t// Escaped forms are present; raw markup is not.\n\tprintln(\"title escaped:\", strings.Contains(out, `\\*Pwn\\* \\# H1`))\n\tprintln(\"body escaped:\", strings.Contains(out, `\\[link\\]\\(https://evil\\.example\\) \\# Injected`))\n\tprintln(\"raw H1 injected:\", strings.Contains(out, \"\\n# Injected\"))\n\n\t// The council is told the proposal runs code it cannot read; the\n\t// proposer's own prose must never be the only thing on the page.\n\tprintln(\"arbitrary-code disclosure shown:\", strings.Contains(out, \"runs arbitrary code with the DAO's own authority\"))\n}\n\n// Output:\n// title escaped: true\n// body escaped: true\n// raw H1 injected: false\n// arbitrary-code disclosure shown: true\n"},{"name":"z_20_d_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_20_d_filetest\n\npackage z_20_d_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Single-member council: one YES decides any proposal immediately.\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Deregister-by-name round trip through the permanent manage-kinds kind:\n\t// the text kind is seeded, so a supermajority deregister removes it and\n\t// HasProposalKind flips to false. Deregistering blocks only new proposals\n\t// of the kind; the registry is read at Propose time.\n\tprintln(\"text registered before:\", commondao.HasProposalKind(daoID, \"text\"))\n\n\tpID := commondao.CreateDeregisterKindProposal(cross(cur), daoID, \"text\")\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n\tprintln(\"text registered after:\", commondao.HasProposalKind(daoID, \"text\"))\n\n\t// A catalog kind deregistered by name can be re-registered by name: the\n\t// manage-kinds kind is never bricked, so the kind set stays governable.\n\tpID = commondao.CreateRegisterKindProposal(cross(cur), daoID, \"text\")\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n\tprintln(\"text re-registered:\", commondao.HasProposalKind(daoID, \"text\"))\n}\n\n// Output:\n// text registered before: true\n// text registered after: false\n// text re-registered: true\n"},{"name":"z_20_e_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_20_e_filetest\n\npackage z_20_e_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// No-op register: the text kind is already seeded, so a council vote to\n\t// register it again is rejected at creation (a vote must be about a real\n\t// change).\n\tcommondao.CreateRegisterKindProposal(cross(cur), daoID, \"text\")\n}\n\n// Error:\n// proposal kind is already registered\n"},{"name":"z_20_f_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_20_f_filetest\n\npackage z_20_f_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// No-op deregister: the execution kind is opt-in and not seeded, so a\n\t// council vote to deregister an absent kind is rejected at creation.\n\tcommondao.CreateDeregisterKindProposal(cross(cur), daoID, \"execution\")\n}\n\n// Error:\n// proposal kind is not registered: execution\n"},{"name":"z_20_g_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_20_g_filetest\n\npackage z_20_g_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tsubID  uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubID = 3\n\n\t// Fund the sub-DAO and enable the execution kind on it.\n\ttesting.IssueCoins(commondao.GetView(subID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 500)))\n\t{\n\t\tpID := commondao.CreateRegisterKindProposal(cross(cur), subID, \"execution\")\n\t\tcommondao.Vote(cross(cur), subID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), subID, pID)\n\t}\n\n\t// The ancestor freezes the sub-DAO treasury.\n\tfID := commondao.CreateTreasuryFreezeProposal(cross(cur), rootID, subID, true)\n\tcommondao.Vote(cross(cur), rootID, fID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, fID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// The sub-DAO is frozen by a proper ancestor. Freeze means no funds can\n\t// leave, so an execution proposal that would drain the sub's own treasury\n\t// is refused at CREATE time (fail-fast), defeating any attempt to bypass\n\t// the ancestor's freeze through arbitrary execution.\n\tcommondao.CreateExecutionProposal(cross(cur), subID, \"Drain\", \"Body\", func(_ int, sub realm) error {\n\t\tb := banker.NewBanker(banker.BankerTypeRealmSend, sub)\n\t\tb.SendCoins(sub.Address(), user, chain.NewCoins(chain.NewCoin(\"ugnot\", 500)))\n\t\treturn nil\n\t})\n}\n\n// Error:\n// commondao: treasury is frozen\n"},{"name":"z_20_h_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_20_h_filetest\n\npackage z_20_h_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/banker\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\trootID uint64\n\tsubID  uint64\n\texecID uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", \"\")\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), rootID, pID)\n\t}\n\tsubID = 3\n\n\t// Fund the sub-DAO and enable the execution kind on it.\n\ttesting.IssueCoins(commondao.GetView(subID).Address(), chain.NewCoins(chain.NewCoin(\"ugnot\", 500)))\n\t{\n\t\tpID := commondao.CreateRegisterKindProposal(cross(cur), subID, \"execution\")\n\t\tcommondao.Vote(cross(cur), subID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), subID, pID)\n\t}\n\n\t// Pass an execution proposal that drains the sub's own treasury, but do\n\t// not execute it yet. It is created while the sub is still unfrozen.\n\texecID = commondao.CreateExecutionProposal(cross(cur), subID, \"Drain\", \"Body\", func(_ int, sub realm) error {\n\t\tb := banker.NewBanker(banker.BankerTypeRealmSend, sub)\n\t\tb.SendCoins(sub.Address(), user, chain.NewCoins(chain.NewCoin(\"ugnot\", 500)))\n\t\treturn nil\n\t})\n\tcommondao.Vote(cross(cur), subID, execID, pdao.ChoiceYes, \"\")\n\n\t// The ancestor freezes the sub-DAO treasury before the execution runs.\n\tfID := commondao.CreateTreasuryFreezeProposal(cross(cur), rootID, subID, true)\n\tcommondao.Vote(cross(cur), rootID, fID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), rootID, fID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// The standing passed execution proposal fails cleanly once the treasury\n\t// is frozen: the freeze check reruns inside Execute, so the closure never\n\t// runs and no funds leave (StatusFailed, not a stuck-Passed tx panic).\n\tcommondao.Execute(cross(cur), subID, execID)\n\n\tview := commondao.GetView(subID)\n\tp, _ := view.GetProposal(execID)\n\tprintln(\"status:\", string(p.Status()))\n\tprintln(\"reason:\", p.StatusReason())\n\tprintln(\"frozen:\", view.IsTreasuryFrozen())\n\tprintln(\"treasury:\", banker.NewReadonlyBanker().GetCoins(view.Address()).String())\n\n\t// A frozen DAO that has the execution kind registered gets the extra\n\t// warning: freeze stops the realm's own spending paths, but a banker\n\t// retained by an earlier execution closure reaches the bank keeper\n\t// without passing through them, so freeze alone is not containment.\n\tout := commondao.Render(strconv.FormatUint(subID, 10))\n\tprintln(\"capability warning shown:\", strings.Contains(out, \"freeze alone is not containment here\"))\n}\n\n// Output:\n// status: failed\n// reason: commondao: treasury is frozen\n// frozen: true\n// treasury: 500ugnot\n// capability warning shown: true\n"},{"name":"z_20_i_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_20_i_filetest\n\npackage z_20_i_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoID  uint64\n\ttextID uint64\n\texecID uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Single-member council: one YES decides any proposal immediately.\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\t// Enable the execution kind through governance.\n\t{\n\t\tpID := commondao.CreateRegisterKindProposal(cross(cur), daoID, \"execution\")\n\t\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\t\tcommondao.Execute(cross(cur), daoID, pID)\n\t}\n\n\t// A second proposal, passed but left unexecuted: the re-entrant target.\n\ttextID = commondao.CreateTextProposal(cross(cur), daoID, \"Text\", \"Body\", 7)\n\tcommondao.Vote(cross(cur), daoID, textID, pdao.ChoiceYes, \"\")\n\n\t// An execution proposal whose closure crosses back in as the DAO's own\n\t// sub and calls Execute on the passed text proposal — a re-entrant\n\t// Execute. The closure is authored here so it survives Propose-\u003eExecute.\n\texecID = commondao.CreateExecutionProposal(cross(cur), daoID, \"Re-enter\", \"Body\", func(_ int, sub realm) error {\n\t\tcommondao.Execute(cross(sub), daoID, textID)\n\t\treturn nil\n\t})\n\tcommondao.Vote(cross(cur), daoID, execID, pdao.ChoiceYes, \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Executing the execution proposal runs its closure, which re-enters\n\t// Execute while the realm-global latch is raised. The nested Execute\n\t// panics; thrown across the cross(sub) boundary it arrived through, that\n\t// aborts the whole transaction.\n\tcommondao.Execute(cross(cur), daoID, execID)\n}\n\n// Error:\n// commondao: re-entrant Execute is not allowed\n"},{"name":"z_20_j_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_20_j_filetest\n\n// Only a council member may propose arbitrary execution.\n//\n// /p/ Propose does not check council membership — it checks the DAO is\n// live, looks up the kind, takes the latch and counts the cap — so this\n// wrapper's gate is the only thing standing between a stranger and an\n// ExecFunc closure of their choosing running with the DAO's authority.\n// The council would still have to vote it through, but the payload\n// author would be unauthenticated and the closure is not displayable.\npackage z_20_j_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx, genesis council only\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1, owns the DAO below\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\t// Opt the DAO into the execution kind, so the gate below is the only\n\t// thing left to refuse the call.\n\tpID := commondao.CreateRegisterKindProposal(cross(cur), daoID, \"execution\")\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n}\n\nfunc main(cur realm) {\n\t// owner sits on the genesis DAO's council, not on this DAO's.\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tcommondao.CreateExecutionProposal(cross(cur), daoID, \"T\", \"B\",\n\t\tfunc(_ int, sub realm) error { return nil })\n}\n\n// Error:\n// caller is not a council member\n"},{"name":"z_21_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_21_a_filetest\n\n// A DAO acting as a council member of another DAO.\n//\n// P (the \"parent\") has two council members: a person (`user`) and another DAO\n// (`M`). A DAO has no private key, so M cannot sign a Vote transaction. A DAO\n// votes by running an EXECUTION proposal in its own governance whose closure\n// calls commondao.Vote as M's own sub-identity: the host mints M's sub\n// (cur.Sub(\"dao/\u003cM\u003e\")) and the closure crosses into Vote with it, so P sees\n// M's address as the caller and records M's vote.\n//\n// The closure must be authored in a PERSISTENT realm — a closure from a CLI\n// `maketx run` does not survive Propose-\u003eExecute. This filetest is itself a\n// persistent realm, so it plays that role; on chain you would deploy a small\n// \"policy\" realm that sits on M's council and authors the closure.\n//\n// Transaction sequence (each commondao.* / policy-realm call is one tx):\n//\n//\tsetup: create M; register the execution kind on M; create P with {user, M}\n//\tin P:  1. CreateTextProposal      (user)         -\u003e propP\n//\t       2. Vote YES on propP        (user)         [propP: 1/2, active]\n//\tin M:  3. CreateExecutionProposal  (policy realm) -\u003e propM\n//\t             closure := Vote YES on (P, propP) as M\n//\t       4. Vote YES on propM        (M's council)\n//\t       5. Execute propM            -\u003e runs closure -\u003e M votes YES in P\n//\t                                                     [propP: 2/2, passed]\n//\tin P:  6. Execute propP            -\u003e Executed\npackage z_21_a_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx (genesis council)\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1 (operator)\n)\n\nvar (\n\tmemberDAO uint64  // M\n\tparentDAO uint64  // P\n\tmAddr     address // M's on-chain address (a council member of P)\n)\n\nfunc init(cur realm) {\n\t// The genesis council invites the operator, who may then create DAOs.\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Create M, the DAO that will be a member of P. (Single-member council\n\t// here, standing in for however M is really governed.)\n\tmemberDAO = commondao.New(cross(cur), \"MemberDAO\", \"Acts as a member of another DAO\", \"\", \"\")\n\n\t// A DAO can only act as its own address through the execution kind, which\n\t// is opt-in. Register it on M through M's own governance.\n\tpid := commondao.CreateRegisterKindProposal(cross(cur), memberDAO, \"execution\")\n\tcommondao.Vote(cross(cur), memberDAO, pid, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), memberDAO, pid)\n\n\t// M's address is what we place on P's council.\n\tmAddr = commondao.GetView(memberDAO).Address()\n\n\t// Create P with two council members: the person `user` and the DAO `M`.\n\tparentDAO = commondao.New(cross(cur), \"ParentDAO\", \"Governed by a person and a DAO\", \"\", mAddr.String())\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tprintln(\"P has the member DAO on its council:\", commondao.GetView(parentDAO).Council().Has(mAddr))\n\n\t// Tx 1 + 2: a proposal in P, and the human member's YES vote. One YES is\n\t// not enough: a two-member council needs both to reach the threshold.\n\tpropP := commondao.CreateTextProposal(cross(cur), parentDAO, \"Parent decision\", \"Should P do X?\", 7)\n\tcommondao.Vote(cross(cur), parentDAO, propP, pdao.ChoiceYes, \"person votes yes\")\n\tprintln(\"propP after the person's vote:\", string(statusOf(parentDAO, propP)))\n\n\t// Tx 3: M creates an execution proposal. The closure is authored in this\n\t// persistent realm and captures P's IDs; at execution it receives M's sub\n\t// and votes as M.\n\tpropM := commondao.CreateExecutionProposal(cross(cur), memberDAO,\n\t\t\"Vote in ParentDAO\", \"Cast this DAO's YES vote on the parent proposal.\",\n\t\tfunc(_ int, sub realm) error {\n\t\t\tcommondao.Vote(cross(sub), parentDAO, propP, pdao.ChoiceYes, \"cast as the member DAO\")\n\t\t\treturn nil\n\t\t},\n\t)\n\n\t// Tx 4 + 5: M's council passes the execution proposal, then executes it.\n\t// Executing runs the closure, which casts M's vote in P as M's own address.\n\tcommondao.Vote(cross(cur), memberDAO, propM, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), memberDAO, propM)\n\n\tpP, _ := commondao.GetView(parentDAO).GetProposal(propP)\n\tprintln(\"M's vote recorded in P:\", pP.VotingRecord().HasVoted(mAddr))\n\tprintln(\"propP YES votes:\", pP.VotingRecord().VoteCount(pdao.ChoiceYes))\n\tprintln(\"propP after the member DAO's vote:\", string(pP.Status()))\n\n\t// Tx 6: finalize the now-passed parent proposal.\n\tcommondao.Execute(cross(cur), parentDAO, propP)\n\tprintln(\"propP final status:\", string(statusOf(parentDAO, propP)))\n}\n\nfunc statusOf(daoID, propID uint64) pdao.ProposalStatus {\n\tp, _ := commondao.GetView(daoID).GetProposal(propID)\n\treturn p.Status()\n}\n\n// Output:\n// P has the member DAO on its council: true\n// propP after the person's vote: active\n// M's vote recorded in P: true\n// propP YES votes: 2\n// propP after the member DAO's vote: passed\n// propP final status: executed\n"},{"name":"z_22_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_22_a_filetest\n\n// Bylaws lifecycle through governance: create a document with a diff\n// patch, amend it, list the set, render the bylaws page, remove it.\npackage z_22_a_filetest\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Single-member council: one YES decides any proposal immediately\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Create a document through governance: the payload is a create patch.\n\tpayload := commondao.AmendBylawsPayload(daoID, \"bylaws/quorum.md\", \"Quorum is half the council.\")\n\tpID := commondao.CreateAmendBylawsProposal(cross(cur), daoID, payload)\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n\tprintln(\"created:\", commondao.GetBylawsDoc(daoID, \"bylaws/quorum.md\"))\n\n\t// Amend it with a diff patch against the current text.\n\tpayload = commondao.AmendBylawsPayload(daoID, \"bylaws/quorum.md\", \"Quorum is two thirds of the council.\")\n\tpID = commondao.CreateAmendBylawsProposal(cross(cur), daoID, payload)\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n\tprintln(\"amended:\", commondao.GetBylawsDoc(daoID, \"bylaws/quorum.md\"))\n\n\t// Add a second document, then list the whole set (sorted).\n\tpayload = commondao.AmendBylawsPayload(daoID, \"bylaws/spend.md\", \"Spend only by vote.\")\n\tpID = commondao.CreateAmendBylawsProposal(cross(cur), daoID, payload)\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n\tfor _, path := range commondao.ListBylawsDocs(daoID, \"\") {\n\t\tprintln(\"doc:\", path)\n\t}\n\n\t// The bylaws page renders every document with its base hash.\n\tprintln(commondao.Render(strconv.FormatUint(daoID, 10) + \"/bylaws\"))\n\n\t// Remove it: an empty proposed text is a remove patch.\n\tpayload = commondao.AmendBylawsPayload(daoID, \"bylaws/spend.md\", \"\")\n\tpID = commondao.CreateAmendBylawsProposal(cross(cur), daoID, payload)\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n\tprintln(\"removed:\", commondao.GetBylawsDoc(daoID, \"bylaws/spend.md\") == \"\")\n}\n\n// Output:\n// created: Quorum is half the council.\n// amended: Quorum is two thirds of the council.\n// doc: bylaws/quorum.md\n// doc: bylaws/spend.md\n// # Foo: Bylaws \u0026 Mandates\n// [Go to DAO](/r/nt/commondao/v0:2)\n//\n// ---\n// ## bylaws/quorum\\.md\n// sha256: 20fd0dbce30ca94d0c6210a877e7b7c50c81c9b66e60265a5a9b6125805db799\n//\n//\n//\n// Quorum is two thirds of the council.\n//\n// ## bylaws/spend\\.md\n// sha256: c890333668c0f8104cf5a6607139f61a962f51077c5e2c8cb3933930ff5e9dc5\n//\n//\n//\n// Spend only by vote.\n//\n//\n// removed: true\n"},{"name":"z_22_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_22_b_filetest\n\n// Two bylaws amendments race from the same base: the first to execute\n// wins, the second fails cleanly (StatusFailed) and clobbers nothing.\npackage z_22_b_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Single-member council: one YES decides any proposal immediately\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Both amendments diff against the same (absent) document.\n\tp1 := commondao.CreateAmendBylawsProposal(cross(cur), daoID, commondao.AmendBylawsPayload(daoID, \"bylaws/a.md\", \"one\"))\n\tp2 := commondao.CreateAmendBylawsProposal(cross(cur), daoID, commondao.AmendBylawsPayload(daoID, \"bylaws/a.md\", \"two\"))\n\n\tcommondao.Vote(cross(cur), daoID, p1, pdao.ChoiceYes, \"\")\n\tcommondao.Vote(cross(cur), daoID, p2, pdao.ChoiceYes, \"\")\n\n\t// The first to execute wins and re-pins the document hash.\n\tcommondao.Execute(cross(cur), daoID, p1)\n\tprintln(\"doc after winner:\", commondao.GetBylawsDoc(daoID, \"bylaws/a.md\"))\n\n\t// The second is now stale: it fails cleanly instead of clobbering.\n\tcommondao.Execute(cross(cur), daoID, p2)\n\tprop, _ := commondao.GetView(daoID).GetProposal(p2)\n\tprintln(\"loser status:\", string(prop.Status()))\n\tprintln(\"loser reason:\", prop.StatusReason())\n\tprintln(\"doc after loser:\", commondao.GetBylawsDoc(daoID, \"bylaws/a.md\"))\n}\n\n// Output:\n// doc after winner: one\n// loser status: failed\n// loser reason: bylaws: document changed since the patch base\n// doc after loser: one\n"},{"name":"z_22_c_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_22_c_filetest\n\n// A bylaws amendment payload built against superseded document text is\n// rejected at proposal creation (stale base), so a proposal can never be\n// created against text that no longer exists.\npackage z_22_c_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Single-member council: one YES decides any proposal immediately\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// A payload built against the current (absent) document...\n\tstale := commondao.AmendBylawsPayload(daoID, \"bylaws/a.md\", \"one\")\n\n\t// ...is superseded when another amendment lands first.\n\tpID := commondao.CreateAmendBylawsProposal(cross(cur), daoID, commondao.AmendBylawsPayload(daoID, \"bylaws/a.md\", \"two\"))\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n\n\t// Proposing the superseded payload is rejected at creation.\n\tcommondao.CreateAmendBylawsProposal(cross(cur), daoID, stale)\n}\n\n// Error:\n// bylaws: document changed since the patch base\n"},{"name":"z_22_d_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_22_d_filetest\n\n// Bylaws rendering is escape-safe and line-preserving: hostile markdown\n// in document text and in patch insert literals is neutralized on both\n// the proposal page (the change summary) and the bylaws page (the stored\n// document), and multi-line content keeps its line structure. A literal\n// line starting with \"- \" cannot masquerade as a deletion marker: every\n// literal line is marker-prefixed by the summary.\npackage z_22_d_filetest\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Single-member council: one YES decides any proposal immediately\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\thostile := \"# Heading injection\\n\\n\u003cdiv\u003ehtml block\u003c/div\u003e\\n\\n[link](https://attacker.example)\\n\\nplain closing line\"\n\n\t// Create the document; render the ACTIVE proposal page first: the\n\t// change summary shows the hostile content escaped, line by line.\n\tpID := commondao.CreateAmendBylawsProposal(cross(cur), daoID, commondao.AmendBylawsPayload(daoID, \"bylaws/policy.md\", hostile))\n\tprintln(commondao.Render(strconv.FormatUint(daoID, 10) + \"/proposals/\" + strconv.FormatUint(pID, 10)))\n\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n\n\t// Amend with an insert whose lines mimic summary markers.\n\tpID = commondao.CreateAmendBylawsProposal(cross(cur), daoID, commondao.AmendBylawsPayload(daoID, \"bylaws/policy.md\", hostile+\"\\n- spoofed deletion marker\\n= 9 unchanged\"))\n\tprintln(commondao.Render(strconv.FormatUint(daoID, 10) + \"/proposals/\" + strconv.FormatUint(pID, 10)))\n\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n\n\t// The stored multi-line document renders escaped with its line\n\t// structure preserved.\n\tprintln(commondao.Render(strconv.FormatUint(daoID, 10) + \"/bylaws\"))\n}\n\n// Output:\n//\n// \u003e Voting ends on **Fri, 20 Feb 2009 11:31pm UTC**\n//\n// # #1 Add Bylaws Document: bylaws/policy\\.md\n// [Go to DAO](/r/nt/commondao/v0:2) • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=1\u0026reason=\u0026vote=)\n//\n// ---\n// ## Details\n// - Proposer: g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// - Submit Time: Fri, 13 Feb 2009 23:31:30 UTC\n// - Expected Outcome: **pending** ⏳\n// - Status: **active**\n// ## Description\n// **Document:** bylaws/policy\\.md\n//\n// ```\n// + # Heading injection\n// +\n// + \u003cdiv\u003ehtml block\u003c/div\u003e\n// +\n// + [link](https://attacker.example)\n// +\n// + plain closing line\n//\n// ```\n//\n//\n//\n//\n// \u003e Voting ends on **Fri, 20 Feb 2009 11:31pm UTC**\n//\n// # #2 Amend Bylaws Document: bylaws/policy\\.md\n// [Go to DAO](/r/nt/commondao/v0:2) • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=2\u0026reason=\u0026vote=)\n//\n// ---\n// ## Details\n// - Proposer: g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// - Submit Time: Fri, 13 Feb 2009 23:31:30 UTC\n// - Expected Outcome: **pending** ⏳\n// - Status: **active**\n// ## Description\n// **Document:** bylaws/policy\\.md\n//\n// ```\n// = 96 unchanged\n// +\n// + - spoofed deletion marker\n// + = 9 unchanged\n//\n// ```\n//\n//\n//\n// # Foo: Bylaws \u0026 Mandates\n// [Go to DAO](/r/nt/commondao/v0:2)\n//\n// ---\n// ## bylaws/policy\\.md\n// sha256: 9ce0a63e0a9255e7a01911bcd9ae19db2880c7a3af153fe7a3363a332bdf1ea6\n//\n//\n//\n// \\# Heading injection\n//\n// \u003cdiv\u003ehtml block\u003c/div\u003e\n//\n// [link](https://attacker.example)\n//\n// plain closing line\n// \\- spoofed deletion marker\n// = 9 unchanged\n"},{"name":"z_22_e_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_22_e_filetest\n\n// The mandates/ folder is reserved: the Constitution grants a council\n// self-power over its Bylaws only, so a council amendment targeting a\n// mandates path is rejected at proposal creation.\npackage z_22_e_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tpayload := commondao.AmendBylawsPayload(daoID, \"mandates/spend.md\", \"Spend only by vote.\")\n\tcommondao.CreateAmendBylawsProposal(cross(cur), daoID, payload)\n}\n\n// Error:\n// mandates are not council-amendable: they are set at creation or by an ancestor (ancestor amendment is not implemented yet)\n"},{"name":"z_23_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_23_a_filetest\n\n// The proposals list route: pagination, and the view/sort toggles.\n//\n// The load-bearing assertion is on page 2: the \"View:\" and \"Sort by:\"\n// links must NOT carry the current page. Switching to a view with fewer\n// pages while page=2 is pinned would land on \"invalid page number\".\npackage z_23_a_filetest\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar listPath string\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID := commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\tlistPath = strconv.FormatUint(daoID, 10) + \"/proposals\"\n\n\t// Nine proposals over a page size of eight: two pages.\n\tfor i := 0; i \u003c 9; i++ {\n\t\tcommondao.CreateTextProposal(cross(cur), daoID, \"Proposal \"+strconv.Itoa(i+1), \"Body\", 7)\n\t}\n}\n\nfunc main() {\n\t// Page 1, then page 2 — where the toggle links must drop the page.\n\tprintln(commondao.Render(listPath))\n\tprintln(commondao.Render(listPath + \"?page=2\"))\n\n\t// Oldest-first, and the (empty) finished view.\n\tprintln(commondao.Render(listPath + \"?order=asc\"))\n\tprintln(commondao.Render(listPath + \"?finished=\"))\n}\n\n// Output:\n// # Foo: Proposals\n// [Go to DAO](/r/nt/commondao/v0:2)\n//\n// ---\n// View: [finished](/r/nt/commondao/v0:2/proposals?finished=) • Sort by: [oldest](/r/nt/commondao/v0:2/proposals?order=asc)\n//\n// **[#9 Proposal 9](/r/nt/commondao/v0:2/proposals/9)**\n// Created by g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// Voting ends on Fri, 20 Feb 2009 11:31pm UTC\n// Votes: **0** • Status: **active** • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=9\u0026reason=\u0026vote=)\n//\n// **[#8 Proposal 8](/r/nt/commondao/v0:2/proposals/8)**\n// Created by g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// Voting ends on Fri, 20 Feb 2009 11:31pm UTC\n// Votes: **0** • Status: **active** • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=8\u0026reason=\u0026vote=)\n//\n// **[#7 Proposal 7](/r/nt/commondao/v0:2/proposals/7)**\n// Created by g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// Voting ends on Fri, 20 Feb 2009 11:31pm UTC\n// Votes: **0** • Status: **active** • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=7\u0026reason=\u0026vote=)\n//\n// **[#6 Proposal 6](/r/nt/commondao/v0:2/proposals/6)**\n// Created by g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// Voting ends on Fri, 20 Feb 2009 11:31pm UTC\n// Votes: **0** • Status: **active** • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=6\u0026reason=\u0026vote=)\n//\n// **[#5 Proposal 5](/r/nt/commondao/v0:2/proposals/5)**\n// Created by g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// Voting ends on Fri, 20 Feb 2009 11:31pm UTC\n// Votes: **0** • Status: **active** • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=5\u0026reason=\u0026vote=)\n//\n// **[#4 Proposal 4](/r/nt/commondao/v0:2/proposals/4)**\n// Created by g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// Voting ends on Fri, 20 Feb 2009 11:31pm UTC\n// Votes: **0** • Status: **active** • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=4\u0026reason=\u0026vote=)\n//\n// **[#3 Proposal 3](/r/nt/commondao/v0:2/proposals/3)**\n// Created by g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// Voting ends on Fri, 20 Feb 2009 11:31pm UTC\n// Votes: **0** • Status: **active** • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=3\u0026reason=\u0026vote=)\n//\n// **[#2 Proposal 2](/r/nt/commondao/v0:2/proposals/2)**\n// Created by g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// Voting ends on Fri, 20 Feb 2009 11:31pm UTC\n// Votes: **0** • Status: **active** • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=2\u0026reason=\u0026vote=)\n//\n// ---\n// \\- | page 1 of 2 | [»](?page=2)\n// # Foo: Proposals\n// [Go to DAO](/r/nt/commondao/v0:2)\n//\n// ---\n// View: [finished](/r/nt/commondao/v0:2/proposals?finished=) • Sort by: [oldest](/r/nt/commondao/v0:2/proposals?order=asc)\n//\n// **[#1 Proposal 1](/r/nt/commondao/v0:2/proposals/1)**\n// Created by g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// Voting ends on Fri, 20 Feb 2009 11:31pm UTC\n// Votes: **0** • Status: **active** • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=1\u0026reason=\u0026vote=)\n//\n// ---\n// [«](?page=1) | page 2 of 2 | \\-\n// # Foo: Proposals\n// [Go to DAO](/r/nt/commondao/v0:2)\n//\n// ---\n// View: [finished](/r/nt/commondao/v0:2/proposals?finished=\u0026order=asc) • Sort by: [newest](/r/nt/commondao/v0:2/proposals?order=desc)\n//\n// **[#1 Proposal 1](/r/nt/commondao/v0:2/proposals/1)**\n// Created by g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// Voting ends on Fri, 20 Feb 2009 11:31pm UTC\n// Votes: **0** • Status: **active** • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=1\u0026reason=\u0026vote=)\n//\n// **[#2 Proposal 2](/r/nt/commondao/v0:2/proposals/2)**\n// Created by g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// Voting ends on Fri, 20 Feb 2009 11:31pm UTC\n// Votes: **0** • Status: **active** • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=2\u0026reason=\u0026vote=)\n//\n// **[#3 Proposal 3](/r/nt/commondao/v0:2/proposals/3)**\n// Created by g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// Voting ends on Fri, 20 Feb 2009 11:31pm UTC\n// Votes: **0** • Status: **active** • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=3\u0026reason=\u0026vote=)\n//\n// **[#4 Proposal 4](/r/nt/commondao/v0:2/proposals/4)**\n// Created by g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// Voting ends on Fri, 20 Feb 2009 11:31pm UTC\n// Votes: **0** • Status: **active** • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=4\u0026reason=\u0026vote=)\n//\n// **[#5 Proposal 5](/r/nt/commondao/v0:2/proposals/5)**\n// Created by g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// Voting ends on Fri, 20 Feb 2009 11:31pm UTC\n// Votes: **0** • Status: **active** • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=5\u0026reason=\u0026vote=)\n//\n// **[#6 Proposal 6](/r/nt/commondao/v0:2/proposals/6)**\n// Created by g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// Voting ends on Fri, 20 Feb 2009 11:31pm UTC\n// Votes: **0** • Status: **active** • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=6\u0026reason=\u0026vote=)\n//\n// **[#7 Proposal 7](/r/nt/commondao/v0:2/proposals/7)**\n// Created by g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// Voting ends on Fri, 20 Feb 2009 11:31pm UTC\n// Votes: **0** • Status: **active** • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=7\u0026reason=\u0026vote=)\n//\n// **[#8 Proposal 8](/r/nt/commondao/v0:2/proposals/8)**\n// Created by g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// Voting ends on Fri, 20 Feb 2009 11:31pm UTC\n// Votes: **0** • Status: **active** • [Vote](/r/nt/commondao/v0$help\u0026func=Vote\u0026daoID=2\u0026proposalID=8\u0026reason=\u0026vote=)\n//\n// ---\n// \\- | page 1 of 2 | [»](?order=asc\u0026page=2)\n// # Foo: Proposals\n// [Go to DAO](/r/nt/commondao/v0:2)\n//\n// ---\n// View: [active](/r/nt/commondao/v0:2/proposals) • Sort by: [oldest](/r/nt/commondao/v0:2/proposals?finished=\u0026order=asc)\n//\n// Currently there are no finished proposals\n"},{"name":"z_23_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_23_b_filetest\n\n// The home index paginates over the LISTED set, not over every DAO.\n//\n// Listing is opt-in and off by default, so the newest DAOs are usually\n// unlisted. Paginating over all DAOs and filtering the window afterwards\n// drops listed DAOs off page 1 entirely (and, when a whole window is\n// unlisted, renders an empty page with no pager at all — stranding them\n// on pages the reader can no longer reach).\npackage z_23_b_filetest\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Twenty DAOs (IDs 2..21). List the ten oldest; the rest stay\n\t// unlisted, so a window taken over all DAOs would start on entries\n\t// that never render.\n\t//\n\t// The counts are deliberately far apart: 11 listed is 2 pages, 21\n\t// total is 3. Were the pager sized on daos.Size() the extra page\n\t// would exist and render empty, so ?page=3 below discriminates the\n\t// pagination total — not just the iteration source.\n\tfor i := 0; i \u003c 20; i++ {\n\t\tid := commondao.New(cross(cur), \"DAO \"+strconv.Itoa(i+1), \"Purpose\", \"\", \"\")\n\t\tif i \u003c 10 {\n\t\t\tcommondao.SetListed(cross(cur), id, true)\n\t\t}\n\t}\n}\n\nfunc main() {\n\t// Eleven listed DAOs (ten above plus the genesis DAO) over a page\n\t// size of ten: page 1 is full and page 2 holds the remainder.\n\tprintln(commondao.Render(\"\"))\n\tprintln(commondao.Render(\"?page=2\"))\n\n\t// Past the end of the LISTED set: there is no third page. Sized on\n\t// every DAO there would be, and it would render empty.\n\tprintln(commondao.Render(\"?page=3\"))\n}\n\n// Output:\n// # Common DAO\n// ---\n// This realm can be used to create CommonDAO instances based on [commondao](/p/nt/commondao/v0/) package.\n//\n// Here is a list of some of the DAOs that were created:\n//\n// - [DAO 10](/r/nt/commondao/v0:11)\n// - [DAO 9](/r/nt/commondao/v0:10)\n// - [DAO 8](/r/nt/commondao/v0:9)\n// - [DAO 7](/r/nt/commondao/v0:8)\n// - [DAO 6](/r/nt/commondao/v0:7)\n// - [DAO 5](/r/nt/commondao/v0:6)\n// - [DAO 4](/r/nt/commondao/v0:5)\n// - [DAO 3](/r/nt/commondao/v0:4)\n// - [DAO 2](/r/nt/commondao/v0:3)\n// - [DAO 1](/r/nt/commondao/v0:2)\n//\n//\n// \\- | page 1 of 2 | [»](?page=2)\n//\n//\n// # Common DAO\n// ---\n// This realm can be used to create CommonDAO instances based on [commondao](/p/nt/commondao/v0/) package.\n//\n// Here is a list of some of the DAOs that were created:\n//\n// - [Common DAO](/r/nt/commondao/v0:1)\n//\n//\n// [«](?page=1) | page 2 of 2 | \\-\n//\n//\n// # Common DAO\n// ---\n// This realm can be used to create CommonDAO instances based on [commondao](/p/nt/commondao/v0/) package.\n//\n// invalid page number\n"},{"name":"z_23_c_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_23_c_filetest\n\n// The single-vote page's failure branches.\n//\n// Each is a navigable page (header + links back), not a bare dead-end\n// string, and a missing vote distinguishes a council member who has not\n// voted yet — an ordinary state — from an account outside the electorate.\npackage z_23_c_filetest\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner     = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser      = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\tsilent    = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\") // in the electorate, never votes\n\tlatecomer = address(\"g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj\") // joined the council AFTER the proposal\n\toutsider  = address(\"g1qjnm0dpkcze233rljaqffny3eel3wt6wn4lql2\") // never on the council\n)\n\nvar proposalPath string\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID := commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", silent.String())\n\n\tpID := commondao.CreateTextProposal(cross(cur), daoID, \"Decision\", \"Body\", 7)\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"yes from the proposer\")\n\tproposalPath = strconv.FormatUint(daoID, 10) + \"/proposals/\" + strconv.FormatUint(pID, 10)\n\n\t// Grow the council AFTER the proposal exists, so the live council and\n\t// the proposal's frozen electorate are different sets. Both current\n\t// members must approve (two-member supermajority).\n\taddID := commondao.CreateCouncilUpdateProposal(cross(cur), daoID, latecomer.String(), \"\")\n\tcommondao.Vote(cross(cur), daoID, addID, pdao.ChoiceYes, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(silent))\n\tcommondao.Vote(cross(cur), daoID, addID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, addID)\n}\n\nfunc main() {\n\t// A recorded vote.\n\tprintln(commondao.Render(proposalPath + \"/vote/\" + string(user)))\n\n\t// A council member who has not voted yet.\n\tprintln(commondao.Render(proposalPath + \"/vote/\" + string(silent)))\n\n\t// A sitting council member who joined after the snapshot: not in the\n\t// electorate, so not entitled to vote on this proposal. Testing the\n\t// live council instead of the snapshot would wrongly report this one\n\t// as merely \"has not voted yet\".\n\tprintln(commondao.Render(proposalPath + \"/vote/\" + string(latecomer)))\n\n\t// An account that was never in the electorate.\n\tprintln(commondao.Render(proposalPath + \"/vote/\" + string(outsider)))\n\n\t// A malformed address.\n\tprintln(commondao.Render(proposalPath + \"/vote/not-an-address\"))\n}\n\n// Output:\n// # Vote: Proposal #1\n// [Go to DAO](/r/nt/commondao/v0:2) • [Go to Proposal](/r/nt/commondao/v0:2/proposals/1)\n//\n// ---\n// ## Details\n// - User: g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n// - Vote: YES\n// ## Reason\n// yes from the proposer\n//\n//\n// # Vote: Proposal #1\n// [Go to DAO](/r/nt/commondao/v0:2) • [Go to Proposal](/r/nt/commondao/v0:2/proposals/1)\n//\n// ---\n// This council member has not voted on this proposal yet.\n//\n//\n// # Vote: Proposal #1\n// [Go to DAO](/r/nt/commondao/v0:2) • [Go to Proposal](/r/nt/commondao/v0:2/proposals/1)\n//\n// ---\n// This account is not a member of the proposal's electorate.\n//\n//\n// # Vote: Proposal #1\n// [Go to DAO](/r/nt/commondao/v0:2) • [Go to Proposal](/r/nt/commondao/v0:2/proposals/1)\n//\n// ---\n// This account is not a member of the proposal's electorate.\n//\n//\n// # Vote: Proposal #1\n// [Go to DAO](/r/nt/commondao/v0:2) • [Go to Proposal](/r/nt/commondao/v0:2/proposals/1)\n//\n// ---\n// Invalid address.\n"},{"name":"z_23_d_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_23_d_filetest\n\n// The home index with nothing listed.\n//\n// pager.New treats a total of zero as having no valid page — including\n// page 1, which its own Picker links to — so the home route skips the\n// pager entirely when the listed set is empty. Without that, unlisting\n// every DAO turns \"?page=1\" into an error page.\npackage z_23_d_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx, genesis council\n)\n\nfunc init(cur realm) {\n\t// The genesis DAO lists itself at creation; unlist it so nothing is\n\t// listed. Only its own council member may toggle the flag.\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.SetListed(cross(cur), 1, false)\n}\n\nfunc main(cur realm) {\n\tprintln(\"listed:\", commondao.IsListed(1))\n\n\t// Both render the header alone — no list, and no \"invalid page number\".\n\tprintln(commondao.Render(\"\"))\n\tprintln(commondao.Render(\"?page=1\"))\n}\n\n// Output:\n// listed: false\n// # Common DAO\n// ---\n// This realm can be used to create CommonDAO instances based on [commondao](/p/nt/commondao/v0/) package.\n//\n//\n// # Common DAO\n// ---\n// This realm can be used to create CommonDAO instances based on [commondao](/p/nt/commondao/v0/) package.\n"},{"name":"z_23_e_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_23_e_filetest\n\n// A pager error raised inside a helper must be its own markdown block.\n//\n// renderCouncil is called mid-page by renderDAO, so its early return\n// resumes the caller, which goes straight on to write the Treasury\n// heading. Written as a bare string the error has no trailing newline\n// and the two glue together (\"invalid page number## Treasury\"),\n// destroying the H2 and taking the council table with it. This is the\n// one pager site where that is observable — everywhere else the error\n// is the last thing on the page, where the missing newline is trimmed.\npackage z_23_e_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tcommondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\t// A council page far past the end.\n\tout := commondao.Render(\"2?members=99\")\n\n\t// Slice around the boundary: the error and the heading that follows\n\t// must be separate blocks.\n\ti := strings.Index(out, \"invalid page number\")\n\tprintln(out[i : i+len(\"invalid page number\\n\\n## Treasury\")])\n}\n\n// Output:\n// invalid page number\n//\n// ## Treasury\n"},{"name":"z_2_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_2_b_filetest\n\npackage z_2_b_filetest\n\nimport (\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nfunc main(cur realm) {\n\tcommondao.New(cross(cur), \"\", \"Purpose\", \"\", \"\")\n}\n\n// Error:\n// DAO name is empty\n"},{"name":"z_2_c_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_2_c_filetest\n\npackage z_2_c_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst user = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\nfunc main(cur realm) {\n\t// Calling with a user that was not invited\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\n// Error:\n// unauthorized\n"},{"name":"z_4_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_4_a_filetest\n\npackage z_4_a_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\tname  = \"B\"\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\t// Invite a user to be able to start creating DAOs\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Create a couple of DAOs\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/test\"))\n\tcommondao.New(cross(cur), \"A\", \"Purpose\", \"\", \"\")\n\tdaoID = commondao.New(cross(cur), name, \"Purpose\", \"\", \"\")\n\tcommondao.New(cross(cur), \"C\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/test\"))\n\n\tview := commondao.GetView(daoID)\n\n\tprintln(view.Name() == name)\n\tprintln(view.ID() == daoID)\n}\n\n// Output:\n// true\n// true\n"},{"name":"z_5_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_5_a_filetest\n\npackage z_5_a_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoID uint64\n\tpID   uint64\n\tvote  pdao.VoteChoice = pdao.ChoiceYes\n)\n\nfunc init(cur realm) {\n\t// Invite a user to be able to start creating DAOs\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Create a new DAO whose caller (`test`) becomes a council member\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user))\n\n\t// Create a new proposal\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tpID = commondao.CreateTextProposal(cross(cur), daoID, \"Title\", \"Body\", 0)\n}\n\nfunc main(cur realm) {\n\t// User must be the caller to Vote()\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.Vote(cross(cur), daoID, pID, vote, \"\")\n\n\tp, _ := commondao.GetView(daoID).GetProposal(pID)\n\trecord := p.VotingRecord()\n\tif record.Size() != 1 {\n\t\tpanic(\"expected a single vote\")\n\t}\n\n\tprintln(record.HasVoted(user))\n\trecord.Iterate(0, record.Size(), false, func(v pdao.Vote) bool {\n\t\tprintln(v.Choice() == vote)\n\t\treturn false\n\t})\n}\n\n// Output:\n// true\n// true\n"},{"name":"z_5_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_5_b_filetest\n\npackage z_5_b_filetest\n\nimport (\n\t\"testing\"\n\n\tpcommondao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst user = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.Vote(cross(cur), 404, 1, pcommondao.ChoiceYes, \"\")\n}\n\n// Error:\n// DAO not found\n"},{"name":"z_5_c_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_5_c_filetest\n\npackage z_5_c_filetest\n\nimport (\n\t\"testing\"\n\n\tpcommondao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoID uint64\n\tpID   uint64\n)\n\nfunc init(cur realm) {\n\t// Invite a user to be able to start creating DAOs\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Create a new DAO whose caller (`test`) becomes a council member\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user))\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tpID = commondao.CreateTextProposal(cross(cur), daoID, \"Title\", \"Body\", 0)\n}\n\nfunc main(cur realm) {\n\t// The caller is not a member of the proposal's electorate\n\tcommondao.Vote(cross(cur), daoID, pID, pcommondao.ChoiceYes, \"\")\n}\n\n// Error:\n// account is not a member of the proposal's electorate\n"},{"name":"z_5_d_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_5_d_filetest\n\npackage z_5_d_filetest\n\nimport (\n\t\"testing\"\n\n\tpcommondao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\t// Invite a user to be able to start creating DAOs\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Create a new DAO whose caller (`test`) becomes a council member\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user))\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.Vote(cross(cur), daoID, 404, pcommondao.ChoiceYes, \"\")\n}\n\n// Error:\n// proposal not found\n"},{"name":"z_5_e_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_5_e_filetest\n\npackage z_5_e_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoID uint64\n\tpID   uint64\n)\n\nfunc init(cur realm) {\n\t// Invite a user to be able to start creating DAOs\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Create a new DAO whose caller (`test`) becomes a council member\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user))\n\n\t// Create a new proposal\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tpID = commondao.CreateTextProposal(cross(cur), daoID, \"Title\", \"Body\", 0)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.Vote(cross(cur), daoID, pID, \"invalid\", \"\")\n}\n\n// Error:\n// invalid vote choice\n"},{"name":"z_6_a_filetest.gno","body":"// PKGPATH: gno.land/r/demo/test\npackage test\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/p/nt/testutils/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst owner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\nvar (\n\tdaoID uint64\n\tpID   uint64\n\tuser1 = testutils.TestAddress(\"user1\")\n)\n\nfunc init(cur realm) {\n\t// Invite a user to be able to start creating DAOs\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user1)\n\n\t// Create a new DAO owned by user1, with user1 as the only council member\n\ttesting.SetRealm(testing.NewUserRealm(user1))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\t// Create a new proposal\n\tpID = commondao.CreateTextProposal(cross(cur), daoID, \"Title\", \"Body\", 0)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user1))\n\n\t// A single YES is a supermajority of the one member electorate,\n\t// so the proposal passes immediately and can be executed early\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n\n\tp, found := commondao.GetView(daoID).GetProposal(pID)\n\tif !found {\n\t\tpanic(\"expected proposal to be finished\")\n\t}\n\n\tprintln(string(p.Status()))\n\tprintln(commondao.GetView(daoID).FinishedProposalsSize())\n}\n\n// Output:\n// executed\n// 1\n"},{"name":"z_6_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_6_b_filetest\n\npackage z_6_b_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst owner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tcommondao.Execute(cross(cur), 404, 1)\n}\n\n// Error:\n// DAO not found\n"},{"name":"z_6_c_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_6_c_filetest\n\npackage z_6_c_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoID uint64\n\tpID   uint64\n)\n\nfunc init(cur realm) {\n\t// Invite a user to be able to start creating DAOs\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Create a new DAO whose caller (`test`) becomes a council member\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user))\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tpID = commondao.CreateTextProposal(cross(cur), daoID, \"Title\", \"Body\", 0)\n}\n\nfunc main(cur realm) {\n\t// Executing before the voting deadline requires council membership\n\tcommondao.Execute(cross(cur), daoID, pID)\n}\n\n// Error:\n// caller is not a council member\n"},{"name":"z_6_d_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_6_d_filetest\n\npackage z_6_d_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\t// Invite a user to be able to start creating DAOs\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Create a new DAO whose caller (`test`) becomes a council member\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user))\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.Execute(cross(cur), daoID, 404)\n}\n\n// Error:\n// proposal not found\n"},{"name":"z_6_f_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_6_f_filetest\n\npackage z_6_f_filetest\n\nimport (\n\t\"testing\"\n\n\tpcommondao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoID uint64\n\tpID   uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Council is {user, owner}\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(owner))\n\n\t// One day voting period; a 1Y/1N tie leaves the proposal undecided\n\tpID = commondao.CreateTextProposal(cross(cur), daoID, \"Title\", \"Body\", 1)\n\tcommondao.Vote(cross(cur), daoID, pID, pcommondao.ChoiceYes, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Vote(cross(cur), daoID, pID, pcommondao.ChoiceNo, \"\")\n}\n\nfunc main(cur realm) {\n\t// Advance past the voting deadline (5 seconds per height)\n\ttesting.SkipHeights(17281)\n\n\t// Finalization after the deadline is permissionless: the caller is\n\t// not a council member, and undecided proposals are dismissed\n\tcommondao.Execute(cross(cur), daoID, pID)\n\n\tp, _ := commondao.GetView(daoID).GetProposal(pID)\n\tprintln(string(p.Status()))\n}\n\n// Output:\n// dismissed\n"},{"name":"z_6_g_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_6_g_filetest\n\npackage z_6_g_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoID uint64\n\tpID   uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\t// A passed proposal that is not executed before its deadline\n\tpID = commondao.CreateTextProposal(cross(cur), daoID, \"Title\", \"Body\", 0)\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n}\n\nfunc main(cur realm) {\n\t// Past the deadline, finalization is permissionless: a non-council\n\t// caller can execute the passed proposal.\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\ttesting.SkipHeights(121000) // 5s blocks: pass the 7 day voting deadline\n\n\tcommondao.Execute(cross(cur), daoID, pID)\n\n\tp, _ := commondao.GetView(daoID).GetProposal(pID)\n\tprintln(\"status:\", string(p.Status()))\n}\n\n// Output:\n// status: executed\n"},{"name":"z_6_h_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_6_h_filetest\n\npackage z_6_h_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoID uint64\n\tpID   uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\tpID = commondao.CreateTextProposal(cross(cur), daoID, \"Title\", \"Body\", 0)\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Executed proposals leave active storage: a second execution attempt\n\t// cannot run them twice\n\tcommondao.Execute(cross(cur), daoID, pID)\n}\n\n// Error:\n// proposal not found\n"},{"name":"z_7_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_7_a_filetest\n\npackage z_7_a_filetest\n\nimport (\n\t\"testing\"\n\n\tpcommondao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\tname  = \"Foo\"\n)\n\nvar parentID uint64\n\nfunc init(cur realm) {\n\t// Invite a user to be able to start creating DAOs\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// The origin must be the invited user where invitation\n\t// is removed after the first user call to create a DAO\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Create the root DAO\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/nt/commondao/v0\"))\n\tparentDAO := commondao.New(cross(cur), \"Parent DAO\", \"Purpose\", \"\", \"\")\n\tparentID = parentDAO\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/nt/commondao/v0\"))\n\n\t// SubDAOs are created through a council proposal at simple majority\n\tpID := commondao.CreateSubDAOProposal(cross(cur), parentID, name, \"Purpose\", \"Sub charter\", string(user))\n\tcommondao.Vote(cross(cur), parentID, pID, pcommondao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), parentID, pID)\n\n\tsubID := uint64(3)\n\tview := commondao.GetView(subID)\n\n\tprintln(view.Name() == name)\n\tprintln(view.Description())\n\n\tparent, found := view.Parent()\n\tprintln(found \u0026\u0026 parent.ID() == parentID)\n\n\t// Check that SubDAO is added as a child to the parent DAO\n\tchildFound := false\n\tparent.IterateChildren(func(child pcommondao.ReadonlyCommonDAO) bool {\n\t\tchildFound = child.ID() == subID\n\t\treturn childFound\n\t})\n\tprintln(childFound)\n}\n\n// Output:\n// true\n// Sub charter\n// true\n// true\n"},{"name":"z_7_f_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_7_f_filetest\n\npackage z_7_f_filetest\n\nimport (\n\t\"testing\"\n\n\tpcommondao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar parentID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tparentID = commondao.New(cross(cur), \"Parent\", \"Purpose\", \"\", \"\")\n\n\t// Dissolve the parent (sole council member passes the supermajority)\n\tpID := commondao.CreateDissolutionProposal(cross(cur), parentID, owner)\n\tcommondao.Vote(cross(cur), parentID, pID, pcommondao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), parentID, pID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// A sub-DAO grafted onto a dissolved parent could never be dissolved\n\t// itself, so creation must be rejected: dissolved DAOs reject proposals.\n\tcommondao.CreateSubDAOProposal(cross(cur), parentID, \"Child\", \"Purpose\", \"\", string(user))\n}\n\n// Error:\n// DAO is deleted\n"},{"name":"z_7_g_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_7_g_filetest\n\npackage z_7_g_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\n// Sub-DAO creation passes by SIMPLE majority (spec :1504), not\n// supermajority. A 5-member council splitting 3 YES / 2 NO clears a simple\n// majority (2*3 \u003e 5) but not a supermajority (3*3 \u003c 2*5), so under the\n// correct Simple threshold the sub-DAO is created; a mutated Super threshold\n// would dismiss it. Mirror of z_11_h (spend = Super).\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\tmoul  = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\") // @moul\n\tmF    = address(\"g1cyh9qm4y43w38gfk77qxczrhqj2asdr8l7uk54\")\n\tmG    = address(\"g1x95kxqpwvqjf98qpkvsay7tppkh6zs9fr7wwda\")\n)\n\nvar (\n\trootID uint64\n\tpID    uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tmembers := strings.Join([]string{owner.String(), moul.String(), mF.String(), mG.String()}, \"\\n\")\n\trootID = commondao.New(cross(cur), \"Root\", \"Purpose\", \"\", members)\n\n\tpID = commondao.CreateSubDAOProposal(cross(cur), rootID, \"Sub\", \"Purpose\", \"\", string(user))\n\n\t// 3 YES / 2 NO from distinct members; NO first so the simple-majority\n\t// pass lands on the last (3rd YES) vote, never on a decided proposal.\n\ttesting.SetRealm(testing.NewUserRealm(mF))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceNo, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(mG))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceNo, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(moul))\n\tcommondao.Vote(cross(cur), rootID, pID, pdao.ChoiceYes, \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SkipHeights(121000) // pass the 7 day voting deadline\n\n\tcommondao.Execute(cross(cur), rootID, pID)\n\n\tp, _ := commondao.GetView(rootID).GetProposal(pID)\n\tprintln(\"status:\", string(p.Status()))\n\tprintln(\"children:\", commondao.GetView(rootID).ChildrenCount())\n}\n\n// Output:\n// status: executed\n// children: 1\n"},{"name":"z_9_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_9_a_filetest\n\npackage z_9_a_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Council is {user, owner}\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(owner))\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.Resign(cross(cur), daoID)\n\n\tcouncil := commondao.GetView(daoID).Council()\n\tprintln(council.Size())\n\tprintln(council.Has(user))\n\tprintln(council.Has(owner))\n}\n\n// Output:\n// 1\n// false\n// true\n"},{"name":"z_9_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_9_b_filetest\n\npackage z_9_b_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Council is {user} only\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.Resign(cross(cur), daoID)\n}\n\n// Error:\n// council update would remove every council member\n"},{"name":"z_9_c_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_9_c_filetest\n\npackage z_9_c_filetest\n\nimport (\n\t\"testing\"\n\n\tpcommondao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(owner))\n\n\t// Dissolve the DAO through a proposal\n\tpID := commondao.CreateDissolutionProposal(cross(cur), daoID, owner)\n\tcommondao.Vote(cross(cur), daoID, pID, pcommondao.ChoiceYes, \"\")\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Vote(cross(cur), daoID, pID, pcommondao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.Resign(cross(cur), daoID)\n}\n\n// Error:\n// DAO is deleted\n"},{"name":"z_9_d_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_9_d_filetest\n\npackage z_9_d_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoID uint64\n\tpID   uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(owner))\n\n\tpID = commondao.CreateTextProposal(cross(cur), daoID, \"Title\", \"Body\", 0)\n}\n\nfunc main(cur realm) {\n\t// Owner is a council member but not the proposal creator\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\n\tcommondao.Withdraw(cross(cur), daoID, pID)\n}\n\n// Error:\n// only the proposal creator can withdraw it\n"},{"name":"z_9_e_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_9_e_filetest\n\npackage z_9_e_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoID uint64\n\tpID   uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\tpID = commondao.CreateTextProposal(cross(cur), daoID, \"Title\", \"Body\", 0)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.Withdraw(cross(cur), daoID, pID)\n\n\tp, found := commondao.GetView(daoID).GetProposal(pID)\n\tprintln(found)\n\tprintln(string(p.Status()))\n\tprintln(commondao.GetView(daoID).ActiveProposalsSize())\n}\n\n// Output:\n// true\n// withdrawn\n// 0\n"},{"name":"z_9_f_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/z_9_f_filetest\n\npackage z_9_f_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\n// The Execute-deadline re-tally uses the proposal's electorate SNAPSHOT, not\n// the live council. A 3-member proposal with a single YES is undecided\n// (supermajority needs 3*1 \u003e= 2*3). If two members resign after the proposal\n// is created, the live council shrinks to 1 (where 1 YES would pass), but the\n// snapshot electorate stays 3, so at the deadline the proposal is DISMISSED.\n// A mutant tallying the live council at Execute would instead pass it.\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\tmoul  = address(\"g1manfred47kzduec920z88wfr64ylksmdcedlf5\") // @moul\n)\n\nvar (\n\tdaoID uint64\n\tpID   uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tmembers := strings.Join([]string{owner.String(), moul.String()}, \"\\n\")\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", members)\n\n\t// Snapshot electorate = 3 members; a single YES leaves it undecided.\n\tpID = commondao.CreateTextProposal(cross(cur), daoID, \"Title\", \"Body\", 0)\n\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\n\t// Two members resign: the live council shrinks to {user}, but the\n\t// proposal's electorate snapshot is unchanged.\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Resign(cross(cur), daoID)\n\ttesting.SetRealm(testing.NewUserRealm(moul))\n\tcommondao.Resign(cross(cur), daoID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SkipHeights(121000) // pass the 7 day deadline\n\n\tcommondao.Execute(cross(cur), daoID, pID)\n\n\tp, _ := commondao.GetView(daoID).GetProposal(pID)\n\tprintln(\"status:\", string(p.Status()))\n\tprintln(\"live council:\", commondao.GetView(daoID).Council().Size())\n\tprintln(\"electorate:\", p.Electorate().Size())\n}\n\n// Output:\n// status: dismissed\n// live council: 1\n// electorate: 3\n"},{"name":"zp_0_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_0_a_filetest\n\npackage zp_0_a_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner         = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser          = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\tnewMembers    = \"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\\ng147ah9520z0r6jh9mjr6c75rv6l8aypzvcd3f7d\"\n\tremoveMembers = \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user))\n\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tpID := commondao.CreateCouncilUpdateProposal(cross(cur), daoID, newMembers, removeMembers)\n\n\tp, found := commondao.GetView(daoID).GetProposal(pID)\n\tif !found {\n\t\tpanic(\"expected proposal to be created\")\n\t}\n\n\tprintln(string(p.Status()))\n\tprintln(p.Creator() == user)\n\tprintln(p.Title() == \"Council Update\")\n\tprintln(\"\")\n\tprintln(p.Body())\n}\n\n// Output:\n// active\n// true\n// true\n//\n// **Council Members to Add:**\n// - g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\n// - g147ah9520z0r6jh9mjr6c75rv6l8aypzvcd3f7d\n//\n//\n// **Council Members to Remove:**\n// - g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n"},{"name":"zp_0_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_0_b_filetest\n\npackage zp_0_b_filetest\n\nimport (\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nfunc main(cur realm) {\n\tcommondao.CreateCouncilUpdateProposal(cross(cur), 404, \"\", \"\")\n}\n\n// Error:\n// DAO not found\n"},{"name":"zp_0_d_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_0_d_filetest\n\npackage zp_0_d_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\t// Invite a user to be able to start creating DAOs\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// The origin must be the invited user where invitation\n\t// is removed after the first user call to create a DAO\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Create root DAO with a subDAO\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(\"g1vh7krmmzfua5xjmkatvmx09z37w34lsvd2mxa5\"))\n\n\tcommondao.CreateCouncilUpdateProposal(cross(cur), daoID, \"\", \"\")\n}\n\n// Error:\n// caller is not a council member\n"},{"name":"zp_0_e_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_0_e_filetest\n\npackage zp_0_e_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\t// Invite a user to be able to start creating DAOs\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// The origin must be the invited user where invitation\n\t// is removed after the first user call to create a DAO\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// Create root DAO with a subDAO\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user))\n\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.CreateCouncilUpdateProposal(cross(cur), daoID, \"not-an-address\", \"\")\n}\n\n// Error:\n// invalid address: not-an-address\n"},{"name":"zp_0_g_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_0_g_filetest\n\npackage zp_0_g_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user))\n\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.CreateCouncilUpdateProposal(cross(cur), daoID, \"\", \"\")\n}\n\n// Error:\n// no council members were specified to be added or removed\n"},{"name":"zp_0_h_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_0_h_filetest\n\npackage zp_0_h_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user))\n\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tpID := commondao.CreateCouncilUpdateProposal(cross(cur), daoID, user.String(), \"\")\n\n\t// Adding an existing member is an idempotent no-op, not an error\n\tp, found := commondao.GetView(daoID).GetProposal(pID)\n\tprintln(found)\n\tprintln(string(p.Status()))\n}\n\n// Output:\n// true\n// active\n"},{"name":"zp_0_i_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_0_i_filetest\n\npackage zp_0_i_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user))\n\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tpID := commondao.CreateCouncilUpdateProposal(cross(cur), daoID, \"\", owner.String())\n\n\t// Removing a non-member is an idempotent no-op, not an error\n\tp, found := commondao.GetView(daoID).GetProposal(pID)\n\tprintln(found)\n\tprintln(string(p.Status()))\n}\n\n// Output:\n// true\n// active\n"},{"name":"zp_1_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_1_a_filetest\n\npackage zp_1_a_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner      = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser       = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\ttitle      = \"General Proposal\"\n\tbody       = \"Foo Bar\"\n\tvotingDays = uint8(1)\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user)+\"\\n\"+string(owner))\n\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tpID := commondao.CreateTextProposal(cross(cur), daoID, title, body, votingDays)\n\n\tp, found := commondao.GetView(daoID).GetProposal(pID)\n\tif !found {\n\t\tpanic(\"expected proposal to be created\")\n\t}\n\n\tprintln(string(p.Status()))\n\tprintln(p.Creator() == user)\n\tprintln(p.Title() == title)\n\tprintln(p.VotingDeadline())\n\tprintln(p.Body())\n}\n\n// Output:\n// active\n// true\n// true\n// 2009-02-14 23:31:30 +0000 UTC\n// Foo Bar\n"},{"name":"zp_1_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_1_b_filetest\n\npackage zp_1_b_filetest\n\nimport (\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nfunc main(cur realm) {\n\tcommondao.CreateTextProposal(cross(cur), 404, \"\", \"\", 0)\n}\n\n// Error:\n// DAO not found\n"},{"name":"zp_1_d_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_1_d_filetest\n\npackage zp_1_d_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user)+\"\\n\"+string(owner))\n\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.CreateTextProposal(cross(cur), daoID, \"\", \"\", 31)\n}\n\n// Error:\n// maximum proposal voting period is 30 days\n"},{"name":"zp_1_e_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_1_e_filetest\n\npackage zp_1_e_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.CreateTextProposal(cross(cur), daoID, \"\", \"\", 1)\n}\n\n// Error:\n// caller is not a council member\n"},{"name":"zp_2_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_2_a_filetest\n\npackage zp_2_a_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner   = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser    = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\tname    = \"Foo SubDAO\"\n\tmembers = \"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\\ng1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\"\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user))\n\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tpID := commondao.CreateSubDAOProposal(cross(cur), daoID, name, \"Purpose\", \"\", members)\n\n\tp, found := commondao.GetView(daoID).GetProposal(pID)\n\tif !found {\n\t\tpanic(\"expected proposal to be created\")\n\t}\n\n\tprintln(string(p.Status()))\n\tprintln(p.Creator() == user)\n\tprintln(p.Title() == (\"New SubDAO: \" + name))\n\tprintln(p.VotingDeadline())\n\tprintln(p.Body())\n}\n\n// Output:\n// active\n// true\n// true\n// 2009-02-20 23:31:30 +0000 UTC\n// **Parent DAO:**\n// [Foo](/r/nt/commondao/v0:2)\n//\n// **SubDAO Name:**\n// Foo SubDAO\n//\n// **SubDAO Purpose:**\n// Purpose\n//\n// **Council Members:**\n// - g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\n// - g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\n"},{"name":"zp_2_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_2_b_filetest\n\npackage zp_2_b_filetest\n\nimport (\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nfunc main(cur realm) {\n\tcommondao.CreateSubDAOProposal(cross(cur), 404, \"\", \"Purpose\", \"\", \"\")\n}\n\n// Error:\n// DAO not found\n"},{"name":"zp_2_d_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_2_d_filetest\n\npackage zp_2_d_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n}\n\nfunc main(cur realm) {\n\t// Call with a user that is not a member of the DAO\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.CreateSubDAOProposal(cross(cur), daoID, \"\", \"Purpose\", \"\", \"\")\n}\n\n// Error:\n// caller is not a council member\n"},{"name":"zp_2_e_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_2_e_filetest\n\npackage zp_2_e_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user))\n\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.CreateSubDAOProposal(cross(cur), daoID, \"Name\", \"Purpose\", \"\", \"INVALID\")\n}\n\n// Error:\n// invalid address: INVALID\n"},{"name":"zp_2_f_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_2_f_filetest\n\npackage zp_2_f_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n\tname  = \"Foo\"\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user))\n\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), daoID, name, \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\t\ttesting.SetRealm(testing.NewUserRealm(user))\n\t\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\t\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\t\tcommondao.Execute(cross(cur), daoID, pID)\n\t}\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.CreateSubDAOProposal(cross(cur), daoID, name, \"Purpose\", \"\", string(user))\n}\n\n// Error:\n// a SubDAO with the same name already exists\n"},{"name":"zp_2_g_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_2_g_filetest\n\npackage zp_2_g_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user))\n\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.CreateSubDAOProposal(cross(cur), daoID, \"\", \"Purpose\", \"\", \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n}\n\n// Error:\n// DAO name is empty\n"},{"name":"zp_2_h_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_2_h_filetest\n\npackage zp_2_h_filetest\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoID uint64\n\tname  = strings.Repeat(\"A\", 61)\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user))\n\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.CreateSubDAOProposal(cross(cur), daoID, name, \"Purpose\", \"\", \"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\")\n}\n\n// Error:\n// DAO name is too long, max length is 60 characters\n"},{"name":"zp_3_a_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_3_a_filetest\n\npackage zp_3_a_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user))\n\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tpID := commondao.CreateDissolutionProposal(cross(cur), daoID, owner)\n\n\tp, found := commondao.GetView(daoID).GetProposal(pID)\n\tif !found {\n\t\tpanic(\"expected proposal to be created\")\n\t}\n\n\tprintln(string(p.Status()))\n\tprintln(p.Creator() == user)\n\tprintln(p.Title() == (\"Dissolve DAO: \" + commondao.GetView(daoID).Name()))\n\tprintln(p.VotingDeadline())\n\tprintln(p.Body())\n}\n\n// Output:\n// active\n// true\n// true\n// 2009-02-20 23:31:30 +0000 UTC\n// **DAO:**\n// [Foo](/r/nt/commondao/v0:2)\n//\n// **Sweep destination:**\n// g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\n"},{"name":"zp_3_b_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_3_b_filetest\n\npackage zp_3_b_filetest\n\nimport (\n\t\"testing\"\n\n\tpdao \"gno.land/p/nt/commondao/v0\"\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar (\n\tdaoID uint64\n\tsubID uint64\n)\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", string(user))\n\n\t// Create a SubDAO to be dissolved\n\t{\n\t\tpID := commondao.CreateSubDAOProposal(cross(cur), daoID, \"Bar\", \"Purpose\", \"\", string(user))\n\t\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\t\ttesting.SetRealm(testing.NewUserRealm(user))\n\t\tcommondao.Vote(cross(cur), daoID, pID, pdao.ChoiceYes, \"\")\n\t\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\t\tcommondao.Execute(cross(cur), daoID, pID)\n\t}\n\tsubID = 3\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tpID := commondao.CreateDissolutionProposal(cross(cur), subID, \"\")\n\n\tp, found := commondao.GetView(daoID).GetProposal(pID)\n\tif !found {\n\t\tpanic(\"expected proposal to be created in the parent DAO\")\n\t}\n\n\t// Make sure proposal doesn't exists in the SubDAO\n\t_, foundInSub := commondao.GetView(subID).GetProposal(pID)\n\tprintln(!foundInSub)\n\n\tprintln(string(p.Status()))\n\tprintln(p.Creator() == user)\n\tprintln(p.Title() == (\"Dissolve DAO: \" + commondao.GetView(subID).Name()))\n\tprintln(p.VotingDeadline())\n\tprintln(p.Body())\n}\n\n// Output:\n// true\n// active\n// true\n// true\n// 2009-02-20 23:31:30 +0000 UTC\n// **DAO:**\n// [Bar](/r/nt/commondao/v0:3)\n"},{"name":"zp_3_c_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_3_c_filetest\n\npackage zp_3_c_filetest\n\nimport (\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nfunc main(cur realm) {\n\tcommondao.CreateDissolutionProposal(cross(cur), 404, \"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\")\n}\n\n// Error:\n// DAO not found\n"},{"name":"zp_3_e_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_3_e_filetest\n\npackage zp_3_e_filetest\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/demo/test\"))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\tcommondao.CreateDissolutionProposal(cross(cur), daoID, owner)\n}\n\n// Error:\n// caller is not a council member\n"},{"name":"zp_3_f_filetest.gno","body":"// PKGPATH: gno.land/r/nt/commondao/v0/filetests/zp_3_f_filetest\n\npackage zp_3_f_filetest\n\nimport (\n\t\"testing\"\n\n\tpcommondao \"gno.land/p/nt/commondao/v0\"\n\n\t\"gno.land/r/nt/commondao/v0\"\n)\n\nconst (\n\towner = address(\"g16jpf0puufcpcjkph5nxueec8etpcldz7zwgydq\") // @devx\n\tuser  = address(\"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5\") // @test1\n)\n\nvar daoID uint64\n\nfunc init(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(owner))\n\tcommondao.Invite(cross(cur), user)\n\n\t// Create a DAO owned by user, with user as the only council member\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\tdaoID = commondao.New(cross(cur), \"Foo\", \"Purpose\", \"\", \"\")\n\n\t// Dissolve the DAO through a proposal decided by supermajority\n\tpID := commondao.CreateDissolutionProposal(cross(cur), daoID, owner)\n\tcommondao.Vote(cross(cur), daoID, pID, pcommondao.ChoiceYes, \"\")\n\tcommondao.Execute(cross(cur), daoID, pID)\n}\n\nfunc main(cur realm) {\n\ttesting.SetRealm(testing.NewUserRealm(user))\n\n\t// A dissolved DAO rejects new proposals\n\tcommondao.CreateDissolutionProposal(cross(cur), daoID, owner)\n}\n\n// Error:\n// DAO is deleted\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"qyNFafmwNNv3qqGsK2lazfaXkMtcTP8b2znokEgw5UZtHIm/qTt4IN0kn5GuICbzDqc8qliTWnaOmgsWfXS7dw=="}],"memo":""}},{"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\"\n\t\"gno.land/p/moul/helplink\"\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\"\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":"cla_test.gno","body":"package cla\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/moul/addrset\"\n\t\"gno.land/p/nt/uassert/v0\"\n)\n\n// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\n\nconst (\n\ttestHash1 = \"abc123def456\"\n\ttestHash2 = \"xyz789uvw012\"\n\ttestUser1 = \"g1user1address1234567890\"\n\ttestUser2 = \"g1user2address0987654321\"\n)\n\nfunc resetState() {\n\tsignatures = addrset.Set{}\n\trequiredHash = \"\"\n\tclaURL = \"\"\n}\n\nfunc TestSign(cur realm, t *testing.T) {\n\tresetState()\n\n\tsetRequiredHash(testHash1)\n\n\ttesting.SetRealm(testing.NewUserRealm(testUser1))\n\tSign(cross(cur), testHash1)\n\n\tuassert.True(t, HasValidSignature(address(testUser1)))\n}\n\nfunc TestSign_WrongHash(cur realm, t *testing.T) {\n\tresetState()\n\n\tsetRequiredHash(testHash1)\n\n\ttesting.SetRealm(testing.NewUserRealm(testUser1))\n\tuassert.AbortsWithMessage(t, cur, \"hash does not match required CLA hash\", func() {\n\t\tSign(cross(cur), testHash2)\n\t})\n\n\tuassert.False(t, HasValidSignature(address(testUser1)))\n}\n\nfunc TestHasValidSignature_Disabled(t *testing.T) {\n\tresetState()\n\n\tuassert.Equal(t, \"\", requiredHash)\n\tuassert.True(t, HasValidSignature(address(testUser1)))\n\tuassert.True(t, HasValidSignature(address(testUser2)))\n}\n\nfunc TestHasValidSignature_Valid(cur realm, t *testing.T) {\n\tresetState()\n\n\tsetRequiredHash(testHash1)\n\n\ttesting.SetRealm(testing.NewUserRealm(testUser1))\n\tSign(cross(cur), testHash1)\n\n\tuassert.True(t, HasValidSignature(address(testUser1)))\n}\n\nfunc TestHasValidSignature_NotSigned(t *testing.T) {\n\tresetState()\n\n\tsetRequiredHash(testHash1)\n\n\tuassert.False(t, HasValidSignature(address(testUser1)))\n}\n\nfunc TestSetRequiredHash_ResetsSignatures(cur realm, t *testing.T) {\n\tresetState()\n\n\tsetRequiredHash(testHash1)\n\n\ttesting.SetRealm(testing.NewUserRealm(testUser1))\n\tSign(cross(cur), testHash1)\n\tuassert.True(t, HasValidSignature(address(testUser1)))\n\tuassert.Equal(t, 1, signatures.Size())\n\n\t// Update hash - should reset signatures\n\tsetRequiredHash(testHash2)\n\n\tuassert.False(t, HasValidSignature(address(testUser1)))\n\tuassert.Equal(t, 0, signatures.Size())\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\"\n\t\"gno.land/p/moul/md\"\n\t\"gno.land/p/moul/mdtable\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"XyG82YGdEVuJYd/COpjQCpsdY8yFU1U8DeSDDACXOa4D77nNFCOuPg/RaBOkBS+PeJmZqGn7ncRhkdcogC9VNA=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l","package":{"name":"namereg","path":"gno.land/r/sys/namereg/v1","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 V1: Pause\", \"\", e)\n\t}\n\n\treturn dao.NewProposalRequest(\"User Registry V1: 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 V1: 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 V1: 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 V1: 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":"blacklist_test.gno","body":"package namereg\n\nimport \"testing\"\n\n// TestReservedNamesSorted enforces lexicographic ordering on reservedNames.\n// The list is intended to be auditable at a glance and to grow over time;\n// keeping it sorted makes diffs minimal and makes manual scanning for a\n// given entry feasible. If this fails after a maintainer adds an entry,\n// re-sort the slice rather than weakening the test.\nfunc TestReservedNamesSorted(cur realm, t *testing.T) {\n\tfor i := 1; i \u003c len(reservedNames); i++ {\n\t\tif reservedNames[i-1] \u003e= reservedNames[i] {\n\t\t\tt.Errorf(\n\t\t\t\t\"reservedNames not sorted at index %d: %q should come after %q\",\n\t\t\t\ti, reservedNames[i-1], reservedNames[i],\n\t\t\t)\n\t\t}\n\t}\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/v1-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/v1 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/v1 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":"canonical_test.gno","body":"package namereg\n\nimport (\n\t\"testing\"\n\n\t\"gno.land/p/nt/uassert/v0\"\n\n\tsusers \"gno.land/r/sys/users\"\n)\n\n// Canonicalize is now a delegating shim to susers.Canonicalize; verify\n// the local export and the upstream produce the same output for the\n// rules namereg/v1 cares about.\nfunc TestCanonicalize_DelegatesToSusers(cur realm, t *testing.T) {\n\tcases := []string{\n\t\t\"\",\n\t\t\"a\",\n\t\t\"alice\",\n\t\t\"vitalik\",\n\t\t\"vital1k\",\n\t\t\"balloon\",\n\t\t\"already-canonical\",\n\t\t\"xyz123\",\n\t\t\"nym-foolbar000\",\n\t\t\"nym-foolbar001\",\n\t}\n\tfor _, in := range cases {\n\t\tuassert.Equal(t, susers.Canonicalize(in), Canonicalize(in),\n\t\t\t\"namereg.Canonicalize must match susers.Canonicalize\")\n\t}\n}\n\nfunc TestReservedSet_BuiltFromBlacklist(cur realm, t *testing.T) {\n\t// Sanity: every entry from reservedNames AND its `+s` form must be\n\t// in the canonicalized lookup.\n\tfor _, n := range reservedNames {\n\t\t_, gotBare := reservedSet[Canonicalize(n)]\n\t\tuassert.True(t, gotBare,\n\t\t\t\"reservedSet missing canonical(%q)\", n)\n\n\t\t_, gotPlural := reservedSet[Canonicalize(n+\"s\")]\n\t\tuassert.True(t, gotPlural,\n\t\t\t\"reservedSet missing canonical(%q+s)\", n)\n\t}\n}\n\nfunc TestIsReserved_LiteralAndCanonical(cur realm, t *testing.T) {\n\t// Literal entry must be reserved.\n\tuassert.True(t, IsReserved(\"admin\"), \"admin should be reserved\")\n\n\t// `blogs` covered via `blog`+s rule (blog is in reservedNames).\n\tuassert.True(t, IsReserved(\"blogs\"), \"blogs covered by blog+s\")\n\n\t// l-substituted: `blog` canonicalizes to `biog`. Both forms blocked\n\t// because we canonicalize the candidate before lookup.\n\tuassert.True(t, IsReserved(\"biog\"), \"canonical(blog)=biog also blocked\")\n\n\t// 1-substituted under the new susers.Canonicalize rules: `1` → `i`.\n\t// `b1og` canonicalizes to `biog`, same as `blog`. Confirms the shim\n\t// picks up the broader rule set.\n\tuassert.True(t, IsReserved(\"b1og\"), \"1→i variant also blocked\")\n\n\t// Non-reserved stem should not be flagged.\n\tuassert.False(t, IsReserved(\"zulufoxtrot\"), \"zulufoxtrot is not reserved\")\n\n\t// Identity passthrough.\n\tuassert.True(t, IsReserved(\"tendermint\"))\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/v1\"\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/v1\"))\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\"\n\t\"gno.land/p/moul/realmpath\"\n\t\"gno.land/p/moul/txlink\"\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 (v1). 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 V1, 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\"\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"},{"name":"users_test.gno","body":"package namereg\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\t\"gno.land/p/nt/urequire/v0\"\n\n\tsusers \"gno.land/r/sys/users\"\n)\n\n// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\n\nfunc init(cur realm) {\n\t// Unit tests run with DefaultHeight=123, so the production init() in init.gno\n\t// (guarded on height==0) is a no-op in tests. Temporarily reset height so we\n\t// can whitelist this realm as a controller for testing.\n\ttesting.SetHeight(0)\n\tsusers.AddControllerAtGenesis(cross(cur), chain.PackageAddress(\"gno.land/r/sys/namereg/v1\"))\n\ttesting.SetHeight(123)\n}\n\nfunc TestRegister_Valid(cur realm, t *testing.T) {\n\t// Stems chosen with no `l` characters to keep canonical forms identical\n\t// to the originals — avoids accidental cross-subtest collisions with\n\t// other tests that may register l-bearing names.\n\tvalidUsernames := []string{\n\t\t\"nym-bravo123\",         // 5-char stem (minimum)\n\t\t\"nym-tango456\",         // 5-char stem\n\t\t\"nym-victor789\",        // 6-char stem\n\t\t\"nym-romeoecho012\",     // 10-char stem\n\t\t\"nym-mikefoxhote345\",   // 11-char stem\n\t\t\"nym-mikefoxhotenp678\", // 13-char stem (maximum)\n\t}\n\n\tfor _, username := range validUsernames {\n\t\taddr := testutils.TestAddress(username)\n\n\t\ttesting.SetRealm(testing.NewUserRealm(addr))\n\t\ttesting.SetOriginCaller(addr)\n\t\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(\"ugnot\", registerPrice)))\n\n\t\turequire.NotPanics(t, cur, func() {\n\t\t\tRegister(cross(cur), username)\n\t\t})\n\t}\n}\n\nfunc TestRegister_Free(cur realm, t *testing.T) {\n\toldPrice := registerPrice\n\tdefer func() { registerPrice = oldPrice }()\n\tregisterPrice = 0\n\n\taddr := testutils.TestAddress(\"free-payer\")\n\n\ttesting.SetRealm(testing.NewUserRealm(addr))\n\ttesting.SetOriginCaller(addr)\n\n\turequire.NotPanics(t, cur, func() {\n\t\tRegister(cross(cur), \"nym-foxtrot456\")\n\t})\n}\n\nfunc TestRegister_InvalidFormat(cur realm, t *testing.T) {\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(\"ugnot\", registerPrice)))\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"fmt-payer\")))\n\n\tcases := []string{\n\t\t\"\",                      // empty\n\t\t\"    \",                  // whitespace\n\t\t\"alice123\",              // missing nym- prefix\n\t\t\"usr-alice123\",          // wrong prefix\n\t\t\"nym-\",                  // prefix only\n\t\t\"nym-abc123\",            // stem too short (3 chars, need ≥5)\n\t\t\"nym-abcd123\",           // stem too short (4 chars)\n\t\t\"nym-abcdefghijklmn123\", // stem too long (14 chars, need ≤13)\n\t\t\"nym-Alice123\",          // uppercase in stem\n\t\t\"nym-al1ce123\",          // digit in stem\n\t\t\"nym-alice12\",           // only 2 trailing digits\n\t\t\"nym-alice1234\",         // 4 trailing digits (extra digit in stem too long)\n\t\t\"nym-alice\u0026#($)123\",     // special chars in stem\n\t}\n\n\tfor _, username := range cases {\n\t\tuassert.AbortsWithMessage(t, cur, ErrInvalidFormat.Error(), func() {\n\t\t\tRegister(cross(cur), username)\n\t\t})\n\t}\n}\n\nfunc TestRegister_ReservedPrefix(cur realm, t *testing.T) {\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(\"ugnot\", registerPrice)))\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"prefix-payer\")))\n\n\tcases := []string{\n\t\t\"nym-gnoblah123\",    // gno prefix\n\t\t\"nym-gnomeland456\",  // gno prefix\n\t\t\"nym-glasgow012\",    // gl prefix (most-confusable with bech32 g1...)\n\t\t\"nym-atomic123\",     // atom prefix\n\t\t\"nym-atonex123\",     // atone prefix\n\t\t\"nym-photons456\",    // photon prefix\n\t\t\"nym-cosmoswide789\", // cosmos prefix\n\t}\n\n\tfor _, username := range cases {\n\t\tuassert.AbortsWithMessage(t, cur, ErrReservedPrefix.Error(), func() {\n\t\t\tRegister(cross(cur), username)\n\t\t})\n\t}\n}\n\n// gi is intentionally NOT in reservedPrefixes (i is visually distinct\n// enough from 1/l that legitimate gi* names should be registerable).\n// Phishing protection for the gi/gl visual class is enforced by\n// canonical-collision detection in r/sys/users — see\n// TestRegister_CanonicalCollision.\nfunc TestRegister_GiPrefix_Allowed(cur realm, t *testing.T) {\n\taddr := testutils.TestAddress(\"gi-prefix-allowed\")\n\ttesting.SetRealm(testing.NewUserRealm(addr))\n\ttesting.SetOriginCaller(addr)\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(\"ugnot\", registerPrice)))\n\n\turequire.NotPanics(t, cur, func() {\n\t\tRegister(cross(cur), \"nym-gillette789\")\n\t})\n}\n\nfunc TestRegister_Blacklisted(cur realm, t *testing.T) {\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(\"ugnot\", registerPrice)))\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"blk-payer\")))\n\n\tcases := []string{\n\t\t// `admin` is in reservedNames; with stem 5 chars it now matches the regex.\n\t\t\"nym-admin123\",\n\t\t// `support` is reserved (7 chars).\n\t\t\"nym-support456\",\n\t\t// `bitcoin` is reserved (7 chars).\n\t\t\"nym-bitcoin789\",\n\t\t// Implicit s-suffix expansion: `blog` is reserved, so `blogs` (stem\n\t\t// = blog+s) must also be rejected.\n\t\t\"nym-blogs012\",\n\t\t// Canonical match: `setting` is reserved → canonical \"setting\" (no l).\n\t\t// Try `setting` directly via 7-char stem.\n\t\t\"nym-setting345\",\n\t\t// Canonical match: `news` is reserved via `new+s` rule; canonical\n\t\t// of `news` is `news`. With a 5-char stem this won't reach here\n\t\t// (stem must be ≥5). Use a longer reserved name with l→i interaction:\n\t\t// `tendermint` (10 chars, no l) → canonical = tendermint → blacklisted.\n\t\t\"nym-tendermint678\",\n\t}\n\n\tfor _, username := range cases {\n\t\tuassert.AbortsWithMessage(t, cur, ErrBlacklisted.Error(), func() {\n\t\t\tRegister(cross(cur), username)\n\t\t})\n\t}\n}\n\nfunc TestRegister_CanonicalCollision(cur realm, t *testing.T) {\n\t// First register a name. Same-digits confusable variant must collide\n\t// in the unified susers canonical store.\n\taddr1 := testutils.TestAddress(\"collision-1\")\n\ttesting.SetRealm(testing.NewUserRealm(addr1))\n\ttesting.SetOriginCaller(addr1)\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(\"ugnot\", registerPrice)))\n\turequire.NotPanics(t, cur, func() {\n\t\tRegister(cross(cur), \"nym-balloon123\")\n\t})\n\n\t// Then attempt to register a canonical-equivalent variant — same\n\t// canonical full name (after l→i, etc.). Must reject from susers.\n\taddr2 := testutils.TestAddress(\"collision-2\")\n\ttesting.SetRealm(testing.NewUserRealm(addr2))\n\ttesting.SetOriginCaller(addr2)\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(\"ugnot\", registerPrice)))\n\tuassert.AbortsWithMessage(t, cur, susers.ErrCanonicalCollision.Error(), func() {\n\t\tRegister(cross(cur), \"nym-baiioon123\")\n\t})\n\n\t// Reverse direction also blocked.\n\taddr3 := testutils.TestAddress(\"collision-3\")\n\ttesting.SetRealm(testing.NewUserRealm(addr3))\n\ttesting.SetOriginCaller(addr3)\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(\"ugnot\", registerPrice)))\n\turequire.NotPanics(t, cur, func() {\n\t\tRegister(cross(cur), \"nym-papaiio789\")\n\t})\n\n\taddr4 := testutils.TestAddress(\"collision-4\")\n\ttesting.SetRealm(testing.NewUserRealm(addr4))\n\ttesting.SetOriginCaller(addr4)\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(\"ugnot\", registerPrice)))\n\tuassert.AbortsWithMessage(t, cur, susers.ErrCanonicalCollision.Error(), func() {\n\t\tRegister(cross(cur), \"nym-papallo789\")\n\t})\n}\n\n// Decision #2 in Option B: store key is full canonical username (not\n// stem). Same alpha stem with different digit suffixes coexists — does\n// not collide.\nfunc TestRegister_SameStemDifferentDigits_Coexist(cur realm, t *testing.T) {\n\taddrA := testutils.TestAddress(\"stem-coexist-A\")\n\ttesting.SetRealm(testing.NewUserRealm(addrA))\n\ttesting.SetOriginCaller(addrA)\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(\"ugnot\", registerPrice)))\n\turequire.NotPanics(t, cur, func() {\n\t\tRegister(cross(cur), \"nym-foolbar000\")\n\t})\n\n\taddrB := testutils.TestAddress(\"stem-coexist-B\")\n\ttesting.SetRealm(testing.NewUserRealm(addrB))\n\ttesting.SetOriginCaller(addrB)\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(\"ugnot\", registerPrice)))\n\turequire.NotPanics(t, cur, func() {\n\t\tRegister(cross(cur), \"nym-foolbar999\")\n\t})\n}\n\nfunc TestRegister_TakenUsername(cur realm, t *testing.T) {\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(\"ugnot\", registerPrice)))\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"taken-payer\")))\n\n\tusername := \"nym-zulutwo567\"\n\n\turequire.NotPanics(t, cur, func() {\n\t\tRegister(cross(cur), username)\n\t})\n\n\t// Re-registration of the same exact name is rejected by susers via\n\t// ErrNameTaken (the nameStore.Has check precedes the canonical check).\n\tuassert.AbortsWithMessage(t, cur, susers.ErrNameTaken.Error(), func() {\n\t\tRegister(cross(cur), username)\n\t})\n}\n\nfunc TestRegister_InvalidPayment(cur realm, t *testing.T) {\n\taddr := testutils.TestAddress(\"payment-payer\")\n\n\ttesting.SetRealm(testing.NewUserRealm(addr))\n\ttesting.SetOriginCaller(addr)\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(\"ugnot\", 12))) // invalid\n\n\tuassert.AbortsContains(t, cur, ErrInvalidPayment.Error(), func() {\n\t\tRegister(cross(cur), \"nym-yankee345\")\n\t})\n}\n\n// Audit finding #11: the OriginSend() payment check is only trustworthy\n// when the direct caller is a pure EOA (IsUserCall). Any intermediate\n// code realm can attach -send to the tx, keep the coins, and call\n// Register; OriginSend() would still describe the envelope but namereg\n// would receive nothing. The EOA-only guard must reject all such callers.\nfunc TestRegister_IntermediateCodeRealmRejected(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewCodeRealm(\"gno.land/r/evil/wrapper\"))\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(\"ugnot\", registerPrice)))\n\n\tuassert.AbortsWithMessage(t, cur, ErrNonUserCall.Error(), func() {\n\t\tRegister(cross(cur), \"nym-whisky345\")\n\t})\n}\n\n// Audit finding #13: the OriginSend mismatch error must report the\n// CURRENT registerPrice, not the value frozen at package init time.\nfunc TestRegister_PaymentErrorReflectsCurrentPrice(cur realm, t *testing.T) {\n\toldPrice := registerPrice\n\tdefer func() { registerPrice = oldPrice }()\n\n\tregisterPrice = 5_000_000\n\n\taddr := testutils.TestAddress(\"price-payer\")\n\ttesting.SetRealm(testing.NewUserRealm(addr))\n\ttesting.SetOriginCaller(addr)\n\ttesting.SetOriginSend(chain.NewCoins(chain.NewCoin(\"ugnot\", 1_000_000))) // wrong\n\n\tuassert.AbortsContains(t, cur, \"5000000\", func() {\n\t\tRegister(cross(cur), \"nym-xrayfox678\")\n\t})\n\n\tuassert.AbortsContains(t, cur, ErrInvalidPayment.Error(), func() {\n\t\tRegister(cross(cur), \"nym-xrayfox678\")\n\t})\n}\n\n// Audit finding #14: ProposeNewRegisterPrice originally rejected only\n// negative prices. A passed proposal to set a negative price would\n// have been arithmetically nonsense; reject below MinRegisterPrice\n// (currently 0) at proposal-creation time so governance can never\n// underflow the floor.\nfunc TestProposeNewRegisterPrice_floor(cur realm, t *testing.T) {\n\tt.Run(\"zero is accepted (free registration is the default)\", func(t *testing.T) {\n\t\turequire.NotPanics(t, cur, func() { ProposeNewRegisterPrice(cur, 0) })\n\t})\n\n\tt.Run(\"negative is rejected\", func(t *testing.T) {\n\t\turequire.PanicsWithMessage(t, cur,\n\t\t\t\"price below floor: -1 ugnot \u003c 0 ugnot (MinRegisterPrice)\",\n\t\t\tfunc() { ProposeNewRegisterPrice(cur, -1) })\n\t})\n\n\tt.Run(\"at floor is accepted\", func(t *testing.T) {\n\t\turequire.NotPanics(t, cur, func() { ProposeNewRegisterPrice(cur, MinRegisterPrice) })\n\t})\n\n\tt.Run(\"above floor is accepted\", func(t *testing.T) {\n\t\turequire.NotPanics(t, cur, func() { ProposeNewRegisterPrice(cur, 1_000_000_000) })\n\t})\n}\n"},{"name":"z_0_prop1_filetest.gno","body":"// PKGPATH: gno.land/r/sys/namereg/v1/filetests/z_0_prop1_filetest\n\npackage z_0_prop1_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/r/gov/dao\"\n\tdaov3init \"gno.land/r/gov/dao/v3/init\"\n\tusers \"gno.land/r/sys/namereg/v1\"\n\tsusers \"gno.land/r/sys/users\"\n)\n\n// Test updating a name via GovDAO\nvar c address = unsafe.OriginCaller()\n\nfunc init(cur realm) {\n\t// Whitelist this realm as a controller so its Register() can reach r/sys/users.\n\ttesting.SetHeight(0)\n\tsusers.AddControllerAtGenesis(cross(cur), chain.PackageAddress(\"gno.land/r/sys/namereg/v1\"))\n\ttesting.SetHeight(123)\n\n\tdaov3init.InitWithUsers(cross(cur), c)\n\n\talice := testutils.TestAddress(\"alice\")\n\n\t// Register alice\n\ttesting.SetOriginCaller(alice)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tusers.Register(cross(cur), \"nym-alice123\")\n\n\t// Prop to change name\n\ttesting.SetOriginCaller(c)\n\ttesting.SetRealm(testing.NewUserRealm(c))\n\tpr := users.ProposeNewName(cross(cur), alice, \"alice_new123\")\n\tdao.MustCreateProposal(cross(cur), pr)\n}\n\nfunc main(cur realm) {\n\ttesting.SetOriginCaller(c)\n\n\tprintln(\"--\")\n\tprintln(dao.Render(cross(cur), \"\"))\n\tprintln(\"--\")\n\tprintln(dao.Render(cross(cur), \"0\"))\n\tprintln(\"--\")\n\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(0)))\n\n\tprintln(\"--\")\n\tprintln(dao.Render(cross(cur), \"0\"))\n\tprintln(\"--\")\n\n\tdao.ExecuteProposal(cross(cur), dao.ProposalID(0))\n\n\tprintln(\"--\")\n\tprintln(dao.Render(cross(cur), \"0\"))\n\n\tdata, _ := susers.ResolveName(\"alice_new123\")\n\tprintln(data.Addr())\n}\n\n// Output:\n// --\n// # GovDAO\n// ## Members\n// [\u003e Go to Memberstore \u003c](/r/gov/dao/v3/memberstore)\n// ## Proposals\n// ### [Prop #0 - User Registry V1: Rename user \\`nym\\-alice123\\` to \\`alice\\_new123\\`](/r/gov/dao:0)\n// Author: g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\n//\n// Status: ACTIVE\n//\n// Tiers eligible to vote: T1, T2, T3\n//\n// ---\n//\n//\n// --\n// ## Prop #0 - User Registry V1: Rename user \\`nym\\-alice123\\` to \\`alice\\_new123\\`\n// Author: g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\n//\n//\n//\n// Executor created in: `gno.land/r/sys/namereg/v1`\n//\n//\n//\n//\n// ---\n//\n// ### Stats\n// - **Proposal is open for votes**\n// - Tiers eligible to vote: T1, T2, T3\n// - YES PERCENT: 0%\n// - NO PERCENT: 0%\n// - ABSTAIN PERCENT: 0%\n//\n// [Detailed voting list](/r/gov/dao:0/votes)\n//\n// ---\n//\n// ### Actions\n// [Vote YES](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=YES\u0026pid=0) | [Vote NO](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=NO\u0026pid=0) | [Vote ABSTAIN](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=ABSTAIN\u0026pid=0)\n//\n// WARNING: Please double check transaction data before voting.\n// --\n// --\n// ## Prop #0 - User Registry V1: Rename user \\`nym\\-alice123\\` to \\`alice\\_new123\\`\n// Author: g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\n//\n//\n//\n// Executor created in: `gno.land/r/sys/namereg/v1`\n//\n//\n//\n//\n// ---\n//\n// ### Stats\n// - **Proposal is open for votes**\n// - Tiers eligible to vote: T1, T2, T3\n// - YES PERCENT: 100%\n// - NO PERCENT: 0%\n// - ABSTAIN PERCENT: 0%\n//\n// [Detailed voting list](/r/gov/dao:0/votes)\n//\n// ---\n//\n// ### Actions\n// [Vote YES](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=YES\u0026pid=0) | [Vote NO](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=NO\u0026pid=0) | [Vote ABSTAIN](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=ABSTAIN\u0026pid=0)\n//\n// WARNING: Please double check transaction data before voting.\n// --\n// --\n// ## Prop #0 - User Registry V1: Rename user \\`nym\\-alice123\\` to \\`alice\\_new123\\`\n// Author: g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\n//\n//\n//\n// Executor created in: `gno.land/r/sys/namereg/v1`\n//\n//\n//\n//\n// ---\n//\n// ### Stats\n// - **PROPOSAL HAS BEEN ACCEPTED**\n// - Tiers eligible to vote: T1, T2, T3\n// - YES PERCENT: 100%\n// - NO PERCENT: 0%\n// - ABSTAIN PERCENT: 0%\n//\n// [Detailed voting list](/r/gov/dao:0/votes)\n//\n// ---\n//\n// ### Actions\n// [Vote YES](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=YES\u0026pid=0) | [Vote NO](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=NO\u0026pid=0) | [Vote ABSTAIN](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=ABSTAIN\u0026pid=0)\n//\n// WARNING: Please double check transaction data before voting.\n// g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh\n"},{"name":"z_1_prop2_filetest.gno","body":"// PKGPATH: gno.land/r/sys/namereg/v1/filetests/z_1_prop2_filetest\n\npackage z_1_prop2_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/r/gov/dao\"\n\tdaov3init \"gno.land/r/gov/dao/v3/init\"\n\tusers \"gno.land/r/sys/namereg/v1\"\n\tsusers \"gno.land/r/sys/users\"\n)\n\n// Test updating a name via GovDAO\nvar c address = unsafe.OriginCaller()\n\nfunc init(cur realm) {\n\t// Whitelist this realm as a controller so its Register() can reach r/sys/users.\n\ttesting.SetHeight(0)\n\tsusers.AddControllerAtGenesis(cross(cur), chain.PackageAddress(\"gno.land/r/sys/namereg/v1\"))\n\ttesting.SetHeight(123)\n\n\tdaov3init.InitWithUsers(cross(cur), c)\n\n\talice := testutils.TestAddress(\"alice\")\n\n\t// Register alice\n\ttesting.SetOriginCaller(alice)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\tusers.Register(cross(cur), \"nym-alice123\")\n\n\t// Prop to delete user\n\ttesting.SetOriginCaller(c)\n\ttesting.SetRealm(testing.NewUserRealm(c))\n\tpr := users.ProposeDeleteUser(cross(cur), alice, \"delete user test\")\n\tdao.MustCreateProposal(cross(cur), pr)\n}\n\nfunc main(cur realm) {\n\ttesting.SetOriginCaller(c)\n\n\tprintln(\"--\")\n\tprintln(dao.Render(cross(cur), \"\"))\n\tprintln(\"--\")\n\tprintln(dao.Render(cross(cur), \"0\"))\n\tprintln(\"--\")\n\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(0)))\n\n\tprintln(\"--\")\n\tprintln(dao.Render(cross(cur), \"0\"))\n\tprintln(\"--\")\n\n\tdao.ExecuteProposal(cross(cur), dao.ProposalID(0))\n\n\tprintln(\"--\")\n\tprintln(dao.Render(cross(cur), \"0\"))\n\n\tdata, _ := susers.ResolveName(\"nym-alice123\")\n\tif data == nil {\n\t\tprintln(\"Successfully deleted alice\")\n\t}\n}\n\n// Output:\n// --\n// # GovDAO\n// ## Members\n// [\u003e Go to Memberstore \u003c](/r/gov/dao/v3/memberstore)\n// ## Proposals\n// ### [Prop #0 - User Registry V1: Delete user \\`nym\\-alice123\\`](/r/gov/dao:0)\n// Author: g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\n//\n// Status: ACTIVE\n//\n// Tiers eligible to vote: T1, T2, T3\n//\n// ---\n//\n//\n// --\n// ## Prop #0 - User Registry V1: Delete user \\`nym\\-alice123\\`\n// Author: g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\n//\n// delete user test\n//\n// Executor created in: `gno.land/r/sys/namereg/v1`\n//\n//\n//\n//\n// ---\n//\n// ### Stats\n// - **Proposal is open for votes**\n// - Tiers eligible to vote: T1, T2, T3\n// - YES PERCENT: 0%\n// - NO PERCENT: 0%\n// - ABSTAIN PERCENT: 0%\n//\n// [Detailed voting list](/r/gov/dao:0/votes)\n//\n// ---\n//\n// ### Actions\n// [Vote YES](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=YES\u0026pid=0) | [Vote NO](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=NO\u0026pid=0) | [Vote ABSTAIN](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=ABSTAIN\u0026pid=0)\n//\n// WARNING: Please double check transaction data before voting.\n// --\n// --\n// ## Prop #0 - User Registry V1: Delete user \\`nym\\-alice123\\`\n// Author: g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\n//\n// delete user test\n//\n// Executor created in: `gno.land/r/sys/namereg/v1`\n//\n//\n//\n//\n// ---\n//\n// ### Stats\n// - **Proposal is open for votes**\n// - Tiers eligible to vote: T1, T2, T3\n// - YES PERCENT: 100%\n// - NO PERCENT: 0%\n// - ABSTAIN PERCENT: 0%\n//\n// [Detailed voting list](/r/gov/dao:0/votes)\n//\n// ---\n//\n// ### Actions\n// [Vote YES](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=YES\u0026pid=0) | [Vote NO](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=NO\u0026pid=0) | [Vote ABSTAIN](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=ABSTAIN\u0026pid=0)\n//\n// WARNING: Please double check transaction data before voting.\n// --\n// --\n// ## Prop #0 - User Registry V1: Delete user \\`nym\\-alice123\\`\n// Author: g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\n//\n// delete user test\n//\n// Executor created in: `gno.land/r/sys/namereg/v1`\n//\n//\n//\n//\n// ---\n//\n// ### Stats\n// - **PROPOSAL HAS BEEN ACCEPTED**\n// - Tiers eligible to vote: T1, T2, T3\n// - YES PERCENT: 100%\n// - NO PERCENT: 0%\n// - ABSTAIN PERCENT: 0%\n//\n// [Detailed voting list](/r/gov/dao:0/votes)\n//\n// ---\n//\n// ### Actions\n// [Vote YES](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=YES\u0026pid=0) | [Vote NO](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=NO\u0026pid=0) | [Vote ABSTAIN](/r/gov/dao$help\u0026func=MustVoteOnProposalSimple\u0026option=ABSTAIN\u0026pid=0)\n//\n// WARNING: Please double check transaction data before voting.\n// Successfully deleted alice\n"},{"name":"z_2_prop3_filetest.gno","body":"// PKGPATH: gno.land/r/sys/namereg/v1/filetests/z_2_prop3_filetest\n\npackage z_2_prop3_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/testutils/v0\"\n\t\"gno.land/r/gov/dao\"\n\tdaov3init \"gno.land/r/gov/dao/v3/init\"\n\tusers \"gno.land/r/sys/namereg/v1\"\n\tsusers \"gno.land/r/sys/users\"\n)\n\n// Test the full governance-driven registerPrice flow:\n//  1. propose a new price via users.ProposeNewRegisterPrice\n//  2. DAO accepts the proposal (vote YES, execute)\n//  3. verify the executed callback updated registerPrice by exercising\n//     Register with the new amount and watching it succeed (registration\n//     under the old default of 0 ugnot would now panic with the new\n//     price in the error message).\nvar c address = unsafe.OriginCaller()\n\nfunc init(cur realm) {\n\t// Whitelist this realm as a controller so its Register() can reach r/sys/users.\n\ttesting.SetHeight(0)\n\tsusers.AddControllerAtGenesis(cross(cur), chain.PackageAddress(\"gno.land/r/sys/namereg/v1\"))\n\ttesting.SetHeight(123)\n\n\tdaov3init.InitWithUsers(cross(cur), c)\n\n\t// Propose raising the price from 0 to 20 GNOT.\n\ttesting.SetOriginCaller(c)\n\ttesting.SetRealm(testing.NewUserRealm(c))\n\tpr := users.ProposeNewRegisterPrice(cross(cur), 20_000_000)\n\tdao.MustCreateProposal(cross(cur), pr)\n}\n\nfunc main(cur realm) {\n\ttesting.SetOriginCaller(c)\n\n\t// Vote and execute.\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(0)))\n\tdao.ExecuteProposal(cross(cur), dao.ProposalID(0))\n\n\t// New price should be active. Register a user with the new amount;\n\t// registration with the old default (0 ugnot) would panic.\n\talice := testutils.TestAddress(\"alice\")\n\ttesting.SetOriginCaller(alice)\n\ttesting.SetRealm(testing.NewUserRealm(alice))\n\ttesting.SetOriginSend(chain.Coins{{Denom: \"ugnot\", Amount: 20_000_000}})\n\tusers.Register(cross(cur), \"nym-alice123\")\n\n\tdata, _ := susers.ResolveName(\"nym-alice123\")\n\tprintln(\"registered alice at:\", data.Addr())\n}\n\n// Output:\n// registered alice at: g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh\n"},{"name":"z_3_prop4_filetest.gno","body":"// PKGPATH: gno.land/r/sys/namereg/v1/filetests/z_3_prop4_filetest\n\npackage z_3_prop4_filetest\n\nimport (\n\t\"chain\"\n\t\"chain/runtime/unsafe\"\n\t\"testing\"\n\n\t\"gno.land/r/gov/dao\"\n\tdaov3init \"gno.land/r/gov/dao/v3/init\"\n\tusers \"gno.land/r/sys/namereg/v1\"\n\tsusers \"gno.land/r/sys/users\"\n)\n\n// Test the full governance-driven pause/unpause flow:\n//  1. propose pause via NewSetPausedExecutor(true), vote YES, execute,\n//     observe IsPaused() flip to true.\n//  2. propose unpause via NewSetPausedExecutor(false), vote YES, execute,\n//     observe IsPaused() flip back to false.\n//  3. Register works again post-unpause.\nvar c address = unsafe.OriginCaller()\n\nfunc init(cur realm) {\n\t// Whitelist this realm as a controller so its Register() can reach r/sys/users.\n\ttesting.SetHeight(0)\n\tsusers.AddControllerAtGenesis(cross(cur), chain.PackageAddress(\"gno.land/r/sys/namereg/v1\"))\n\ttesting.SetHeight(123)\n\n\tdaov3init.InitWithUsers(cross(cur), c)\n}\n\nfunc main(cur realm) {\n\ttesting.SetOriginCaller(c)\n\ttesting.SetRealm(testing.NewUserRealm(c))\n\n\tprintln(\"paused before:\", users.IsPaused())\n\n\t// Propose, vote, execute: pause.\n\tdao.MustCreateProposal(cross(cur), users.NewSetPausedExecutor(cross(cur), true))\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(0)))\n\tdao.ExecuteProposal(cross(cur), dao.ProposalID(0))\n\tprintln(\"paused after pause prop:\", users.IsPaused())\n\n\t// Propose, vote, execute: unpause.\n\tdao.MustCreateProposal(cross(cur), users.NewSetPausedExecutor(cross(cur), false))\n\tdao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(1)))\n\tdao.ExecuteProposal(cross(cur), dao.ProposalID(1))\n\tprintln(\"paused after unpause prop:\", users.IsPaused())\n\n\t// Register works again (the pause check inside Register would have\n\t// panicked with ErrPaused had the unpause executor not run).\n\tusers.Register(cross(cur), \"nym-alice123\")\n\tdata, _ := susers.ResolveName(\"nym-alice123\")\n\tprintln(\"registered alice at:\", data.Addr())\n}\n\n// Output:\n// paused before: false\n// paused after pause prop: true\n// paused after unpause prop: false\n// registered alice at: g1wymu47drhr0kuq2098m792lytgtj2nyx77yrsm\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"DX7MT/Fyr+S9RNB0tqOlCHIvPYkCt2Wmras5ehP0OYY2i6f7n3ioXWzOCphIMdll8NX1B6bQgJ9eZ16XR8mwsw=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l","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/v1 (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/v3/impl\"\n\tmemberstore \"gno.land/r/gov/dao/v3/memberstore\"\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(\"g1rp7cmetn27eqlpjpc4vuusf8kaj746tysc0qgh\")\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"},{"name":"verifier_test.gno","body":"package names\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\n// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\nvar (\n\talice = testutils.TestAddress(\"alice\")\n\tbob   = testutils.TestAddress(\"bob\")\n)\n\nfunc TestDefaultVerifier(t *testing.T) {\n\t// Disabled: any case is true (regardless of paused or lookup).\n\tuassert.True(t, verifier(false, false, alice, alice.String(), nil))\n\tuassert.True(t, verifier(false, false, \"\", alice.String(), nil))\n\tuassert.True(t, verifier(false, false, alice, \"somerandomusername\", nil))\n\n\t// Pre-Enable bypass takes priority over paused — even when paused=true,\n\t// !isEnabled returns true. This is the documented \"stage pause before\n\t// Enable\" behavior.\n\tuassert.True(t, verifier(false, true, alice, alice.String(), nil))\n\tuassert.True(t, verifier(false, true, alice, \"anything\", nil))\n\n\t// Enabled: PA namespace check.\n\tuassert.True(t, verifier(true, false, alice, alice.String(), nil))\n\n\t// Enabled: non-PA namespaces denied when no registered-name lookup.\n\tuassert.False(t, verifier(true, false, alice, \"notregistered\", nil))\n\tuassert.False(t, verifier(true, false, alice, \"alice\", nil))\n\n\t// Enabled: empty name/address.\n\tuassert.False(t, verifier(true, false, address(\"\"), \"\", nil))\n\tuassert.False(t, verifier(true, false, alice, \"\", nil))\n\tuassert.False(t, verifier(true, false, address(\"\"), \"something\", nil))\n}\n\n// TestRegisteredNameVerifier exercises the second authorization path —\n// the registered-name lookup. Uses a fake lookup so this test doesn't\n// depend on r/sys/users state.\nfunc TestRegisteredNameVerifier(t *testing.T) {\n\t// Lookup that says \"gnobody\" is registered to alice.\n\taliceOwnsGnobody := func(name string) (address, bool) {\n\t\tif name == \"gnobody\" {\n\t\t\treturn alice, true\n\t\t}\n\t\treturn \"\", false\n\t}\n\n\t// alice can deploy under \"gnobody\" (her registered name).\n\tuassert.True(t, verifier(true, false, alice, \"gnobody\", aliceOwnsGnobody))\n\n\t// bob cannot deploy under \"gnobody\" (registered to alice, not bob).\n\tuassert.False(t, verifier(true, false, bob, \"gnobody\", aliceOwnsGnobody))\n\n\t// Unknown name still rejects (lookup returns ok=false).\n\tuassert.False(t, verifier(true, false, alice, \"notregistered\", aliceOwnsGnobody))\n\n\t// PA path still works alongside registered-name lookup. Tried first.\n\tuassert.True(t, verifier(true, false, alice, alice.String(), aliceOwnsGnobody))\n\n\t// Disabled bypasses both paths entirely (returns true regardless).\n\tuassert.True(t, verifier(false, false, bob, \"gnobody\", aliceOwnsGnobody))\n\n\t// Empty namespace + non-nil lookup: still rejects (early-out before lookup).\n\tuassert.False(t, verifier(true, false, alice, \"\", aliceOwnsGnobody))\n\n\t// Lookup returns ok=true for current-but-mismatched address.\n\tbobOwnsGnobody := func(name string) (address, bool) {\n\t\tif name == \"gnobody\" {\n\t\t\treturn bob, true\n\t\t}\n\t\treturn \"\", false\n\t}\n\tuassert.False(t, verifier(true, false, alice, \"gnobody\", bobOwnsGnobody))\n}\n\n// TestPausedVerifier covers the emergency-halt semantic. When paused\n// AND enabled, the verifier rejects EVERY namespace check including PA.\nfunc TestPausedVerifier(t *testing.T) {\n\t// Lookup that says \"gnobody\" is registered to alice. Used to confirm\n\t// the registered-name path is also halted by pause.\n\taliceOwnsGnobody := func(name string) (address, bool) {\n\t\tif name == \"gnobody\" {\n\t\t\treturn alice, true\n\t\t}\n\t\treturn \"\", false\n\t}\n\n\tt.Run(\"paused blocks PA namespaces\", func(t *testing.T) {\n\t\t// PA would normally succeed (addr.String() == namespace), but\n\t\t// pause short-circuits before the PA check.\n\t\tuassert.False(t, verifier(true, true, alice, alice.String(), nil))\n\t\tuassert.False(t, verifier(true, true, alice, alice.String(), aliceOwnsGnobody))\n\t})\n\n\tt.Run(\"paused blocks registered-name namespaces\", func(t *testing.T) {\n\t\t// Registered-name path would normally succeed, but pause\n\t\t// short-circuits before the lookup is consulted.\n\t\tuassert.False(t, verifier(true, true, alice, \"gnobody\", aliceOwnsGnobody))\n\t})\n\n\tt.Run(\"paused blocks any other namespace too\", func(t *testing.T) {\n\t\tuassert.False(t, verifier(true, true, alice, \"anything\", aliceOwnsGnobody))\n\t\tuassert.False(t, verifier(true, true, alice, \"\", aliceOwnsGnobody))\n\t\tuassert.False(t, verifier(true, true, address(\"\"), \"anything\", aliceOwnsGnobody))\n\t})\n\n\tt.Run(\"pre-Enable bypass takes priority over paused\", func(t *testing.T) {\n\t\t// !enabled is checked BEFORE paused in the verifier — the\n\t\t// pre-Enable shortcut returns true regardless of pause state.\n\t\t// This is the \"pause is staged, applies on Enable\" semantic.\n\t\tuassert.True(t, verifier(false, true, alice, alice.String(), nil))\n\t\tuassert.True(t, verifier(false, true, alice, \"gnobody\", aliceOwnsGnobody))\n\t\tuassert.True(t, verifier(false, true, alice, \"anything\", nil))\n\t})\n\n\tt.Run(\"paused=false with enabled=true behaves normally\", func(t *testing.T) {\n\t\t// Sanity: just confirms the false case doesn't accidentally do\n\t\t// something different from the no-pause baseline.\n\t\tuassert.True(t, verifier(true, false, alice, alice.String(), nil))\n\t\tuassert.True(t, verifier(true, false, alice, \"gnobody\", aliceOwnsGnobody))\n\t\tuassert.False(t, verifier(true, false, bob, \"gnobody\", aliceOwnsGnobody))\n\t})\n}\n\n// TestProposeSetPaused_idempotency verifies the proposal-creation guard:\n// requesting a pause state that already matches the current state panics\n// at proposal-creation time, so voters never see a no-op proposal.\n//\n// NOTE: this test mutates the package-level `paused` var directly to\n// avoid driving the full DAO flow. Restores the value via defer.\nfunc TestProposeSetPaused_idempotency(cur realm, t *testing.T) {\n\tsaved := paused\n\tdefer func() { paused = saved }()\n\n\tt.Run(\"propose pause when already paused panics\", func(t *testing.T) {\n\t\tpaused = true\n\t\turequire.PanicsWithMessage(t, cur,\n\t\t\t\"paused state already matches requested value; no-op proposal rejected\",\n\t\t\tfunc() { ProposeSetPaused(cur, true) })\n\t})\n\n\tt.Run(\"propose unpause when already unpaused panics\", func(t *testing.T) {\n\t\tpaused = false\n\t\turequire.PanicsWithMessage(t, cur,\n\t\t\t\"paused state already matches requested value; no-op proposal rejected\",\n\t\t\tfunc() { ProposeSetPaused(cur, false) })\n\t})\n\n\tt.Run(\"propose pause when unpaused succeeds\", func(t *testing.T) {\n\t\tpaused = false\n\t\turequire.NotPanics(t, cur, func() { ProposeSetPaused(cur, true) })\n\t\t// The proposal-create call doesn't actually mutate paused —\n\t\t// only its execution would. Confirm.\n\t\tuassert.False(t, paused)\n\t})\n\n\tt.Run(\"propose unpause when paused succeeds\", func(t *testing.T) {\n\t\tpaused = true\n\t\turequire.NotPanics(t, cur, func() { ProposeSetPaused(cur, false) })\n\t\t// Same: proposal-create does not mutate.\n\t\tuassert.True(t, paused)\n\t})\n}\n\n// TestSetPaused_internal verifies the private setPaused actuator\n// directly. Bypasses the proposal flow to confirm the toggle and the\n// event-emission path independently.\nfunc TestSetPaused_internal(cur realm, t *testing.T) {\n\tsaved := paused\n\tdefer func() { paused = saved }()\n\n\tpaused = false\n\tsetPaused(0, cur, true)\n\tuassert.True(t, paused)\n\n\tsetPaused(0, cur, false)\n\tuassert.False(t, paused)\n}\n\nfunc TestIsPaused(t *testing.T) {\n\tsaved := paused\n\tdefer func() { paused = saved }()\n\n\tpaused = false\n\tuassert.False(t, IsPaused())\n\n\tpaused = true\n\tuassert.True(t, IsPaused())\n}\n\nfunc TestEnable(cur realm, t *testing.T) {\n\ttesting.SetRealm(testing.NewUserRealm(testutils.TestAddress(\"random\")))\n\tuassert.AbortsWithMessage(t, cur, \"caller is not admin\", func() {\n\t\tEnable(cross(cur))\n\t})\n\tuassert.False(t, IsEnabled())\n\n\ttesting.SetRealm(testing.NewUserRealm(admin))\n\tuassert.NotPanics(t, cur, func() {\n\t\tEnable(cross(cur))\n\t})\n\tuassert.True(t, IsEnabled())\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"+Upx9L1rJ2a9lQf3uyq4gtt9MTaakK4thkjGWO8BH84WPC+mVK0cHQ5lWoHQzJ8KxjXapco6rla+a1Cx57qoTg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l","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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"XEjuAhDwfZ5ZYrBpYS8qGpHPVXAEs3PqpcdVjxUQeE4rK4iJ2Q8zvGBtqxmaDsXZpbDZM7rV/xqRKmlYwAaBmw=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l","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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"z1ZJ96sHHLzJde8+hHmBySwUqD23yjwsfqr9vTLbFAwNVuVLrQufb1L5wm6nTEhcA3J9mXh5oMYT6eKa/JQhKg=="}],"memo":""}},{"tx":{"msg":[{"@type":"/vm.m_addpkg","creator":"g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l","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\"\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\"\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\"\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"},{"name":"validators_test.gno","body":"package validators\n\nimport (\n\t\"chain/runtime\"\n\t\"math\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"gno.land/p/nt/bptree/v0\"\n\t\"gno.land/p/nt/poa/v0\"\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\t\"gno.land/p/sys/validators\"\n)\n\n// cur is a zero-value realm used as a placeholder when forwarding to\n// uassert/urequire dispatch helpers that gained an `rlm realm` param.\n// These tests pass `func()` callbacks (no crossing inside the callback),\n// so rlm is ignored — a nil realm here is safe.\nvar cur realm\n\n// generateTestValidators generates a dummy validator set\nfunc generateTestValidators(count int) []validators.Validator {\n\tvals := make([]validators.Validator, 0, count)\n\n\tfor i := 0; i \u003c count; i++ {\n\t\tval := validators.Validator{\n\t\t\tAddress:     testutils.TestAddress(ufmt.Sprintf(\"%d\", i)),\n\t\t\tPubKey:      \"public-key\",\n\t\t\tVotingPower: 10,\n\t\t}\n\n\t\tvals = append(vals, val)\n\t}\n\n\treturn vals\n}\n\nfunc TestValidators_AddRemove(t *testing.T) {\n\t// Clear any changes\n\tchanges = bptree.NewBPTree32()\n\n\tvar (\n\t\tvals          = generateTestValidators(100)\n\t\tinitialHeight = int64(123)\n\t)\n\n\t// Add in the validators\n\tfor _, val := range vals {\n\t\taddValidator(val)\n\n\t\t// Make sure the validator is added\n\t\tuassert.True(t, vp.IsValidator(val.Address))\n\n\t\ttesting.SkipHeights(1)\n\t}\n\n\tfor i := initialHeight; i \u003c initialHeight+int64(len(vals)); i++ {\n\t\t// Make sure the changes are saved\n\t\tchs := GetChanges(i, initialHeight+int64(len(vals)))\n\n\t\t// We use the funky index calculation to make sure\n\t\t// changes are properly handled for each block span\n\t\tuassert.Equal(t, initialHeight+int64(len(vals))-i, int64(len(chs)))\n\n\t\tfor index, val := range vals[i-initialHeight:] {\n\t\t\t// Make sure the changes are equal to the additions\n\t\t\tch := chs[index]\n\n\t\t\tuassert.Equal(t, val.Address, ch.Address)\n\t\t\tuassert.Equal(t, val.PubKey, ch.PubKey)\n\t\t\tuassert.Equal(t, val.VotingPower, ch.VotingPower)\n\t\t}\n\t}\n\n\t// Save the beginning height for the removal\n\tinitialRemoveHeight := runtime.ChainHeight()\n\n\t// Clear any changes\n\tchanges = bptree.NewBPTree32()\n\n\t// Remove the validators\n\tfor _, val := range vals {\n\t\tremoveValidator(val.Address)\n\n\t\t// Make sure the validator is removed\n\t\tuassert.False(t, vp.IsValidator(val.Address))\n\n\t\ttesting.SkipHeights(1)\n\t}\n\n\tfor i := initialRemoveHeight; i \u003c initialRemoveHeight+int64(len(vals)); i++ {\n\t\t// Make sure the changes are saved\n\t\tchs := GetChanges(i, initialRemoveHeight+int64(len(vals)))\n\n\t\t// We use the funky index calculation to make sure\n\t\t// changes are properly handled for each block span\n\t\tuassert.Equal(t, initialRemoveHeight+int64(len(vals))-i, int64(len(chs)))\n\n\t\tfor index, val := range vals[i-initialRemoveHeight:] {\n\t\t\t// Make sure the changes are equal to the additions\n\t\t\tch := chs[index]\n\n\t\t\tuassert.Equal(t, val.Address, ch.Address)\n\t\t\tuassert.Equal(t, val.PubKey, ch.PubKey)\n\t\t\tuassert.Equal(t, uint64(0), ch.VotingPower)\n\t\t}\n\t}\n}\n\n// TestGetChanges_BoundedRange verifies that GetChanges(from, to) correctly\n// returns only changes within the [from, to] block range.\nfunc TestGetChanges_BoundedRange(t *testing.T) {\n\tchanges = bptree.NewBPTree32()\n\tvp = poa.NewPoA()\n\n\tvals := generateTestValidators(3)\n\n\t// Store additions at block h1\n\th1 := runtime.ChainHeight()\n\tfor _, val := range vals {\n\t\taddValidator(val)\n\t}\n\ttesting.SkipHeights(1)\n\n\t// Store removals at block h2\n\th2 := runtime.ChainHeight()\n\tfor _, val := range vals {\n\t\tremoveValidator(val.Address)\n\t}\n\ttesting.SkipHeights(1)\n\n\t// Query spanning both blocks returns all changes\n\tall := GetChanges(h1, h2)\n\tuassert.Equal(t, 6, len(all))\n\n\t// Query for h1 only returns additions\n\tatH1 := GetChanges(h1, h1)\n\tuassert.Equal(t, 3, len(atH1))\n\tfor i, ch := range atH1 {\n\t\tuassert.Equal(t, vals[i].Address, ch.Address)\n\t\tuassert.True(t, ch.VotingPower \u003e 0)\n\t}\n\n\t// Query for h2 only returns removals\n\tatH2 := GetChanges(h2, h2)\n\tuassert.Equal(t, 3, len(atH2))\n\tfor i, ch := range atH2 {\n\t\tuassert.Equal(t, vals[i].Address, ch.Address)\n\t\tuassert.Equal(t, uint64(0), ch.VotingPower)\n\t}\n\n\t// Query beyond stored range returns empty\n\tuassert.Equal(t, 0, len(GetChanges(h2+1, h2+1)))\n}\n\n// TestRender_ShowsNewestWhenOverLimit verifies that Render displays the newest\n// maxDisplay buckets when there are more change buckets than maxDisplay.\nfunc TestRender_ShowsNewestWhenOverLimit(t *testing.T) {\n\tchanges = bptree.NewBPTree32()\n\tvp = poa.NewPoA()\n\n\tconst total = 13\n\tconst maxDisplay = 10\n\n\tvals := generateTestValidators(total)\n\tbase := runtime.ChainHeight()\n\n\tfor i := 0; i \u003c total; i++ {\n\t\th := base + int64(i)\n\t\tchanges.Set(getBlockID(h), []change{\n\t\t\t{blockNum: h, validator: vals[i]},\n\t\t})\n\t}\n\n\toutput := Render(\"\")\n\n\t// Newest maxDisplay buckets must appear.\n\tfor i := total - maxDisplay; i \u003c total; i++ {\n\t\th := base + int64(i)\n\t\tuassert.True(t, strings.Contains(output, ufmt.Sprintf(\"#%d:\", h)),\n\t\t\tufmt.Sprintf(\"expected block #%d in output\", h))\n\t}\n\n\t// Oldest (total - maxDisplay) buckets must NOT appear.\n\tfor i := 0; i \u003c total-maxDisplay; i++ {\n\t\th := base + int64(i)\n\t\tuassert.False(t, strings.Contains(output, ufmt.Sprintf(\"#%d:\", h)),\n\t\t\tufmt.Sprintf(\"block #%d should be absent from output\", h))\n\t}\n}\n\n// TestRender_ShowsAllWhenUnderLimit verifies that all buckets are displayed when\n// there are fewer than maxDisplay, and that no panic occurs from a negative offset.\nfunc TestRender_ShowsAllWhenUnderLimit(t *testing.T) {\n\tchanges = bptree.NewBPTree32()\n\tvp = poa.NewPoA()\n\n\tconst total = 5 // less than maxDisplay=10\n\n\tvals := generateTestValidators(total)\n\tbase := runtime.ChainHeight()\n\n\tfor i := 0; i \u003c total; i++ {\n\t\th := base + int64(i)\n\t\tchanges.Set(getBlockID(h), []change{\n\t\t\t{blockNum: h, validator: vals[i]},\n\t\t})\n\t}\n\n\toutput := Render(\"\")\n\n\tfor i := 0; i \u003c total; i++ {\n\t\th := base + int64(i)\n\t\tuassert.True(t, strings.Contains(output, ufmt.Sprintf(\"#%d:\", h)),\n\t\t\tufmt.Sprintf(\"expected block #%d in output\", h))\n\t}\n}\n\nfunc TestGetChanges_PanicsOnInvalidRange(cur realm, t *testing.T) {\n\tuassert.PanicsWithMessage(t, cur, \"invalid range: from must be \u003c= to\", func() {\n\t\tGetChanges(10, 5)\n\t})\n}\n\nfunc TestGetChanges_ClampsMaxInt64(t *testing.T) {\n\tchanges = bptree.NewBPTree32()\n\n\tvals := generateTestValidators(1)\n\n\t// Simulate a validator change at block math.MaxInt64-1 (the boundary value).\n\tchanges.Set(getBlockID(math.MaxInt64-1), []change{\n\t\t{blockNum: math.MaxInt64 - 1, validator: vals[0]},\n\t})\n\n\t// Passing math.MaxInt64 as \"to\" means \"get all updates from here onwards\".\n\t// The clamp (to = MaxInt64-1) must still include the boundary block.\n\tresult := GetChanges(math.MaxInt64-1, math.MaxInt64)\n\tuassert.Equal(t, 1, len(result))\n\tuassert.Equal(t, vals[0].Address, result[0].Address)\n}\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"G+o0L9fqLAV4Kgy29Lanmmmw47qXaVMmcrUm5gQ/QW8hpK1IfMqT7DKppQh998R2fEtGjAJ2Yal8TSVgy27mvQ=="}],"memo":""}},{"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/bitwise.gno (z.arr[0] = z.arr[0] \u003c\u003c n)\npackage issue5736_common\n\nimport (\n\tu256 \"gno.land/p/onbloc/uint256\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"5TJd32fJE9X/kdnS3t1BoMoR4XgE3zUKES6w9+V9qMwCEPtQt6cvb5cOerrem9oTtlBGIqj/GTBRyp7C5JjP9g=="}],"memo":""}},{"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\"\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":"bar_test.gno","body":"package issue5736_bar\n\nimport (\n\t\"testing\"\n)\n\nfunc TestCall(cur realm, t *testing.T) {\n\tgot := Call(cross(cur))\n\tif got != \"246\" {\n\t\tt.Fatalf(\"got %s, want 246\", got)\n\t}\n}\n"},{"name":"gnomod.toml","body":"module = \"gno.land/r/tests/issue5736_bar\"\ngno = \"0.9\"\n"}],"type":{"@type":"/gno.MemPackageType","value":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"YlCj+5VhWLe+U8SpuaVvRH5D2ys3TlmQgjMvA/FIylcWQXjD7PLyRk/If7vouB+Tr6dk9w6mtbgaJZbRXp8Hug=="}],"memo":""}},{"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\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"2iy8Ere/c8sjh0eGniMCgAaz0LqsEj+kEpzUzFawa88NrziHQozKsoiTzOo1hWv0T43RpdQQMRMOzw6F8u4euQ=="}],"memo":""}},{"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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"DPaZXDJF8fyWcMdjBnfLeN3PvPpkkCT4cKIRKjqBmMBKaQLiz/hhoJNP3XKBGdtP6/QSgBFGiWFscXYP9+LnRg=="}],"memo":""}},{"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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"Rzs67V3UAnmMP1UWGRPYTdKuiwYslkZ3NxBANquvJeN6IJ8M7LANx70pvfHSFHg6eB/rB7mg/Gb9yWHgY3vScA=="}],"memo":""}},{"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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"enkRHEbfMtIE0rLwu8QsQJdXwQFuC0BajPg4TOOkUJRjH5EnK7ebVV/DwdwGbHIOAMnwRyyT4mS1SxU+BFU6Kw=="}],"memo":""}},{"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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"E4lcT6GDfuCYlDlAmT7Bazi5NiKp2LiBAKCpODuxJLtCX4WQf8FW1oau1+GVHa+q+cHZajxi6/r0Ar4PWyWAUw=="}],"memo":""}},{"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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"LGMb1N1b5lu1ChnxeIIWZTiJhH4Zf/MexYXMXB6iU7csZeaGeNeTi4lAw8ZwKqwrKjGyg+gjkdHCtyMa52J+yw=="}],"memo":""}},{"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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"uTHvE7tKAZi56yinsvgzYKnRqG/bRhZCFYzROla/BkNtghhYhDMI+NBMMpg98UBxvim0Z9hHc76t0pETcWJBHA=="}],"memo":""}},{"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\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"/crWwIJg1fX2JMZiz/Rh91gQzin6HrzUM9ximi+AWCQxVljEHdhsHVyPd5gTPr9clDf3fb/UTnkquvih6Seu1A=="}],"memo":""}},{"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\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"ASfhL4eSGU0OrBLV9K1ja1fjtJTVWYECaDuIHtnPlldc/lpOodLQUZQs0IdpqTU/2ou5C7wwn78btPTA6YeClw=="}],"memo":""}},{"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\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"x5B+PwztOsDYSGCnzAl5gi3UEyubGErK0tJAbIxeHyYZhtvt7lZNrLtdji0cLY4MMex8G9B5x9T5rahRxIuXXQ=="}],"memo":""}},{"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\"\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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"iNREZ/XUj+W8xLFV9XrXaT1eo5oB5y3OcPbF2/gk2owhcxtR3jliLrB+C0RfhVdJXh9vQqWrD71uBRCugbXjDA=="}],"memo":""}},{"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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"M8joj/U2ET3pps8IHyTna25J/EGRj0S/mqOvYbjBY9FjAWb769iZ1wOPHXm3BCzbNm4ly2ADC/IAWsARtSD4Rw=="}],"memo":""}},{"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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"rfncDrGqMRUaioDu1SdbeNKkCF2n34hObHkuXqH2f991O/OhKhFQI8sPNVlZK78Z5w3gETtsU2bscZEwvPowzA=="}],"memo":""}},{"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":"MPUserAll"}},"send":"","max_deposit":""}],"fee":{"gas_wanted":"50000","gas_fee":"1ugnot"},"signatures":[{"pub_key":{"@type":"/tm.PubKeySecp256k1","value":"A+FhNtsXHjLfSJk1lB8FbiL4mGPjc50Kt81J7EKDnJ2y"},"signature":"LFCoR2ThZN6mdpVdcE0+OX37YBlZAUSPKV29GnmL1YdJivlQ20AW6gOv8db6dDZQSOHG5SgUhnT9cOH9GBT/Sw=="}],"memo":""}}]}}}}