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

[addpkg]
  creator = "g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct"
  height = 1552677
  max_deposit = "50000000ugnot"

render.gno

package treasury

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

	"gno.land/p/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/budget/v2"
	"gno.land/p/moul/txlink/v0"
	"gno.land/p/nt/mdalert/v0"
	"gno.land/p/nt/ufmt/v0"
)

func Render(path string) string {
	path = strings.TrimPrefix(path, ":")
	height := runtime.ChainHeight()
	if path == "" {
		return renderDirectory(height)
	}
	parts := strings.SplitN(path, "/", 5)
	id, err := strconv.ParseInt(parts[0], 10, 64)
	p := findProgram(id)
	if err != nil || p == nil {
		return "# Shared Budget\n\nProgram not found."
	}
	switch len(parts) {
	case 1:
		return renderProgram(p, height)
	case 3:
		switch parts[1] {
		case "period":
			return renderPeriod(p, parts[2], height)
		case budget.RefundLane:
			if parts[2] == "0" {
				return renderRefund(p)
			}
		default:
			return renderItem(p, parts[1], parts[2], height)
		}
	case 4:
		if parts[1] == "check" {
			return renderCheck(p, parts[2], parts[3], height)
		}
	}
	return "# Shared Budget\n\nUse a program, item, period, or spending check link."
}

func renderDirectory(height int64) string {
	var table strings.Builder
	active := 0
	programs.ReverseIterate("", "", func(_ string, value any) bool {
		p := value.(*program)
		status := p.statusAt(height)
		if status == Active {
			active++
		}
		locked := p.ledger.Funded - p.ledger.Paid
		table.WriteString(ufmt.Sprintf("| [%s](%s) | %s | %d | %s |\n",
			programTitle(p), programURL(p.id), status, len(p.policies), budget.FormatUGNOT(locked)))
		return false
	})
	header := "# Shared Budget\n\n**Total value locked** " + budget.FormatUGNOT(outstanding) +
		" · **Active programs** " + budget.FormatInt(int64(active)) + " / " + budget.FormatInt(latestProgramID) +
		"\n\n" + txLink("Create a program", "CreateProgram") + "\n\n## Program Directory\n\n"
	if latestProgramID == 0 {
		return header + "No programs yet.\n"
	}
	return header + "| Program | Status | Policies | Locked |\n| --- | --- | ---: | ---: |\n" + table.String()
}

func renderProgram(p *program, height int64) string {
	view := p.view(height)
	id := number(p.id)
	var page strings.Builder
	page.WriteString("# " + programTitle(p) + "\n\n")
	page.WriteString(programStatus(view) + "\n")
	page.WriteString("**Sponsor** " + string(p.sponsor) + "\n\n")
	if view.Status != Draft {
		page.WriteString(ufmt.Sprintf("**Period** [%d](%s/period/%d) · **Issuance ends at block** %d · **Pending holds** %d\n\n",
			view.CurrentPeriod, programURL(p.id), view.CurrentPeriod, p.issueEnd, p.activeCount))
	}
	page.WriteString("## Fund allocation\n\n" + budget.AllocationBarSVG(p.ledger, p.reserveFloor) + "\n\n")
	page.WriteString("| Ledger state | Amount |\n| --- | ---: |\n")
	entries := []struct {
		label  string
		amount int64
	}{
		{"Funded", p.ledger.Funded}, {"Available", p.ledger.Available},
		{"Protected reserve floor", p.reserveFloor}, {"Reserved", p.ledger.Reserved},
		{"Claimable", p.ledger.Claimable}, {"Paid", p.ledger.Paid},
	}
	for _, entry := range entries {
		page.WriteString("| " + entry.label + " | " + budget.FormatUGNOT(entry.amount) + " |\n")
	}
	if len(view.Policies) == 0 {
		page.WriteString("\nAdd a policy lane to prepare this draft for funding.\n")
	}
	if view.Pruned {
		page.WriteString("\nReservation and period records were pruned. The final ledger and policy settings are available here.\n")
	}
	for _, rule := range view.Policies {
		renderPolicy(&page, p, rule)
	}
	refund := GetClaim(p.id, budget.RefundLane, 0)
	if refund.Exists {
		page.WriteString("\n[View sponsor refund](" + programURL(p.id) + "/refund/0)")
		if !refund.Paid {
			page.WriteString(" · " + txLink("Withdraw refund", "Withdraw", "programID", id, "lane", budget.RefundLane, "itemID", "0"))
		}
		page.WriteString("\n")
	}
	return page.String() + renderProgramActions(p, view.Status)
}

func programStatus(view ProgramView) string {
	switch view.Status {
	case Draft:
		return mdalert.Note("Draft", "The sponsor can add policies. Each policy must register before funding opens the program.")
	case Active:
		return mdalert.Success("Active", "Registered policies can reserve funds under their spending limits.")
	case IssuanceClosed:
		return mdalert.Warning("Issuance closed", "Pending reservations can still be resolved, and approved claims can be withdrawn.")
	default:
		return mdalert.Info("Closed", "Closed at block "+number(view.ClosedHeight)+" in period "+number(view.ClosedPeriod)+".")
	}
}

func renderProgramActions(p *program, status string) string {
	id := number(p.id)
	switch status {
	case Draft:
		actions := "\n" + txLink("Add a policy", "AddPolicy", "programID", id)
		if len(p.policies) > 0 {
			for _, rule := range p.policies {
				if !rule.registered {
					return actions + "\n"
				}
			}
			actions += " · " + txLink("Open and fund", "Open", "programID", id)
		}
		return actions + "\n"
	case Active:
		return "\n" + txLink("Top up", "Fund", "programID", id) + " · " +
			txLink("Update reserve floor", "UpdateReserveFloor", "programID", id) + " · " +
			txLink("Close issuance", "CloseIssuance", "programID", id) + "\n"
	case IssuanceClosed:
		if p.activeCount == 0 {
			return "\n" + txLink("Finalize closure", "FinalizeClose", "programID", id) + "\n"
		}
	case Closed:
		if p.canPrune() {
			return "\n" + txLink("Prune closed records", "PruneClosed", "programID", id) + "\n"
		}
	}
	return ""
}

func renderPolicy(page *strings.Builder, p *program, policy PolicyView) {
	lane := policy.Lane
	page.WriteString("\n## " + budget.MarkdownText(lane) + "\n\n")
	page.WriteString("[Policy and roles](" + strings.TrimPrefix(policy.Path, "gno.land") + ":" + number(p.id) + ")\n\n")
	if !policy.Registered {
		page.WriteString("Awaiting policy registration.\n\n")
	}
	floor := "protected reserve applies"
	color := "#2563eb"
	if policy.CanBreachFloor {
		floor = "can spend from protected reserve"
		color = "#b45309"
	}
	if !p.pruned {
		page.WriteString(budget.CapMeterSVG("Period budget", policy.Used, policy.PeriodCap, color) + "\n\n")
	}
	page.WriteString("**Item cap** " + budget.FormatUGNOT(policy.ItemCap) +
		" · **Period cap** " + budget.FormatUGNOT(policy.PeriodCap) + " · " + floor + "\n\n")
	page.WriteString("**Spending check** " + comparisonLinks(p.id, lane) + "\n")
	rule := p.rule(lane)
	if rule.items == nil || rule.items.Size() == 0 {
		return
	}
	offset := rule.items.Size() - 4
	if offset < 0 {
		offset = 0
	}
	recent := ListReservations(p.id, lane, offset, 4)
	page.WriteString("\n| Recent item | Amount | Status | Memo | Action |\n| --- | ---: | --- | --- | --- |\n")
	for _, item := range recent {
		memo := "—"
		if item.Memo != "" {
			memo = budget.MarkdownText(item.Memo)
		}
		page.WriteString(ufmt.Sprintf("| [%d](%s) | %s | %s | %s | %s |\n", item.ID, itemURL(p.id, lane, item.ID),
			budget.FormatUGNOT(item.Amount), item.Status, memo, itemAction(p.id, item)))
	}
}

func renderCheck(p *program, lane, rawAmount string, height int64) string {
	rule := p.findRule(lane)
	amount, err := strconv.ParseInt(rawAmount, 10, 64)
	header := "# Spending Check\n\n[Back to program](" + programURL(p.id) + ")\n\n"
	if rule == nil || err != nil || amount <= 0 {
		return header + "Choose a registered lane and enter a positive amount in ugnot."
	}
	period := p.periodAt(height)
	result := p.evaluate(rule, period, amount)
	maxAllowed := result.MaxAllowed
	shortfall := result.Shortfall
	alert := mdalert.Success("PASS", "The amount fits the lane and shared treasury limits.")
	switch {
	case p.statusAt(height) != Active || !rule.registered:
		alert = mdalert.Caution("FAIL", "The program is not accepting reservations in this lane.")
		maxAllowed, shortfall = 0, amount
	case !result.Allowed:
		alert = mdalert.Caution("FAIL", constraintLabel(result.BindingConstraint)+" limits this reservation.")
	}
	floorAvailable := budget.FormatUGNOT(result.PoolRoom)
	floorResult := guardResult(amount, result.PoolRoom)
	if rule.canBreachFloor {
		floorAvailable, floorResult = "Priority lane", "Bypassed"
	}
	return header + alert + "\n" +
		"**Lane** " + budget.MarkdownText(lane) + " · **Period** [" + number(period) + "](" +
		programURL(p.id) + "/period/" + number(period) + ")\n\n" +
		"**Requested** " + budget.FormatUGNOT(amount) + "\n\n" +
		"| Guardrail | Remaining room | Result |\n| --- | ---: | --- |\n" +
		guardRow("Item cap", result.ItemRoom, amount) +
		guardRow("Period budget", result.PeriodRoom, amount) +
		"| Reserve floor | " + floorAvailable + " | " + floorResult + " |\n" +
		guardRow("Shared available", p.ledger.Available, amount) + "\n" +
		"**Maximum reservable** " + budget.FormatUGNOT(maxAllowed) +
		" · **Shortfall** " + budget.FormatUGNOT(shortfall) + "\n\n" +
		"**Compare amounts** " + comparisonLinks(p.id, lane) + "\n"
}

func constraintLabel(constraint string) string {
	switch constraint {
	case "item_cap":
		return "Item cap"
	case "period_cap":
		return "Period budget"
	case "reserve_floor":
		return "Reserve floor"
	default:
		return "Shared available balance"
	}
}

func guardRow(label string, room, amount int64) string {
	return "| " + label + " | " + budget.FormatUGNOT(room) + " | " + guardResult(amount, room) + " |\n"
}

func guardResult(amount, room int64) string {
	if amount > room {
		return "Fail"
	}
	return "Pass"
}

func renderPeriod(p *program, rawPeriod string, height int64) string {
	period, err := strconv.ParseInt(rawPeriod, 10, 64)
	if err != nil || period < 0 || period > p.periodAt(height) || p.status == Draft {
		return "# Shared Budget\n\nPeriod not found."
	}
	header := "# Period " + number(period) + "\n\n[Back to program](" + programURL(p.id) + ")\n\n"
	if p.pruned {
		return header + "Period records were pruned."
	}
	var page strings.Builder
	page.WriteString(header + "| Lane | Used | Cap | Check |\n| --- | ---: | ---: | --- |\n")
	for _, row := range GetPeriodUsage(p.id, period) {
		page.WriteString(ufmt.Sprintf("| %s | %s | %s | %s |\n", budget.MarkdownText(row.Lane),
			budget.FormatUGNOT(row.Used), budget.FormatUGNOT(row.PeriodCap), comparisonLinks(p.id, row.Lane)))
	}
	return page.String() + renderProgramActions(p, p.statusAt(height))
}

func renderItem(p *program, lane, rawID string, height int64) string {
	rule := p.findRule(lane)
	if rule == nil {
		return "# Shared Budget\n\nPolicy lane not found."
	}
	if p.pruned {
		return "# Shared Budget\n\nReservation records were pruned. [View program summary](" + programURL(p.id) + ")."
	}
	id, err := strconv.ParseInt(rawID, 10, 64)
	item := rule.item(id)
	if err != nil || item == nil {
		return "# Shared Budget\n\nReservation not found."
	}
	view := item.view(lane, height)
	policyURL := strings.TrimPrefix(rule.path, "gno.land") + ":" + number(p.id) + "/" + number(id)
	return "# " + budget.MarkdownText(lane) + " · Item " + number(id) + "\n\n" +
		"[Program](" + programURL(p.id) + ") · [Policy record](" + policyURL + ")\n\n" +
		"| Reservation | Details |\n| --- | --- |\n" +
		"| Status | " + view.Status + " |\n| Recipient | " + string(view.Recipient) +
		" |\n| Amount | " + budget.FormatUGNOT(view.Amount) +
		" |\n| Period | [" + number(view.Period) + "](" + programURL(p.id) + "/period/" + number(view.Period) +
		") |\n| Deadline | " + number(view.Deadline) +
		" |\n| Memo | " + budget.MarkdownText(view.Memo) +
		" |\n| Paid | " + strconv.FormatBool(view.Paid) + " |\n\n" + itemAction(p.id, view) + "\n"
}

func renderRefund(p *program) string {
	header := "# Sponsor refund\n\n[Back to program](" + programURL(p.id) + ")\n\n"
	refund := GetClaim(p.id, budget.RefundLane, 0)
	if !refund.Exists {
		return header + "No refund claim."
	}
	page := header + "| Claim | Details |\n| --- | --- |\n| Recipient | " + string(refund.Recipient) +
		" |\n| Amount | " + budget.FormatUGNOT(refund.Amount) +
		" |\n| Paid | " + strconv.FormatBool(refund.Paid) + " |\n"
	if !refund.Paid {
		page += "\n" + txLink("Withdraw refund", "Withdraw", "programID", number(p.id), "lane", budget.RefundLane, "itemID", "0") + "\n"
	}
	return page
}

func itemAction(programID int64, item ReservationView) string {
	args := []string{"programID", number(programID), "lane", item.Lane, "itemID", number(item.ID)}
	switch {
	case item.ExpiredAtHeight:
		return txLink("Expire", "Expire", args...)
	case item.Status == Approved && !item.Paid:
		return txLink("Withdraw", "Withdraw", args...)
	default:
		return "—"
	}
}

func programTitle(p *program) string {
	if p.title == "" {
		return "Program " + number(p.id)
	}
	return budget.MarkdownText(p.title)
}

func programURL(id int64) string {
	return strings.TrimPrefix(packagePath, "gno.land") + ":" + number(id)
}

func itemURL(programID int64, lane string, itemID int64) string {
	return programURL(programID) + "/" + lane + "/" + number(itemID)
}

func comparisonLinks(id int64, lane string) string {
	path := programURL(id) + "/check/" + lane
	return "[200,000 ugnot](" + path + "/200000) · [100,000 ugnot](" + path + "/100000)"
}

func txLink(label, function string, args ...string) string {
	return "[" + label + "](" + txlink.Realm(packagePath).Call(function, args...) + ")"
}

treasury.gno

// Package treasury holds funds and accounts for reservations across independent policies.
package treasury

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

	"gno.land/p/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/budget/v2"
	"gno.land/p/nt/avl/v0"
)

const (
	packagePath             = "gno.land/r/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/treasury/v3"
	maxScheduleBlocks int64 = 2147483647
	maxPolicies             = 8

	Draft          = "draft"
	Active         = "active"
	IssuanceClosed = "issuance_closed"
	Closed         = "closed"

	Reserved = "reserved"
	Approved = "approved"
	Rejected = "rejected"
	Canceled = "canceled"
	Expired  = "expired"
)

type policy struct {
	lane           string
	path           string
	addr           address
	periodCap      int64
	itemCap        int64
	canBreachFloor bool
	registered     bool
	lastItemID     int64
	usage          *avl.Tree
	items          *avl.Tree
}

type claim struct {
	recipient address
	amount    int64
	paid      bool
}

type reservation struct {
	id       int64
	payment  claim
	status   string
	period   int64
	deadline int64
	memo     string
}

type program struct {
	id           int64
	sponsor      address
	title        string
	status       string
	reserveFloor int64
	periodBlocks int64
	issueBlocks  int64
	maxHold      int64
	start        int64
	issueEnd     int64
	closedHeight int64
	closedPeriod int64
	pruned       bool
	policies     []*policy
	ledger       budget.Ledger
	activeCount  int64
	refund       claim
}

var (
	programs        = avl.NewTree()
	latestProgramID int64
	outstanding     int64
)

func CreateProgram(cur realm, title string, reserveFloor, periodBlocks, issueBlocks, maxHold int64) int64 {
	sponsor := userCaller(cur, false)
	budget.RequireMemo(title)
	requireFloor(reserveFloor)
	if periodBlocks <= 0 || issueBlocks <= 0 || maxHold <= 0 {
		panic("program durations must be positive")
	}
	if periodBlocks > maxScheduleBlocks || issueBlocks > maxScheduleBlocks || maxHold > maxScheduleBlocks {
		panic("program durations cannot exceed 2147483647 blocks")
	}
	runtime.AssertOriginCall()
	id := budget.Add(latestProgramID, 1)
	programs.Set(numericKey(id), &program{
		id: id, sponsor: sponsor, title: title, status: Draft, reserveFloor: reserveFloor,
		periodBlocks: periodBlocks, issueBlocks: issueBlocks, maxHold: maxHold,
	})
	latestProgramID = id
	chain.Emit("ProgramCreated", "program", number(id), "sponsor", string(sponsor),
		"title", title, "reserve_floor", number(reserveFloor))
	return id
}

func AddPolicy(cur realm, programID int64, lane, policyPath string, periodCap, itemCap int64, canBreachFloor bool) {
	p := sponsorProgram(programID, userCaller(cur, false))
	if p.status != Draft {
		panic("policies can only be added to a draft")
	}
	if len(p.policies) == maxPolicies {
		panic("a program can have at most 8 policies")
	}
	budget.RequireLaneName(lane)
	requirePolicyPath(policyPath)
	if itemCap <= 0 || itemCap > periodCap {
		panic("policy caps require 0 < item cap <= period cap")
	}
	for _, rule := range p.policies {
		if lane == rule.lane {
			panic("policy lane already added")
		}
		if policyPath == rule.path {
			panic("policies must use distinct realm paths")
		}
	}
	runtime.AssertOriginCall()
	addr := chain.PackageAddress(policyPath)
	p.policies = append(p.policies, &policy{
		lane: lane, path: policyPath, addr: addr, periodCap: periodCap, itemCap: itemCap,
		canBreachFloor: canBreachFloor, usage: avl.NewTree(), items: avl.NewTree(),
	})
	chain.Emit("PolicyAdded", "program", number(programID), "lane", lane, "path", policyPath,
		"address", string(addr), "period_cap", number(periodCap), "item_cap", number(itemCap),
		"can_breach_floor", strconv.FormatBool(canBreachFloor))
}

func RegisterPolicy(cur realm, programID int64, lane string) {
	requireTreasury(cur)
	p := mustProgram(programID)
	rule := p.rule(lane)
	caller := cur.Previous()
	if !rule.matches(caller.PkgPath(), caller.Address()) {
		panic("caller is not the pinned policy for this lane")
	}
	if p.status != Draft || rule.registered {
		panic("policy registration requires an unconfigured draft")
	}
	rule.registered = true
	chain.Emit("PolicyRegistered", "program", number(programID), "lane", lane, "path", rule.path)
}

func Open(cur realm, programID int64) {
	sponsor := userCaller(cur, true)
	p := sponsorProgram(programID, sponsor)
	if p.status != Draft || len(p.policies) == 0 {
		panic("opening requires a draft with at least one policy")
	}
	for _, rule := range p.policies {
		if !rule.registered {
			panic("all policies must be registered before opening")
		}
	}
	amount := fundingAmount()
	runtime.AssertOriginCall()
	p.start = runtime.ChainHeight()
	p.issueEnd = budget.Add(p.start, p.issueBlocks)
	p.credit(amount)
	p.status = Active
	chain.Emit("ProgramOpened", "program", number(programID), "sponsor", string(sponsor),
		"amount", number(amount), "start", number(p.start), "issue_end", number(p.issueEnd))
}

func Fund(cur realm, programID int64) {
	sponsor := userCaller(cur, true)
	p := sponsorProgram(programID, sponsor)
	if p.statusAt(runtime.ChainHeight()) != Active {
		panic("program is not accepting funds")
	}
	amount := fundingAmount()
	runtime.AssertOriginCall()
	p.credit(amount)
	chain.Emit("ProgramFunded", "program", number(programID), "sponsor", string(sponsor), "amount", number(amount))
}

func UpdateReserveFloor(cur realm, programID, newFloor int64) {
	p := sponsorProgram(programID, userCaller(cur, false))
	if p.statusAt(runtime.ChainHeight()) != Active {
		panic("reserve floor can only be updated while active")
	}
	requireFloor(newFloor)
	runtime.AssertOriginCall()
	oldFloor := p.reserveFloor
	p.reserveFloor = newFloor
	chain.Emit("ReserveFloorUpdated", "program", number(programID), "old_floor", number(oldFloor), "reserve_floor", number(newFloor))
}

// Reserve assigns the next item ID in the caller's lane and returns it with the remaining available balance.
func Reserve(cur realm, programID int64, recipient address, amount, deadline int64, memo string) (int64, int64) {
	requireTreasury(cur)
	p := mustProgram(programID)
	rule := p.policyCaller(cur)
	height := runtime.ChainHeight()
	if p.statusAt(height) != Active {
		panic("program is not accepting reservations")
	}
	budget.RequireAddress(recipient)
	if recipient == cur.Address() {
		panic("the treasury cannot be an item recipient")
	}
	budget.RequirePositive(amount)
	budget.CheckDeadline(height, deadline, p.maxHold)
	budget.RequireMemo(memo)
	period := p.periodAt(height)
	check := p.evaluate(rule, period, amount)
	if !check.Allowed {
		switch check.BindingConstraint {
		case "item_cap":
			panic("item cap exceeded")
		case "period_cap":
			panic("period cap exceeded")
		case "reserve_floor":
			panic("reserve floor exceeded")
		default:
			panic("shared balance exceeded")
		}
	}

	id := budget.Add(rule.lastItemID, 1)
	item := &reservation{
		id: id, payment: claim{recipient: recipient, amount: amount}, status: Reserved,
		period: period, deadline: deadline, memo: memo,
	}
	p.ledger = p.ledger.Reserve(amount)
	p.activeCount = budget.Add(p.activeCount, 1)
	rule.usage.Set(numericKey(period), budget.Add(rule.used(period), amount))
	rule.items.Set(numericKey(id), item)
	rule.lastItemID = id
	emitItem("Reserved", programID, rule.lane, item)
	return id, p.ledger.Available
}

func Approve(cur realm, programID, itemID int64) {
	requireTreasury(cur)
	p := mustProgram(programID)
	rule := p.policyCaller(cur)
	item := rule.pendingBeforeDeadline(itemID)
	p.ledger = p.ledger.Approve(item.payment.amount)
	p.activeCount = budget.Subtract(p.activeCount, 1)
	item.status = Approved
	emitItem("Approved", programID, rule.lane, item)
}

func Reject(cur realm, programID, itemID int64) {
	requireTreasury(cur)
	p := mustProgram(programID)
	rule := p.policyCaller(cur)
	p.release(rule, rule.pendingBeforeDeadline(itemID), Rejected, "Rejected")
}

func Cancel(cur realm, programID, itemID int64) {
	requireTreasury(cur)
	p := mustProgram(programID)
	rule := p.policyCaller(cur)
	p.release(rule, rule.pendingBeforeDeadline(itemID), Canceled, "Canceled")
}

func Expire(cur realm, programID int64, lane string, itemID int64) {
	requireTreasury(cur)
	requireNoSend()
	p := mustProgram(programID)
	rule := p.rule(lane)
	item := rule.pending(itemID)
	if runtime.ChainHeight() < item.deadline {
		panic("reservation has not reached its deadline")
	}
	p.release(rule, item, Expired, "Expired")
}

func CloseIssuance(cur realm, programID int64) {
	sponsor := userCaller(cur, false)
	p := sponsorProgram(programID, sponsor)
	if p.statusAt(runtime.ChainHeight()) != Active {
		panic("issuance is not active")
	}
	runtime.AssertOriginCall()
	p.status = IssuanceClosed
	chain.Emit("IssuanceClosed", "program", number(programID), "sponsor", string(sponsor))
}

// FinalizeClose creates a sponsor refund and freezes the period displayed for the program.
func FinalizeClose(cur realm, programID int64) {
	requireTreasury(cur)
	requireNoSend()
	p := mustProgram(programID)
	height := runtime.ChainHeight()
	if p.statusAt(height) != IssuanceClosed {
		panic("close issuance before finalization")
	}
	if p.activeCount != 0 {
		panic("program still has active reservations")
	}
	amount := p.ledger.Available
	if amount > 0 {
		p.refund = claim{recipient: p.sponsor, amount: amount}
	}
	p.ledger = p.ledger.RefundAvailable()
	p.closedPeriod = p.periodAt(height)
	p.closedHeight = height
	p.status = Closed
	chain.Emit("ProgramClosed", "program", number(programID), "actor", string(cur.Previous().Address()),
		"refund", number(amount), "closed_height", number(height), "closed_period", number(p.closedPeriod))
}

// Withdraw pays an approved claim. Use lane "refund" and item ID 0 for the sponsor refund.
func Withdraw(cur realm, programID int64, lane string, itemID int64) {
	requireTreasury(cur)
	requireNoSend()
	caller := cur.Previous().Address()
	p := mustProgram(programID)
	payment := p.findClaim(lane, itemID)
	if payment == nil || payment.recipient != caller {
		panic("claim is payable only to its recipient")
	}
	if payment.paid {
		panic("claim already paid")
	}
	p.ledger = p.ledger.Pay(payment.amount)
	outstanding = budget.Subtract(outstanding, payment.amount)
	payment.paid = true
	coins := chain.Coins{chain.NewCoin(budget.Denom, payment.amount)}
	banker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(cur.Address(), payment.recipient, coins)
	chain.Emit("Withdrawn", "program", number(programID), "lane", lane, "item", number(itemID),
		"recipient", string(caller), "amount", number(payment.amount))
}

func PruneClosed(cur realm, programID int64) int64 {
	p := sponsorProgram(programID, userCaller(cur, false))
	if !p.canPrune() {
		panic("pruning requires an unpruned closed program with no unpaid claims or pending reservations")
	}
	runtime.AssertOriginCall()
	count := int64(0)
	for _, rule := range p.policies {
		count = budget.Add(count, int64(rule.items.Size()))
		rule.items = nil
		rule.usage = nil
	}
	p.pruned = true
	chain.Emit("ProgramPruned", "program", number(programID), "items", number(count))
	return count
}

func (p *program) canPrune() bool {
	return p.status == Closed && p.ledger.Claimable == 0 && p.activeCount == 0 && !p.pruned
}

func requireFloor(floor int64) {
	if floor < 0 {
		panic("reserve floor must be non-negative")
	}
}

func requirePolicyPath(path string) {
	const prefix = "gno.land/r/"
	if len(path) > 256 || !strings.HasPrefix(path, prefix) || path == packagePath {
		panic("expected a versioned policy realm path")
	}
	parts := strings.Split(path[len(prefix):], "/")
	last := len(parts) - 1
	if last < 1 || !versionSuffix(parts[last]) || versionSuffix(parts[last-1]) {
		panic("expected a versioned policy realm path")
	}
	for _, part := range parts {
		if !validPathSegment(part) {
			panic("expected a versioned policy realm path")
		}
	}
}

func versionSuffix(part string) bool {
	if part == "v0" {
		return true
	}
	if len(part) < 2 || part[0] != 'v' || part[1] < '1' || part[1] > '9' {
		return false
	}
	for i := 2; i < len(part); i++ {
		if part[i] < '0' || part[i] > '9' {
			return false
		}
	}
	return true
}

// Each Gno package path segment starts with a letter and has interior separators only.
func validPathSegment(part string) bool {
	if part == "" || part[0] < 'a' || part[0] > 'z' {
		return false
	}
	separator := false
	for i := 1; i < len(part); i++ {
		c := part[i]
		switch {
		case c >= 'a' && c <= 'z', c >= '0' && c <= '9':
			separator = false
		case (c == '-' || c == '_') && !separator:
			separator = true
		default:
			return false
		}
	}
	return !separator
}

func (p *program) credit(amount int64) {
	p.ledger = p.ledger.Fund(amount)
	outstanding = budget.Add(outstanding, amount)
}

func (p *program) release(rule *policy, item *reservation, status, event string) {
	amount := item.payment.amount
	p.ledger = p.ledger.Release(amount)
	p.activeCount = budget.Subtract(p.activeCount, 1)
	used := budget.Subtract(rule.used(item.period), amount)
	key := numericKey(item.period)
	if used == 0 {
		rule.usage.Remove(key)
	} else {
		rule.usage.Set(key, used)
	}
	item.status = status
	emitItem(event, p.id, rule.lane, item)
}

func (p *program) statusAt(height int64) string {
	if p.status == Active && height >= p.issueEnd {
		return IssuanceClosed
	}
	return p.status
}

func (p *program) periodAt(height int64) int64 {
	switch p.status {
	case Draft:
		return 0
	case Closed:
		return p.closedPeriod
	default:
		return budget.PeriodAt(height, p.start, p.periodBlocks)
	}
}

func (p *program) evaluate(rule *policy, period, amount int64) budget.SpendCheck {
	return budget.EvaluateSpend(p.ledger.Available, p.reserveFloor, rule.canBreachFloor,
		rule.itemCap, rule.periodCap, rule.used(period), amount)
}

func (p *program) findRule(lane string) *policy {
	for _, rule := range p.policies {
		if rule.lane == lane {
			return rule
		}
	}
	return nil
}

func (p *program) rule(lane string) *policy {
	rule := p.findRule(lane)
	if rule == nil {
		panic("unknown policy lane")
	}
	return rule
}

func (p *program) policyCaller(cur realm) *policy {
	caller := cur.Previous()
	path, addr := caller.PkgPath(), caller.Address()
	for _, rule := range p.policies {
		if rule.matches(path, addr) {
			if !rule.registered {
				panic("policy is not registered")
			}
			return rule
		}
	}
	panic("caller is not a pinned policy realm")
}

func (rule *policy) matches(path string, addr address) bool {
	return path == rule.path && addr == rule.addr
}

func (p *program) findClaim(lane string, itemID int64) *claim {
	if lane == budget.RefundLane {
		if itemID == 0 && p.refund.amount > 0 {
			return &p.refund
		}
		return nil
	}
	item := p.rule(lane).item(itemID)
	if item == nil || item.status != Approved {
		return nil
	}
	return &item.payment
}

func (rule *policy) used(period int64) int64 {
	if rule.usage == nil {
		return 0
	}
	amount, _ := rule.usage.Get(numericKey(period)).(int64)
	return amount
}

func (rule *policy) item(id int64) *reservation {
	if rule.items == nil || id <= 0 {
		return nil
	}
	item, _ := rule.items.Get(numericKey(id)).(*reservation)
	return item
}

func (rule *policy) pending(id int64) *reservation {
	item := rule.item(id)
	if item == nil || item.status != Reserved {
		panic("reservation is not pending")
	}
	return item
}

func (rule *policy) pendingBeforeDeadline(id int64) *reservation {
	item := rule.pending(id)
	if runtime.ChainHeight() >= item.deadline {
		panic("reservation deadline reached")
	}
	return item
}

func findProgram(id int64) *program {
	if id <= 0 {
		return nil
	}
	p, _ := programs.Get(numericKey(id)).(*program)
	return p
}

func mustProgram(id int64) *program {
	p := findProgram(id)
	if p == nil {
		panic("program not found")
	}
	return p
}

func sponsorProgram(id int64, caller address) *program {
	p := mustProgram(id)
	if p.sponsor != caller {
		panic("only the program sponsor can do that")
	}
	return p
}

func fundingAmount() int64 {
	coins := unsafe.OriginSend()
	if len(coins) != 1 || coins[0].Denom != budget.Denom || coins[0].Amount <= 0 {
		panic("attach a positive amount of ugnot")
	}
	return coins[0].Amount
}

func requireTreasury(cur realm) {
	if !cur.IsCurrent() || cur.PkgPath() != packagePath {
		panic("invalid treasury context")
	}
}

func requireNoSend() {
	if len(unsafe.OriginSend()) != 0 {
		panic("unexpected attached coins")
	}
}

func userCaller(cur realm, payable bool) address {
	requireTreasury(cur)
	caller := cur.Previous()
	if !caller.IsUserCall() {
		panic("direct treasury call required")
	}
	if !payable {
		requireNoSend()
	}
	return caller.Address()
}

func emitItem(event string, programID int64, lane string, item *reservation) {
	chain.Emit(event, "program", number(programID), "lane", lane, "item", number(item.id),
		"recipient", string(item.payment.recipient), "amount", number(item.payment.amount),
		"period", number(item.period), "deadline", number(item.deadline), "memo", item.memo)
}

func numericKey(n int64) string {
	const zeros = "0000000000000000000"
	digits := number(n)
	return zeros[len(digits):] + digits
}

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

views.gno

package treasury

import (
	"chain"
	"chain/banker"
	"chain/runtime"

	"gno.land/p/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/budget/v2"
)

const MaxPageSize = 20

type PolicyView struct {
	Lane           string
	Path           string
	Address        address
	PeriodCap      int64
	ItemCap        int64
	CanBreachFloor bool
	Registered     bool
	Used           int64
}

type ProgramView struct {
	ID                 int64
	Title              string
	Sponsor            address
	Status             string
	ReserveFloor       int64
	StartHeight        int64
	IssueEndHeight     int64
	IssueBlocks        int64
	PeriodBlocks       int64
	MaxHoldBlocks      int64
	CurrentPeriod      int64
	ClosedHeight       int64
	ClosedPeriod       int64
	Pruned             bool
	ActiveReservations int64
	Balance            budget.Ledger
	Policies           []PolicyView
}

type LaneUsageView struct {
	Lane      string
	Used      int64
	PeriodCap int64
}

type ReservationView struct {
	ID              int64
	Lane            string
	Recipient       address
	Amount          int64
	Status          string
	Period          int64
	Deadline        int64
	Memo            string
	ExpiredAtHeight bool
	Paid            bool
}

type ClaimView struct {
	Exists    bool
	Recipient address
	Amount    int64
	Paid      bool
}

func LatestProgramID() int64 {
	return latestProgramID
}

// ListPrograms returns programs in descending ID order.
func ListPrograms(offset, limit int) []ProgramView {
	requirePage(offset, limit)
	height := runtime.ChainHeight()
	page := make([]ProgramView, 0, limit)
	programs.ReverseIterateByOffset(offset, limit, func(_ string, value any) bool {
		page = append(page, value.(*program).view(height))
		return false
	})
	return page
}

func GetProgram(programID int64) ProgramView {
	return mustProgram(programID).view(runtime.ChainHeight())
}

func (p *program) view(height int64) ProgramView {
	period := p.periodAt(height)
	rules := make([]PolicyView, 0, len(p.policies))
	for _, rule := range p.policies {
		rules = append(rules, PolicyView{
			Lane: rule.lane, Path: rule.path, Address: rule.addr, PeriodCap: rule.periodCap, ItemCap: rule.itemCap,
			CanBreachFloor: rule.canBreachFloor, Registered: rule.registered, Used: rule.used(period),
		})
	}
	return ProgramView{
		ID: p.id, Title: p.title, Sponsor: p.sponsor, Status: p.statusAt(height), ReserveFloor: p.reserveFloor,
		StartHeight: p.start, IssueEndHeight: p.issueEnd, IssueBlocks: p.issueBlocks,
		PeriodBlocks: p.periodBlocks, MaxHoldBlocks: p.maxHold, CurrentPeriod: period,
		ClosedHeight: p.closedHeight, ClosedPeriod: p.closedPeriod, Pruned: p.pruned,
		ActiveReservations: p.activeCount, Balance: p.ledger, Policies: rules,
	}
}

// CheckSpend preflights a reservation amount against an active, registered lane.
func CheckSpend(programID int64, lane string, amount int64) budget.SpendCheck {
	p := mustProgram(programID)
	rule := p.rule(lane)
	height := runtime.ChainHeight()
	if p.statusAt(height) != Active || !rule.registered {
		panic("program is not accepting reservations")
	}
	return p.evaluate(rule, p.periodAt(height), amount)
}

func GetLanePeriodUsage(programID int64, lane string, period int64) int64 {
	requirePeriod(period)
	return mustProgram(programID).rule(lane).used(period)
}

func GetPeriodUsage(programID, period int64) []LaneUsageView {
	requirePeriod(period)
	p := mustProgram(programID)
	usage := make([]LaneUsageView, 0, len(p.policies))
	for _, rule := range p.policies {
		usage = append(usage, LaneUsageView{Lane: rule.lane, Used: rule.used(period), PeriodCap: rule.periodCap})
	}
	return usage
}

func GetReservation(programID int64, lane string, itemID int64) ReservationView {
	item := mustProgram(programID).rule(lane).item(itemID)
	if item == nil {
		panic("reservation not found")
	}
	return item.view(lane, runtime.ChainHeight())
}

// ListReservations returns a lane's items in ascending ID order.
func ListReservations(programID int64, lane string, offset, limit int) []ReservationView {
	requirePage(offset, limit)
	rule := mustProgram(programID).rule(lane)
	page := make([]ReservationView, 0, limit)
	if rule.items == nil {
		return page
	}
	height := runtime.ChainHeight()
	rule.items.IterateByOffset(offset, limit, func(_ string, value any) bool {
		page = append(page, value.(*reservation).view(lane, height))
		return false
	})
	return page
}

func GetClaim(programID int64, lane string, itemID int64) ClaimView {
	c := mustProgram(programID).findClaim(lane, itemID)
	if c == nil {
		return ClaimView{}
	}
	return ClaimView{Exists: true, Recipient: c.recipient, Amount: c.amount, Paid: c.paid}
}

// GetTreasuryBalance returns total bank cash and the portion owed to programs.
func GetTreasuryBalance() (int64, int64) {
	addr := chain.PackageAddress(packagePath)
	return banker.NewReadonlyBanker().GetCoin(addr, budget.Denom), outstanding
}

func (item *reservation) view(lane string, height int64) ReservationView {
	return ReservationView{
		ID: item.id, Lane: lane, Recipient: item.payment.recipient, Amount: item.payment.amount,
		Status: item.status, Period: item.period, Deadline: item.deadline, Memo: item.memo,
		ExpiredAtHeight: item.status == Reserved && height >= item.deadline, Paid: item.payment.paid,
	}
}

func requirePage(offset, limit int) {
	if offset < 0 || limit < 1 || limit > MaxPageSize {
		panic("offset must be non-negative and limit must be 1 to 20")
	}
}

func requirePeriod(period int64) {
	if period < 0 {
		panic("period must be non-negative")
	}
}