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/v3"
gno = "0.9"

[addpkg]
  creator = "g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct"
  height = 1552686
  max_deposit = "40000000ugnot"

maintenance.gno

// Package maintenance requires two independent reviewers to resolve a milestone.
package maintenance

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

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

const packagePath = "gno.land/r/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/maintenance/v3"

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

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

type program struct {
	roles      Roles
	milestones map[int64]*milestone
}

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

var programs = make(map[int64]*program)

func Configure(cur realm, programID int64, lane string, coordinator, r1, r2, r3 address) {
	caller := userCaller(cur)
	config := treasury.GetProgram(programID)
	if config.Sponsor != caller {
		panic("only the program sponsor can configure maintenance")
	}
	if config.Status != treasury.Draft || programs[programID] != nil {
		panic("maintenance configuration requires an unconfigured draft")
	}
	roles := Roles{Lane: lane, Coordinator: coordinator, Reviewers: [3]address{r1, r2, r3}}
	requireRoles(roles)
	runtime.AssertOriginCall()
	treasury.RegisterPolicy(cross(cur), programID, lane)
	programs[programID] = &program{roles: roles, milestones: make(map[int64]*milestone)}
	chain.Emit("MaintenanceConfigured", "program", number(programID), "lane", lane, "coordinator", string(coordinator))
}

func SubmitMilestone(cur realm, programID int64, recipient address, amount, holdBlocks int64, proofDigest, memo string) (int64, int64) {
	caller := userCaller(cur)
	p := mustProgram(programID)
	if caller != p.roles.Coordinator {
		panic("only the maintenance coordinator can submit")
	}
	budget.RequireDigest(proofDigest)
	budget.RequirePositive(holdBlocks)
	deadline := budget.Add(runtime.ChainHeight(), holdBlocks)
	runtime.AssertOriginCall()
	itemID, available := treasury.Reserve(cross(cur), programID, recipient, amount, deadline, memo)
	lane := p.roles.Lane
	evidence := budget.EvidenceCommitment(programID, lane, itemID, proofDigest)
	p.milestones[itemID] = &milestone{digest: evidence}
	chain.Emit("MilestoneSubmitted", "program", number(programID), "lane", lane, "item", number(itemID),
		"actor", string(caller), "evidence", evidence)
	return itemID, available
}

func Vote(cur realm, programID, itemID int64, evidence string, approve bool) string {
	caller := userCaller(cur)
	p := mustProgram(programID)
	index := p.reviewerIndex(caller)
	item := p.mustMilestone(itemID)
	lane := p.roles.Lane
	reservation := treasury.GetReservation(programID, lane, itemID)
	if caller == reservation.Recipient {
		panic("recipient cannot review their own milestone")
	}
	if reservation.Status != treasury.Reserved || reservation.ExpiredAtHeight {
		panic("milestone is no longer open for review")
	}
	if item.digest != evidence {
		panic("milestone evidence does not match")
	}
	if item.voted(caller) {
		panic("reviewer already voted")
	}
	if item.votes[index] != "" {
		panic("reviewer seat already voted on this milestone")
	}
	runtime.AssertOriginCall()
	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 >= 2:
		treasury.Approve(cross(cur), programID, itemID)
		return treasury.Approved
	case rejections >= 2:
		treasury.Reject(cross(cur), programID, itemID)
		return treasury.Rejected
	case approvals+remaining < 2 && rejections+remaining < 2:
		treasury.Reject(cross(cur), programID, itemID)
		chain.Emit("MilestoneDeadlocked", "program", number(programID), "lane", lane, "item", number(itemID))
		return treasury.Rejected
	}
	return treasury.Reserved
}

func CancelMilestone(cur realm, programID, itemID int64) {
	caller := userCaller(cur)
	p := mustProgram(programID)
	if caller != p.roles.Coordinator {
		panic("only the maintenance coordinator can cancel")
	}
	if p.mustMilestone(itemID).votes != [3]string{} {
		panic("milestone can only be canceled before a vote")
	}
	runtime.AssertOriginCall()
	treasury.Cancel(cross(cur), programID, itemID)
}

func RotateReviewer(cur realm, programID int64, index int, newReviewer address) {
	caller := userCaller(cur)
	if treasury.GetProgram(programID).Sponsor != caller {
		panic("only the program sponsor can rotate reviewers")
	}
	p := mustProgram(programID)
	if index < 0 || index >= len(p.roles.Reviewers) {
		panic("reviewer index must be 0 to 2")
	}
	roles := p.roles
	old := roles.Reviewers[index]
	roles.Reviewers[index] = newReviewer
	requireRoles(roles)
	runtime.AssertOriginCall()
	p.roles = roles
	chain.Emit("ReviewerRotated", "program", number(programID), "lane", roles.Lane,
		"index", strconv.Itoa(index), "old_reviewer", string(old), "reviewer", string(newReviewer))
}

func GetRoles(programID int64) Roles {
	return mustProgram(programID).roles
}

func GetMilestone(programID, itemID int64) MilestoneView {
	p := mustProgram(programID)
	item := p.mustMilestone(itemID)
	return MilestoneView{Evidence: item.digest, Votes: item.votes, Voters: item.voters,
		Reservation: treasury.GetReservation(programID, p.roles.Lane, itemID)}
}

func Render(path string) string {
	id, itemID := budget.ParsePolicyViewPath(path)
	p := programs[id]
	if p == nil {
		return "# Maintenance\n\nOpen a configured program with `:programID` or a milestone with `:programID/itemID`."
	}
	program := treasury.GetProgram(id)
	tx := txlink.Realm(packagePath)
	args := []string{"programID", number(id)}
	if itemID == 0 {
		var page strings.Builder
		page.WriteString("# Maintenance · Program " + number(id) + "\n\n**Lane** " + budget.MarkdownText(p.roles.Lane) +
			" · **Quorum** two eligible 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...) + ")")
		if program.Status == treasury.Active {
			page.WriteString(" · [Submit a milestone](" + tx.Call("SubmitMilestone", args...) + ")")
		}
		return page.String() + "\n"
	}
	if program.Pruned {
		return "# Maintenance\n\nThe treasury pruned this program's reservation records."
	}
	item := p.milestones[itemID]
	if item == nil {
		return "# Maintenance\n\nMilestone not found."
	}
	m := GetMilestone(id, itemID)
	var page strings.Builder
	page.WriteString("# Milestone " + number(itemID) + "\n\n**Status** " + m.Reservation.Status +
		" · **Amount** " + budget.FormatUGNOT(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 m.Votes == [3]string{} {
			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) 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 [3]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 mustProgram(id int64) *program {
	p := programs[id]
	if p == nil {
		panic("maintenance is not configured for this program")
	}
	return p
}

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

func (p *program) 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 userCaller(cur realm) address {
	if !cur.IsCurrent() || cur.PkgPath() != packagePath || !cur.Previous().IsUserCall() {
		panic("direct maintenance call required")
	}
	if len(unsafe.OriginSend()) != 0 {
		panic("unexpected attached coins")
	}
	return cur.Previous().Address()
}

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