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

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

Playground

gnomod.toml

module = "gno.land/r/nym-gfanton001/gnotif/v1"
gno = "0.9"

[addpkg]
  creator = "g18me5p9kqqxyswd8ytrmlv3q8kvy7uacx2v90ne"
  height = 665398
  max_deposit = "20000000ugnot"

gnotif.gno

// Package gnotif is a registry of notification triggers. Each trigger names
// a realm and an event type to watch, and the text of the notification that
// gnotif servers send when a matching event lands on chain. A later registry
// version follows the rules in
// https://gnotif.xyz/docs/how-it-works/#rules-for-a-new-registry-version.
package gnotif

import (
	"chain"
	"chain/runtime"
	"chain/runtime/unsafe"
	"strings"

	"gno.land/p/nym-gfanton001/gnotif/trigger/v0"
	"gno.land/p/nt/bptree/v0"
	"gno.land/p/nt/seqid/v0"
	"gno.land/r/sys/names"
)

// Subpath is the subpath of a realm's gnotif identity: me := cur.Sub(gnotif.Subpath).
const Subpath = "gnotif"

// Trigger is an alias, so a dapp imports only the registry.
type Trigger = trigger.Trigger

// Handle changes the triggers of the realm that opened it. Each method also
// needs that realm's gnotif identity as its caller, so the pointer alone is
// useless to any other realm.
type Handle struct {
	target   string
	approver string // the namespace owner who signed the Open
}

var (
	triggers bptree.BPTree // id → record.encode()
	byTarget bptree.BPTree // target → []string of its active ids, oldest first
	handles  bptree.BPTree // target → its live *Handle
	lastID   seqid.ID
)

// idPrefix is the last element of the registry's path and a dash, such as
// "v1-": gnotifd takes an id only from the registry version it names.
var idPrefix = selfPath[strings.LastIndex(selfPath, "/")+1:] + "-"

// Open returns the handle that changes the triggers of the realm whose gnotif
// identity calls it. It panics while the realm holds a handle its namespace
// owner has not revoked. It also panics outside the owner's deploy of the
// realm and outside a call the owner signed and sent straight to the realm.
// r/sys/names says who the owner is.
func Open(cur realm) *Handle {
	me := cur.Previous()
	target := targetOf(0, me)
	if handles.Has(target) {
		panic(target + " already holds a handle: its namespace owner can Revoke it")
	}
	mustOwnerEntered(0, me, target)
	h := &Handle{target: target, approver: unsafe.OriginCaller().String()}
	handles.Set(target, h)
	return h
}

// Set stores t under name and returns its id. A new name gets a new id. On a
// name in use, t must watch the same event, filter and param: the id stays,
// so users who turned the trigger on keep it.
func (h *Handle) Set(cur realm, name string, t Trigger) string {
	h.mustHold(cur.Previous().PkgPath())
	if !validName(name, 1, maxName) {
		panic("invalid name")
	}
	validate(t)
	r := record{Target: h.target, Name: name, T: t}
	ids := activeOf(h.target)
	if id, old, ok := find(ids, name); ok {
		if old.T == t {
			return id
		}
		if old.T.Event != t.Event || old.T.Filter != t.Filter || old.T.Param != t.Param {
			panic(name + " watches a different event, filter or param: Remove it, then Set it again")
		}
		store(id, r, h.approver)
		return id
	}
	if len(ids) >= maxPerTarget {
		panic("too many triggers for target")
	}
	id := idPrefix + lastID.Next().String()
	store(id, r, h.approver)
	byTarget.Set(h.target, append(ids, id))
	return id
}

// Remove removes the trigger under name, and with it every user's choice to
// receive it.
func (h *Handle) Remove(cur realm, name string) {
	h.mustHold(cur.Previous().PkgPath())
	if !validName(name, 1, maxName) {
		panic("invalid name")
	}
	id, _, ok := find(activeOf(h.target), name)
	if !ok {
		panic(name + " is not a trigger of " + h.target)
	}
	removeIDs(h.target, id)
}

// mustHold panics unless h is its realm's live handle and caller is that
// realm's gnotif identity.
func (h *Handle) mustHold(caller string) {
	if handles.Get(h.target) != h {
		panic("not the live handle of " + h.target)
	}
	if caller != h.target+"#"+Subpath {
		panic("not the gnotif identity of " + h.target + ": " + caller)
	}
}

// Drop removes target's listed active triggers, ids separated by commas.
// Spaces around an id are ignored. Only target's namespace owner may call it,
// directly, with their own key. r/sys/names says who the owner is, and while
// it is not enabled nobody is. A call that lists an id more than once, or one
// that is not an active trigger of target, removes nothing. Drop leaves the realm's handle live: Revoke stops the realm
// from setting them again.
func Drop(cur realm, target, ids string) {
	mustOwn(cur, target)
	live := make(map[string]bool)
	for _, id := range activeOf(target) {
		live[id] = true
	}
	dropped := strings.Split(ids, ",")
	for i, id := range dropped {
		id = strings.TrimSpace(id)
		dropped[i] = id
		if !live[id] {
			panic(id + " is not an active trigger of " + target)
		}
		live[id] = false
	}
	removeIDs(target, dropped...)
}

// Revoke ends target's handle: its methods panic from then on, and target's
// triggers stay. The realm can Open a new handle. Only target's namespace
// owner may call it, directly, with their own key. r/sys/names says who the
// owner is, and while it is not enabled nobody is.
func Revoke(cur realm, target string) {
	mustOwn(cur, target)
	if _, removed := handles.Remove(target); !removed {
		panic(target + " holds no handle")
	}
}

// Active lists target's active trigger ids, comma-separated, oldest first.
func Active(target string) string {
	return strings.Join(activeOf(target), ",")
}

func activeOf(target string) []string {
	ids, _ := byTarget.Get(target).([]string)
	return ids
}

// ceiling: decodes up to maxPerTarget records per lookup; index target and
// name to id before raising maxPerTarget.
func find(ids []string, name string) (string, record, bool) {
	for _, id := range ids {
		if r := decodeRecord(triggers.Get(id)); r.Name == name {
			return id, r, true
		}
	}
	return "", record{}, false
}

// targetOf returns the realm whose gnotif identity me is, and panics for any
// other caller.
func targetOf(_ int, me realm) string {
	path := me.PkgPath()
	host, subpath, _ := chain.SplitPkgSubPath(path)
	if subpath != Subpath || !validTarget(host) {
		panic("call with this realm's gnotif identity (me := cur.Sub(gnotif.Subpath), then cross(me)); got " + path)
	}
	return host
}

// mustOwnerEntered panics unless target's namespace owner signed the
// transaction with its own key and called target's realm directly.
func mustOwnerEntered(_ int, me realm, target string) {
	if _, _, _, isSession := runtime.GetSessionInfo(); isSession {
		panic("signed with a session key: sign with the namespace owner's own key")
	}
	signer := unsafe.OriginCaller()
	if ns := namespaceOf(target); !names.IsAuthorizedAddressForNamespace(signer, ns) {
		panic(signer.String() + " is not authorized for namespace " + ns)
	}
	// The Previous of a gnotif identity is the caller of its host realm.
	entry := me.Previous()
	if !entry.IsUserCall() || entry.Address() != signer {
		panic("the dapp was not entered directly by its namespace owner; entered from " + entry.PkgPath())
	}
}

// mustOwn panics unless target's namespace owner called straight into the
// registry with its own key.
func mustOwn(cur realm, target string) {
	caller := cur.Previous()
	if !caller.IsUserCall() {
		panic("only the namespace owner may do this, in a call signed with its own key; got " + caller.PkgPath())
	}
	if _, _, _, isSession := runtime.GetSessionInfo(); isSession {
		panic("sign with the namespace owner's own key, not a session key")
	}
	// Before Enable, names authorizes every key for every namespace.
	if !names.IsEnabled() {
		panic("r/sys/names is not enabled, so no namespace has an owner")
	}
	if ns := namespaceOf(target); !names.IsAuthorizedAddressForNamespace(caller.Address(), ns) {
		panic(caller.Address().String() + " is not authorized for namespace " + ns)
	}
}

// store writes r under id and emits TriggerDeclared.
func store(id string, r record, approver string) {
	triggers.Set(id, r.encode())
	chain.Emit("TriggerDeclared",
		"id", id,
		"target", r.Target,
		"name", r.Name,
		"event", r.T.Event,
		"filter", r.T.Filter,
		"param", r.T.Param,
		"title", r.T.Title,
		"body", r.T.Body,
		"link", r.T.Link,
		"declarer", chain.PackageAddress(r.Target).String(),
		"verified", "true",
		"approver", approver,
	)
}

// removeIDs removes the listed active ids of target and emits TriggerRemoved
// for each.
func removeIDs(target string, ids ...string) {
	gone := make(map[string]bool, len(ids))
	for _, id := range ids {
		gone[id] = true
	}
	var left []string
	for _, id := range activeOf(target) {
		if !gone[id] {
			left = append(left, id)
		}
	}
	if len(left) == 0 {
		byTarget.Remove(target)
	} else {
		byTarget.Set(target, left)
	}
	for _, id := range ids {
		triggers.Remove(id)
		chain.Emit("TriggerRemoved", "id", id)
	}
}

record.gno

package gnotif

import (
	"strconv"
	"strings"
)

const recordFields = 8

// record is a trigger, its target and its name as the registry stores them:
// one string per trigger, because a tree holds a string inline and a struct
// is one more stored object.
type record struct {
	Target string
	Name   string
	T      Trigger
}

func (r record) encode() string {
	return packFields(r.Target, r.Name, r.T.Event, r.T.Filter, r.T.Param, r.T.Title, r.T.Body, r.T.Link)
}

// decodeRecord reads a string made by encode and panics on any other.
func decodeRecord(v any) record {
	f := unpackFields(v.(string), recordFields)
	return record{
		Target: f[0],
		Name:   f[1],
		T:      Trigger{Event: f[2], Filter: f[3], Param: f[4], Title: f[5], Body: f[6], Link: f[7]},
	}
}

// packFields writes each field as its byte length, a colon and the field, so
// a field may hold colons and digits.
func packFields(fields ...string) string {
	var b strings.Builder
	for _, f := range fields {
		b.WriteString(strconv.Itoa(len(f)) + ":" + f)
	}
	return b.String()
}

// unpackFields reads exactly n fields made by packFields and panics on any
// other string.
func unpackFields(s string, n int) []string {
	fields := make([]string, n)
	for i := range fields {
		field, rest, ok := cutField(s)
		if !ok {
			panic("corrupt record")
		}
		fields[i], s = field, rest
	}
	if s != "" {
		panic("corrupt record")
	}
	return fields
}

func cutField(s string) (field, rest string, ok bool) {
	length, body, found := strings.Cut(s, ":")
	if !found {
		return "", "", false
	}
	n, err := strconv.Atoi(length)
	if err != nil || n < 0 || n > len(body) {
		return "", "", false
	}
	return body[:n], body[n:], true
}

render.gno

package gnotif

import (
	"chain"
	"chain/runtime/unsafe"
	"strconv"
	"strings"

	"gno.land/p/nt/markdown/sanitize/v0"
)

const pageSize = 50

// Render serves "" (the first page), "page/N", "trigger/<id>" and
// "target/<path>".
func Render(path string) string {
	switch {
	case path == "":
		return renderPage(1)
	case strings.HasPrefix(path, "page/"):
		n, err := strconv.Atoi(strings.TrimPrefix(path, "page/"))
		if err != nil || n < 1 {
			return "Not found."
		}
		return renderPage(n)
	case strings.HasPrefix(path, "trigger/"):
		id := strings.TrimPrefix(path, "trigger/")
		v := triggers.Get(id)
		if v == nil {
			return "Not found."
		}
		return renderTrigger(id, decodeRecord(v))
	case strings.HasPrefix(path, "target/"):
		target := strings.TrimPrefix(path, "target/")
		ids := activeOf(target)
		if len(ids) == 0 {
			return "Not found."
		}
		return renderTarget(target, ids)
	}
	return "Not found."
}

// renderPage lists the triggers newest first, pageSize to a page.
func renderPage(n int) string {
	var b strings.Builder
	b.WriteString("# gnotif triggers\n\n")
	pages := (triggers.Size() + pageSize - 1) / pageSize
	if n > pages {
		b.WriteString("No triggers on this page.\n")
		return b.String()
	}
	triggers.ReverseIterateByOffset((n-1)*pageSize, pageSize, func(id string, v any) bool {
		writeLine(&b, id, decodeRecord(v))
		return false
	})
	if n < pages {
		b.WriteString("\n[Next page](" + selfPath + ":page/" + strconv.Itoa(n+1) + ")\n")
	}
	return b.String()
}

// renderTarget lists a realm's triggers, newest first. The cap on them keeps
// the page to one screen, so it is not paged.
func renderTarget(target string, ids []string) string {
	var b strings.Builder
	b.WriteString("# gnotif triggers for " + sanitize.InlineText(target) + "\n\n")
	for i := len(ids) - 1; i >= 0; i-- {
		writeLine(&b, ids[i], decodeRecord(triggers.Get(ids[i])))
	}
	b.WriteString("\n[All triggers](" + selfPath + ")\n")
	return b.String()
}

func writeLine(b *strings.Builder, id string, r record) {
	b.WriteString("- [**" + id + "**](" + selfPath + ":trigger/" + id + ") " +
		sanitize.InlineText(r.Target) + " · " + sanitize.InlineText(r.Name) + " · " + sanitize.InlineText(r.T.Event))
	if r.T.Param != "" {
		b.WriteString(" · param " + sanitize.InlineText(r.T.Param))
	}
	b.WriteString(" · ✓ verified · by " + chain.PackageAddress(r.Target).String() + "\n")
}

func renderTrigger(id string, r record) string {
	var b strings.Builder
	b.WriteString("# Trigger " + id + "\n\n")
	b.WriteString("- Target: " + sanitize.InlineText(r.Target) + "\n")
	b.WriteString("- Name: " + sanitize.InlineText(r.Name) + "\n")
	b.WriteString("- Event: " + sanitize.InlineText(r.T.Event) + "\n")
	b.WriteString("- Filter: " + sanitize.InlineText(r.T.Filter) + "\n")
	b.WriteString("- Param: " + sanitize.InlineText(r.T.Param) + "\n")
	b.WriteString("- Title: " + sanitize.InlineText(r.T.Title) + "\n")
	b.WriteString("- Body: " + sanitize.InlineText(r.T.Body) + "\n")
	b.WriteString("- Link: " + sanitize.InlineText(r.T.Link) + "\n")
	b.WriteString("- Declarer: " + chain.PackageAddress(r.Target).String() + "\n")
	b.WriteString("- ✓ verified\n")
	b.WriteString("\n[All triggers](" + selfPath + ")\n")
	return b.String()
}

// selfPath is this realm's path on gnoweb, read at package init: Render is not
// crossing, so reading it there would give the caller's path.
var selfPath = strings.TrimPrefix(unsafe.CurrentRealm().PkgPath(), "gno.land")

validate.gno

package gnotif

import "strings"

const (
	targetPrefix   = "gno.land/r/"
	maxTarget      = 249
	maxName        = 64
	maxFilterPairs = 8
	maxBody        = 255
	maxLink        = 256
	maxPerTarget   = 64
)

func validate(t Trigger) {
	switch {
	case !validName(t.Event, 1, maxName):
		panic("invalid event")
	case !validFilter(t.Filter):
		panic("invalid filter")
	case !validName(t.Param, 0, maxName):
		panic("invalid param")
	case !sized(t.Title, 1, maxName):
		panic("invalid title")
	case !sized(t.Body, 0, maxBody):
		panic("invalid body")
	case !validLink(t.Link):
		panic("invalid link")
	}
}

// namespaceOf returns the namespace a valid target lives in, and panics on a
// target that is not a valid realm path.
func namespaceOf(target string) string {
	if !validTarget(target) {
		panic("invalid target " + target)
	}
	namespace, _, _ := strings.Cut(target[len(targetPrefix):], "/")
	return namespace
}

func sized(s string, lo, hi int) bool {
	return len(s) >= lo && len(s) <= hi
}

// validTarget accepts a realm path whose segments each match the chain's
// Re_name, so a target names a path where a realm can exist.
func validTarget(target string) bool {
	if !strings.HasPrefix(target, targetPrefix) || len(target) > maxTarget {
		return false
	}
	rest := target[len(targetPrefix):]
	start := 0 // index of the current segment's first byte
	for i := 0; i <= len(rest); i++ {
		if i == len(rest) || rest[i] == '/' {
			if i == start || !isLowerAlnum(rest[i-1]) {
				return false
			}
			start = i + 1
			continue
		}
		c := rest[i]
		switch {
		case i == start:
			if !(c >= 'a' && c <= 'z') {
				return false
			}
		case c == '_' || c == '-':
			if !isLowerAlnum(rest[i-1]) {
				return false
			}
		case !isLowerAlnum(c):
			return false
		}
	}
	return true
}

func isLowerAlnum(c byte) bool {
	return c >= 'a' && c <= 'z' || c >= '0' && c <= '9'
}

// validName accepts identifier bytes only, so a name cannot carry spaces or
// symbols that imitate the verified mark in rendered output.
func validName(s string, lo, hi int) bool {
	if !sized(s, lo, hi) {
		return false
	}
	for i := 0; i < len(s); i++ {
		c := s[i]
		if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_') {
			return false
		}
	}
	return true
}

func validFilter(filter string) bool {
	if filter == "" {
		return true
	}
	pairs := strings.Split(filter, ",")
	if len(pairs) > maxFilterPairs {
		return false
	}
	for _, pair := range pairs {
		key, value, ok := strings.Cut(pair, "=")
		if !ok || !validName(key, 1, maxName) || !sized(value, 1, maxName) || strings.Contains(value, "=") {
			return false
		}
	}
	return true
}

// validLink accepts only a path, so a click always stays on the dapp's origin.
// "//host" starts with a slash yet resolves to another host. A URL parser
// drops tab, LF and CR and reads a backslash as a slash, so "/\t/host" and
// "/\host" would do the same; control bytes and backslashes are refused.
func validLink(link string) bool {
	if !sized(link, 1, maxLink) || !strings.HasPrefix(link, "/") || strings.HasPrefix(link, "//") {
		return false
	}
	for i := 0; i < len(link); i++ {
		if c := link[i]; c < 0x20 || c == 0x7f || c == '\\' {
			return false
		}
	}
	return true
}