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

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

optimistic.gno

// Package optimistic releases a proposal after its challenge window unless a guardian vetoes it.
package optimistic

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

	"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 Config struct {
	Lane            string
	Proposer        address
	Guardians       [2]address
	ChallengeBlocks int64
}

type proposal struct {
	digest       string
	challengeEnd int64
	vetoedBy     address
	vetoReason   string
	settled      bool
}

type ProposalView struct {
	Pruned       bool
	Evidence     string
	ChallengeEnd int64
	VetoedBy     address
	VetoReason   string
	Settled      bool
	Reservation  treasury.ReservationView
}

type laneConfig struct {
	config    Config
	proposals *avl.Tree
}

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

func Configure(cur realm, programID int64, lane string, proposer, guardian1, guardian2 address, challengeBlocks int64) {
	caller := callerAddress(cur)
	view := treasury.GetProgram(programID)
	if view.Sponsor != caller {
		panic("only the program sponsor can configure optimistic policy")
	}
	if challengeBlocks < 2 || challengeBlocks > view.MaxHoldBlocks-2 {
		panic("challenge window requires at least 2 blocks and a 2-block settlement buffer")
	}
	config := Config{Lane: lane, Proposer: proposer, Guardians: [2]address{guardian1, guardian2}, ChallengeBlocks: challengeBlocks}
	requireRoles(config)
	treasury.RegisterPolicy(cross(cur), programID, lane)
	lanes.Set(budget.PolicyLaneKey(programID, lane), &laneConfig{config: config, proposals: avl.NewTree()})
	chain.Emit("OptimisticConfigured", "program", number(programID), "lane", lane,
		"proposer", string(proposer), "guardian1", string(guardian1), "guardian2", string(guardian2),
		"challenge_blocks", number(challengeBlocks))
}

func Propose(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.config.Proposer {
		panic("only the optimistic proposer can submit")
	}
	if recipient == caller {
		panic("proposer cannot be the recipient")
	}
	if holdBlocks < p.config.ChallengeBlocks+2 {
		panic("hold must leave at least 2 blocks after the challenge window")
	}
	budget.RequireDigest(proofDigest)
	height := runtime.ChainHeight()
	challengeEnd := budget.Add(height, p.config.ChallengeBlocks)
	deadline := budget.Add(height, holdBlocks)
	itemID, available := treasury.Reserve(cross(cur), programID, lane, recipient, amount, deadline, memo)
	evidence := budget.EvidenceCommitment(programID, lane, itemID, proofDigest)
	p.proposals.Set(number(itemID), &proposal{digest: evidence, challengeEnd: challengeEnd})
	chain.Emit("OptimisticProposed", "program", number(programID), "lane", lane, "item", number(itemID),
		"actor", string(caller), "challenge_end", number(challengeEnd), "evidence", evidence)
	return itemID, available
}

// Veto can be used by either guardian, including a guardian named as recipient.
func Veto(cur realm, programID int64, lane string, itemID int64, reason string) {
	caller := callerAddress(cur)
	p := mustLane(programID, lane)
	if caller != p.config.Guardians[0] && caller != p.config.Guardians[1] {
		panic("only an optimistic guardian can veto")
	}
	item := p.mustProposal(itemID)
	if runtime.ChainHeight() >= item.challengeEnd {
		panic("challenge window has ended")
	}
	budget.RequireMemo(reason)
	treasury.Reject(cross(cur), programID, lane, itemID)
	item.vetoedBy, item.vetoReason = caller, reason
	chain.Emit("OptimisticVetoed", "program", number(programID), "lane", p.config.Lane,
		"item", number(itemID), "guardian", string(caller), "reason", reason)
}

func Settle(cur realm, programID int64, lane string, itemID int64) {
	caller := callerAddress(cur)
	p := mustLane(programID, lane)
	item := p.mustProposal(itemID)
	if item.vetoedBy != "" {
		panic("proposal was vetoed")
	}
	if item.settled {
		panic("proposal already settled")
	}
	if runtime.ChainHeight() < item.challengeEnd {
		panic("challenge window is still open")
	}
	treasury.Approve(cross(cur), programID, lane, itemID)
	item.settled = true
	chain.Emit("OptimisticSettled", "program", number(programID), "lane", p.config.Lane,
		"item", number(itemID), "actor", string(caller))
}

func CancelProposal(cur realm, programID int64, lane string, itemID int64) {
	caller := callerAddress(cur)
	p := mustLane(programID, lane)
	if caller != p.config.Proposer {
		panic("only the optimistic proposer can cancel")
	}
	p.mustProposal(itemID)
	treasury.Cancel(cross(cur), programID, lane, itemID)
}

func RotateGuardian(cur realm, programID int64, lane string, index int, newGuardian address) {
	caller := callerAddress(cur)
	if treasury.GetProgram(programID).Sponsor != caller {
		panic("only the program sponsor can rotate guardians")
	}
	p := mustLane(programID, lane)
	if index < 0 || index >= len(p.config.Guardians) {
		panic("guardian index must be 0 or 1")
	}
	config := p.config
	old := config.Guardians[index]
	config.Guardians[index] = newGuardian
	requireRoles(config)
	p.config = config
	chain.Emit("GuardianRotated", "program", number(programID), "lane", config.Lane,
		"index", strconv.Itoa(index), "old_guardian", string(old), "guardian", string(newGuardian))
}

func RotateProposer(cur realm, programID int64, lane string, newProposer address) {
	if callerAddress(cur) != treasury.GetProgram(programID).Sponsor {
		panic("only the program sponsor can rotate the proposer")
	}
	p := mustLane(programID, lane)
	config := p.config
	config.Proposer = newProposer
	requireRoles(config)
	p.config = config
	chain.Emit("ProposerRotated", "program", number(programID), "lane", lane, "proposer", string(newProposer))
}

func GetConfig(programID int64, lane string) Config {
	return mustLane(programID, lane).config
}

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 optimistic")
	}
	p := mustLane(programID, lane)
	if program.Status != treasury.Closed || program.Balance.Claimable != 0 ||
		program.ActiveReservations != 0 || p.proposals == nil {
		panic("pruning requires an unpruned closed lane with no unpaid claims or pending reservations")
	}
	count := int64(p.proposals.Size())
	p.proposals = nil
	chain.Emit("OptimisticPruned", "program", number(programID), "lane", lane, "items", number(count))
	return count
}

func GetProposal(programID int64, lane string, itemID int64) ProposalView {
	p := mustLane(programID, lane)
	if p.proposals == nil || treasury.GetProgram(programID).Pruned {
		return ProposalView{Pruned: true}
	}
	item := p.mustProposal(itemID)
	return ProposalView{Evidence: item.digest, ChallengeEnd: item.challengeEnd,
		VetoedBy: item.vetoedBy, VetoReason: item.vetoReason, Settled: item.settled,
		Reservation: treasury.GetReservation(programID, lane, itemID)}
}

func Render(path string) string {
	program, names, itemID := treasury.PolicyRenderRoute(path, realmPath)
	if len(names) == 0 {
		return "# Optimistic policy\n\nOpen a configured lane with `:programID/lane` or a proposal with `:programID/lane/itemID`."
	}
	if len(names) > 1 {
		return "# Optimistic policy 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 {
		config := p.config
		page := "# Optimistic policy · Program " + number(id) + "\n\n**Lane** " + budget.MarkdownText(config.Lane) +
			" · **Challenge window** " + number(config.ChallengeBlocks) + " blocks\n\n" +
			"| Role | Address |\n| --- | --- |\n| Proposer | " + string(config.Proposer) +
			" |\n| Guardian 1 | " + string(config.Guardians[0]) + " |\n| Guardian 2 | " + string(config.Guardians[1]) +
			" |\n\n[Rotate guardian](" + tx.Call("RotateGuardian", args...) + ") · [Rotate proposer](" +
			tx.Call("RotateProposer", args...) + ")"
		if program.Status == treasury.Active {
			page += " · [Propose spending](" + tx.Call("Propose", args...) + ")"
		}
		if program.Status == treasury.Closed && program.Balance.Claimable == 0 && p.proposals != nil {
			page += " · [Prune proposals](" + tx.Call("PruneClosed", args...) + ")"
		}
		return page + "\n"
	}
	if program.Pruned || p.proposals == nil {
		return "# Optimistic policy\n\nProposal records were pruned."
	}
	if p.proposal(itemID) == nil {
		return "# Optimistic policy\n\nProposal not found."
	}
	view := GetProposal(id, lane, itemID)
	reservation := view.Reservation
	page := "# Optimistic proposal " + number(itemID) + "\n\n**Status** " + reservation.Status +
		" · **Amount** " + budget.MarkdownText(program.FormatAmount(reservation.Amount)) +
		"\n\n**Challenge ends at block** " + number(view.ChallengeEnd) +
		" · **Reservation deadline** " + number(reservation.Deadline) +
		"\n\n**Memo** " + budget.MarkdownText(reservation.Memo) + "\n\n**Evidence** `" + view.Evidence + "`\n"
	if view.VetoedBy != "" {
		return page + "\n**Vetoed by** " + string(view.VetoedBy) + "\n\n**Reason** " + budget.MarkdownText(view.VetoReason) + "\n"
	}
	if reservation.ExpiredAtHeight {
		return page + "\nThis hold has reached its deadline and can be expired in the treasury.\n"
	}
	if reservation.Status != treasury.Reserved {
		return page
	}
	args = append(args, "itemID", number(itemID))
	page += "\n[Cancel proposal](" + tx.Call("CancelProposal", args...) + ")\n"
	if runtime.ChainHeight() < view.ChallengeEnd {
		return page + "\nThe challenge window is open. [Veto proposal](" + tx.Call("Veto", args...) + ")\n"
	}
	return page + "\nAnyone can [settle this proposal](" + tx.Call("Settle", args...) + ") before its deadline.\n"
}

func requireRoles(config Config) {
	budget.RequireAddress(config.Proposer)
	for _, guardian := range config.Guardians {
		budget.RequireAddress(guardian)
		if guardian == config.Proposer {
			panic("proposer cannot be a guardian")
		}
	}
	if config.Guardians[0] == config.Guardians[1] {
		panic("guardians must be distinct")
	}
}

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

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

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

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

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