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/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/maintenance/v4"
gno = "0.9"

[addpkg]
  creator = "g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct"
  height = 1562625
  max_deposit = "20000000ugnot"

maintenance.gno

// Package maintenance resolves milestones with a configurable reviewer quorum.
package maintenance

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

	"gno.land/p/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/budget/v3"
	"gno.land/p/moul/txlink/v0"
	"gno.land/p/nt/avl/v0"
	"gno.land/r/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/treasury/v4"
)

type Roles struct {
	Lane        string
	Coordinator address
	Reviewers   []address
	Quorum      int
}

type milestone struct {
	digest string
	votes  []string
	voters []address
}

type laneConfig struct {
	roles      Roles
	milestones *avl.Tree
}

type MilestoneView struct {
	Evidence    string
	Votes       []string
	Voters      []address
	Reservation treasury.ReservationView
	Pruned      bool
}

var (
	realmPath = unsafe.CurrentRealm().PkgPath()
	lanes     = avl.NewTree()
)

func PolicyPath() string {
	return realmPath
}

func Configure(cur realm, programID int64, lane string, coordinator address, reviewersCSV string, quorum int) {
	if callerAddress(cur) != treasury.GetProgram(programID).Sponsor {
		panic("only the program sponsor can configure maintenance")
	}
	parts := strings.SplitN(reviewersCSV, ",", 8)
	if len(parts) < 2 || len(parts) > 7 || quorum < 2 || quorum > len(parts) {
		panic("maintenance requires 2 to 7 reviewers and a quorum of 2 to the reviewer count")
	}
	reviewers := make([]address, len(parts))
	for i, part := range parts {
		reviewers[i] = address(strings.TrimSpace(part))
	}
	roles := Roles{Lane: lane, Coordinator: coordinator, Reviewers: reviewers, Quorum: quorum}
	requireRoles(roles)
	treasury.RegisterPolicy(cross(cur), programID, lane)
	lanes.Set(budget.PolicyLaneKey(programID, lane), &laneConfig{roles: roles, milestones: avl.NewTree()})
	chain.Emit("MaintenanceConfigured", "program", number(programID), "lane", lane,
		"coordinator", string(coordinator), "quorum", strconv.Itoa(quorum))
}

func SubmitMilestone(cur realm, programID int64, lane string, recipient address, amount, holdBlocks int64, proofDigest, memo string) (int64, int64) {
	caller := callerAddress(cur)
	p := mustLane(programID, lane)
	if caller != p.roles.Coordinator {
		panic("only the maintenance coordinator can submit")
	}
	item := &milestone{votes: make([]string, len(p.roles.Reviewers)), voters: make([]address, len(p.roles.Reviewers))}
	if item.deadlocked(p.roles, recipient) {
		panic("milestone recipient leaves too few eligible reviewers for quorum")
	}
	budget.RequireDigest(proofDigest)
	budget.RequirePositive(holdBlocks)
	deadline := budget.Add(runtime.ChainHeight(), holdBlocks)
	itemID, available := treasury.Reserve(cross(cur), programID, lane, recipient, amount, deadline, memo)
	evidence := budget.EvidenceCommitment(programID, lane, itemID, proofDigest)
	item.digest = evidence
	p.milestones.Set(number(itemID), item)
	chain.Emit("MilestoneSubmitted", "program", number(programID), "lane", lane, "item", number(itemID),
		"actor", string(caller), "evidence", evidence)
	return itemID, available
}

func Vote(cur realm, programID int64, lane string, itemID int64, evidence string, approve bool) string {
	caller := callerAddress(cur)
	p := mustLane(programID, lane)
	index := p.reviewerIndex(caller)
	item := p.mustMilestone(itemID)
	reservation := openReservation(programID, lane, itemID)
	if item.digest != evidence {
		panic("milestone evidence does not match")
	}
	if item.deadlocked(p.roles, reservation.Recipient) {
		releaseDeadlock(cur, programID, lane, itemID)
		return treasury.Rejected
	}
	if caller == reservation.Recipient {
		panic("recipient cannot review their own milestone")
	}
	if item.voted(caller) {
		panic("reviewer already voted")
	}
	if item.votes[index] != "" {
		panic("reviewer seat already voted on this milestone")
	}
	vote := treasury.Rejected
	if approve {
		vote = treasury.Approved
	}
	item.votes[index], item.voters[index] = vote, caller
	chain.Emit("MilestoneVote", "program", number(programID), "lane", lane, "item", number(itemID),
		"reviewer", string(caller), "decision", vote, "evidence", evidence)
	approvals, rejections, remaining := item.tally(p.roles.Reviewers, reservation.Recipient)
	switch {
	case approvals >= p.roles.Quorum:
		treasury.Approve(cross(cur), programID, lane, itemID)
		return treasury.Approved
	case rejections >= p.roles.Quorum:
		treasury.Reject(cross(cur), programID, lane, itemID)
		return treasury.Rejected
	case approvals+remaining < p.roles.Quorum && rejections+remaining < p.roles.Quorum:
		releaseDeadlock(cur, programID, lane, itemID)
		return treasury.Rejected
	}
	return treasury.Reserved
}

// ResolveDeadlock releases an open milestone when neither decision can reach quorum.
func ResolveDeadlock(cur realm, programID int64, lane string, itemID int64) {
	callerAddress(cur)
	p := mustLane(programID, lane)
	item := p.mustMilestone(itemID)
	if !item.deadlocked(p.roles, openReservation(programID, lane, itemID).Recipient) {
		panic("milestone can still reach quorum")
	}
	releaseDeadlock(cur, programID, lane, itemID)
}

func releaseDeadlock(cur realm, programID int64, lane string, itemID int64) {
	treasury.Reject(cross(cur), programID, lane, itemID)
	chain.Emit("MilestoneDeadlocked", "program", number(programID), "lane", lane, "item", number(itemID))
}

func openReservation(programID int64, lane string, itemID int64) treasury.ReservationView {
	reservation := treasury.GetReservation(programID, lane, itemID)
	if reservation.Status != treasury.Reserved || reservation.ExpiredAtHeight {
		panic("milestone is no longer open for review")
	}
	return reservation
}

func CancelMilestone(cur realm, programID int64, lane string, itemID int64) {
	caller := callerAddress(cur)
	p := mustLane(programID, lane)
	if caller != p.roles.Coordinator {
		panic("only the maintenance coordinator can cancel")
	}
	if p.mustMilestone(itemID).hasVotes() {
		panic("milestone can only be canceled before a vote")
	}
	treasury.Cancel(cross(cur), programID, lane, itemID)
}

func RotateReviewer(cur realm, programID int64, lane string, index int, newReviewer address) {
	caller := callerAddress(cur)
	if treasury.GetProgram(programID).Sponsor != caller {
		panic("only the program sponsor can rotate reviewers")
	}
	p := mustLane(programID, lane)
	if index < 0 || index >= len(p.roles.Reviewers) {
		panic("reviewer index is out of range")
	}
	roles := GetRoles(programID, lane)
	old := roles.Reviewers[index]
	roles.Reviewers[index] = newReviewer
	requireRoles(roles)
	p.roles = roles
	chain.Emit("ReviewerRotated", "program", number(programID), "lane", roles.Lane,
		"index", strconv.Itoa(index), "old_reviewer", string(old), "reviewer", string(newReviewer))
}

func RotateCoordinator(cur realm, programID int64, lane string, newCoordinator address) {
	if callerAddress(cur) != treasury.GetProgram(programID).Sponsor {
		panic("only the program sponsor can rotate the coordinator")
	}
	p := mustLane(programID, lane)
	roles := p.roles
	roles.Coordinator = newCoordinator
	requireRoles(roles)
	p.roles.Coordinator = newCoordinator
	chain.Emit("CoordinatorRotated", "program", number(programID), "lane", lane, "coordinator", string(newCoordinator))
}

func PruneClosed(cur realm, programID int64, lane string) int64 {
	caller := callerAddress(cur)
	program := treasury.GetProgram(programID)
	if caller != program.Sponsor {
		panic("only the program sponsor can prune maintenance")
	}
	p := mustLane(programID, lane)
	if program.Status != treasury.Closed || program.Balance.Claimable != 0 ||
		program.ActiveReservations != 0 || p.milestones == nil {
		panic("pruning requires an unpruned closed lane with no unpaid claims or pending reservations")
	}
	count := int64(p.milestones.Size())
	p.milestones = nil
	chain.Emit("MaintenancePruned", "program", number(programID), "lane", lane, "items", number(count))
	return count
}

func GetRoles(programID int64, lane string) Roles {
	roles := mustLane(programID, lane).roles
	roles.Reviewers = append([]address(nil), roles.Reviewers...)
	return roles
}

func GetMilestone(programID int64, lane string, itemID int64) MilestoneView {
	p := mustLane(programID, lane)
	if p.milestones == nil || treasury.GetProgram(programID).Pruned {
		return MilestoneView{Pruned: true}
	}
	item := p.mustMilestone(itemID)
	return MilestoneView{Evidence: item.digest, Votes: append([]string(nil), item.votes...),
		Voters: append([]address(nil), item.voters...), Reservation: treasury.GetReservation(programID, lane, itemID)}
}

func Render(path string) string {
	program, names, itemID := treasury.PolicyRenderRoute(path, realmPath)
	if len(names) == 0 {
		return "# Maintenance\n\nOpen a configured lane with `:programID/lane` or a milestone with `:programID/lane/itemID`."
	}
	if len(names) > 1 {
		return "# Maintenance lanes\n\n" + budget.PolicyLaneLinks(realmPath, program.ID, names)
	}
	id, lane := program.ID, names[0]
	p := mustLane(id, lane)
	tx := txlink.Realm(realmPath)
	args := []string{"programID", number(id), "lane", lane}
	if itemID == 0 {
		var page strings.Builder
		page.WriteString("# Maintenance · Program " + number(id) + "\n\n**Lane** " + budget.MarkdownText(p.roles.Lane) +
			" · **Quorum** " + strconv.Itoa(p.roles.Quorum) + " of " + strconv.Itoa(len(p.roles.Reviewers)) + " reviewers\n\n| Role | Address |\n| --- | --- |\n| Coordinator | " + string(p.roles.Coordinator) + " |\n")
		for i, reviewer := range p.roles.Reviewers {
			page.WriteString("| Reviewer " + strconv.Itoa(i+1) + " | " + string(reviewer) + " |\n")
		}
		page.WriteString("\n[Rotate a reviewer](" + tx.Call("RotateReviewer", args...) + ") · [Rotate coordinator](" +
			tx.Call("RotateCoordinator", args...) + ")")
		if program.Status == treasury.Active {
			page.WriteString(" · [Submit a milestone](" + tx.Call("SubmitMilestone", args...) + ")")
		}
		if program.Status == treasury.Closed && program.Balance.Claimable == 0 && p.milestones != nil {
			page.WriteString("\n[Prune milestones](" + tx.Call("PruneClosed", args...) + ")")
		}
		return page.String() + "\n"
	}
	if program.Pruned || p.milestones == nil {
		return "# Maintenance\n\nMilestone records were pruned."
	}
	item := p.milestone(itemID)
	if item == nil {
		return "# Maintenance\n\nMilestone not found."
	}
	m := GetMilestone(id, lane, itemID)
	var page strings.Builder
	page.WriteString("# Milestone " + number(itemID) + "\n\n**Status** " + m.Reservation.Status +
		" · **Amount** " + budget.MarkdownText(program.FormatAmount(m.Reservation.Amount)) +
		"\n\n**Memo** " + budget.MarkdownText(m.Reservation.Memo) +
		"\n\n**Evidence** `" + m.Evidence + "`\n\n| Reviewer seat | Current address | Vote | Signed by |\n| --- | --- | --- | --- |\n")
	for i, reviewer := range p.roles.Reviewers {
		vote, signer := m.Votes[i], m.Voters[i]
		if vote == "" {
			vote = "—"
			if reviewer == m.Reservation.Recipient {
				vote = "Recipient · ineligible"
			} else if item.voted(reviewer) {
				vote = "Already voted"
			}
		}
		page.WriteString("| " + strconv.Itoa(i+1) + " | " + string(reviewer) + " | " + vote + " | " + string(signer) + " |\n")
	}
	if m.Reservation.Status == treasury.Reserved && !m.Reservation.ExpiredAtHeight {
		args = append(args, "itemID", number(itemID))
		if item.deadlocked(p.roles, m.Reservation.Recipient) {
			page.WriteString("\n[Resolve deadlock](" + tx.Call("ResolveDeadlock", args...) + ")\n")
			return page.String()
		}
		if !item.hasVotes() {
			page.WriteString("\n[Cancel milestone](" + tx.Call("CancelMilestone", args...) + ")\n")
		}
		args = append(args, "evidence", m.Evidence)
		page.WriteString("\n[Vote to approve](" + tx.Call("Vote", append(args, "approve", "true")...) +
			") · [Vote to reject](" + tx.Call("Vote", append(args, "approve", "false")...) + ")\n")
	}
	return page.String()
}

func requireRoles(roles Roles) {
	budget.RequireAddress(roles.Coordinator)
	for i, reviewer := range roles.Reviewers {
		budget.RequireAddress(reviewer)
		if reviewer == roles.Coordinator {
			panic("coordinator cannot be a reviewer")
		}
		for _, previous := range roles.Reviewers[:i] {
			if reviewer == previous {
				panic("reviewers must be distinct")
			}
		}
	}
}

func (item *milestone) hasVotes() bool {
	for _, vote := range item.votes {
		if vote != "" {
			return true
		}
	}
	return false
}

func (item *milestone) voted(caller address) bool {
	for _, voter := range item.voters {
		if voter == caller {
			return true
		}
	}
	return false
}

// Votes belong to their signer and occupy a seat even if its reviewer changes.
func (item *milestone) tally(reviewers []address, recipient address) (approvals, rejections, remaining int) {
	for i, vote := range item.votes {
		switch vote {
		case treasury.Approved:
			approvals++
		case treasury.Rejected:
			rejections++
		default:
			if reviewers[i] != recipient && !item.voted(reviewers[i]) {
				remaining++
			}
		}
	}
	return
}

func (item *milestone) deadlocked(roles Roles, recipient address) bool {
	approvals, rejections, remaining := item.tally(roles.Reviewers, recipient)
	return approvals+remaining < roles.Quorum && rejections+remaining < roles.Quorum
}

func mustLane(programID int64, lane string) *laneConfig {
	p, _ := lanes.Get(budget.PolicyLaneKey(programID, lane)).(*laneConfig)
	if p == nil {
		panic("maintenance lane is not configured")
	}
	return p
}

func (p *laneConfig) milestone(itemID int64) *milestone {
	if p.milestones == nil {
		return nil
	}
	item, _ := p.milestones.Get(number(itemID)).(*milestone)
	return item
}

func (p *laneConfig) mustMilestone(itemID int64) *milestone {
	item := p.milestone(itemID)
	if item == nil {
		panic("milestone not found")
	}
	return item
}

func (p *laneConfig) reviewerIndex(caller address) int {
	for i, reviewer := range p.roles.Reviewers {
		if reviewer == caller {
			return i
		}
	}
	panic("only a registered maintenance reviewer can vote")
}

func callerAddress(cur realm) address {
	if !cur.IsCurrent() || cur.PkgPath() != realmPath {
		panic("invalid maintenance context")
	}
	if len(unsafe.OriginSend()) != 0 {
		panic("unexpected attached coins")
	}
	return cur.Previous().Address()
}

func number(n int64) string {
	return strconv.FormatInt(n, 10)
}