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

funding.gno

package treasury

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

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

var (
	registeredTokens = avl.NewTree()
	registeredIDs    = avl.NewTree()
	outstanding      = avl.NewTree()
)

// RegisterToken binds a key to a GRC20 ledger for the lifetime of the treasury.
func RegisterToken(cur realm, key string, token *grc20.Token) {
	callerAddress(cur)
	budget.RequireAsset(budget.GRC20Prefix + key)
	if token == nil || token.ID() == "" {
		panic("expected a GRC20 token created with grc20.NewToken")
	}
	if registeredTokens.Has(key) {
		panic("token key already registered")
	}
	id := token.ID()
	if registeredIDs.Has(id) {
		panic("token already registered under another key")
	}
	registeredTokens.Set(key, token)
	registeredIDs.Set(id, key)
	chain.Emit("TokenRegistered", "key", key, "token", id)
}

func GetRegisteredToken(key string) *grc20.Token {
	token, _ := registeredTokens.Get(key).(*grc20.Token)
	return token
}

func isTokenAsset(asset string) bool {
	return strings.HasPrefix(asset, budget.GRC20Prefix)
}

func tokenForAsset(asset string) *grc20.Token {
	token := GetRegisteredToken(strings.TrimPrefix(asset, budget.GRC20Prefix))
	if token == nil {
		panic("GRC20 token is not registered")
	}
	return token
}

func Open(cur realm, programID int64) {
	p, actor, amount := attachedFunding(cur, programID, true)
	runtime.AssertOriginCall()
	p.recordFunding(actor, amount, true)
}

func Fund(cur realm, programID int64) {
	p, actor, amount := attachedFunding(cur, programID, false)
	runtime.AssertOriginCall()
	p.recordFunding(actor, amount, false)
}

func attachedFunding(cur realm, programID int64, opening bool) (*program, address, int64) {
	requireTreasury(cur)
	caller := cur.Previous()
	if !caller.IsUserCall() {
		panic("use a banker to fund native coins from another realm")
	}
	p := fundingProgram(programID, caller.Address(), opening)
	if isTokenAsset(p.asset) {
		panic("use OpenToken or FundToken for a GRC20 program")
	}
	coins := unsafe.OriginSend()
	if len(coins) != 1 || coins[0].Denom != p.asset || coins[0].Amount <= 0 {
		panic("attach a positive amount of " + p.asset + " only")
	}
	return p, caller.Address(), coins[0].Amount
}

func OpenFromBanker(cur realm, programID int64, fromBanker banker.Banker, amount int64) {
	fundFromBanker(cur, programID, fromBanker, amount, true)
}

func FundFromBanker(cur realm, programID int64, fromBanker banker.Banker, amount int64) {
	fundFromBanker(cur, programID, fromBanker, amount, false)
}

func fundFromBanker(cur realm, programID int64, fromBanker banker.Banker, amount int64, opening bool) {
	actor := fundingActor(cur)
	p := fundingProgram(programID, actor, opening)
	if isTokenAsset(p.asset) {
		panic("use OpenToken or FundToken for a GRC20 program")
	}
	if !banker.IsCanonical(fromBanker) {
		panic("funding requires a canonical banker")
	}
	requireFundingSource(actor, cur.Address(), amount)
	fromBanker.SendCoins(actor, cur.Address(), chain.Coins{chain.NewCoin(p.asset, amount)})
	p.recordFunding(actor, amount, opening)
}

func OpenToken(cur realm, programID, amount int64) {
	fundToken(cur, programID, amount, true)
}

func FundToken(cur realm, programID, amount int64) {
	fundToken(cur, programID, amount, false)
}

func fundToken(cur realm, programID, amount int64, opening bool) {
	actor := fundingActor(cur)
	p := fundingProgram(programID, actor, opening)
	if !isTokenAsset(p.asset) {
		panic("program uses native coins")
	}
	requireFundingSource(actor, cur.Address(), amount)
	token := tokenForAsset(p.asset)
	if err := token.RealmTeller(0, cur).TransferFrom(0, cur, actor, cur.Address(), amount); err != nil {
		panic("GRC20 funding failed: " + err.Error())
	}
	p.recordFunding(actor, amount, opening)
}

func fundingActor(cur realm) address {
	requireTreasury(cur)
	caller := cur.Previous()
	// A nested call transfers its own funds. The outer envelope was sent to its entry realm.
	if caller.IsUserCall() {
		requireNoSend()
	}
	return caller.Address()
}

func requireFundingSource(actor, destination address, amount int64) {
	budget.RequirePositive(amount)
	if actor == destination {
		panic("funding source must differ from the treasury")
	}
}

func fundingProgram(id int64, actor address, opening bool) *program {
	if !opening {
		p := mustProgram(id)
		if p.statusAt(runtime.ChainHeight()) != Active {
			panic("program is not accepting funds")
		}
		return p
	}
	p := sponsorProgram(id, actor)
	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")
		}
	}
	return p
}

func (p *program) recordFunding(actor address, amount int64, opening bool) {
	p.ledger = p.ledger.Fund(amount)
	setOutstanding(p.asset, budget.Add(assetOutstanding(p.asset), amount))
	if opening {
		p.start = runtime.ChainHeight()
		p.issueEnd = budget.Add(p.start, p.issueBlocks)
		p.status = Active
		chain.Emit("ProgramOpened", "program", number(p.id), "sponsor", string(actor), "asset", p.asset,
			"amount", number(amount), "start", number(p.start), "issue_end", number(p.issueEnd))
		return
	}
	chain.Emit("ProgramFunded", "program", number(p.id), "sponsor", string(p.sponsor),
		"funder", string(actor), "asset", p.asset, "amount", number(amount))
}

func (p *program) pay(cur realm, payment *claim) {
	if isTokenAsset(p.asset) {
		token := tokenForAsset(p.asset)
		if err := token.RealmTeller(0, cur).Transfer(0, cur, payment.recipient, payment.amount); err != nil {
			panic("GRC20 withdrawal failed: " + err.Error())
		}
		return
	}
	coins := chain.Coins{chain.NewCoin(p.asset, payment.amount)}
	banker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(cur.Address(), payment.recipient, coins)
}

func assetOutstanding(asset string) int64 {
	amount, _ := outstanding.Get(asset).(int64)
	return amount
}

func setOutstanding(asset string, amount int64) {
	if amount == 0 {
		outstanding.Remove(asset)
		return
	}
	outstanding.Set(asset, amount)
}

gnomod.toml

module = "gno.land/r/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/treasury/v4"
gno = "0.9"

[addpkg]
  creator = "g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct"
  height = 1562614
  max_deposit = "30000000ugnot"

governance.gno

package treasury

import (
	"chain"
	"chain/runtime"

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

type capChange struct {
	periodCap int64
	itemCap   int64
	eta       int64
}

func ProposeSponsorTransfer(cur realm, programID int64, nextSponsor address) {
	p := sponsorProgram(programID, callerAddress(cur))
	if p.status == Canceled {
		panic("draft was canceled")
	}
	budget.RequireAddress(nextSponsor)
	if nextSponsor == p.sponsor || nextSponsor == cur.Address() {
		panic("choose a different sponsor outside the treasury")
	}
	p.pendingSponsor = nextSponsor
	chain.Emit("SponsorTransferProposed", "program", number(programID),
		"sponsor", string(p.sponsor), "pending_sponsor", string(nextSponsor))
}

func AcceptSponsorTransfer(cur realm, programID int64) {
	caller := callerAddress(cur)
	p := mustProgram(programID)
	if p.pendingSponsor == "" || caller != p.pendingSponsor {
		panic("only the pending sponsor can accept")
	}
	old := p.sponsor
	p.sponsor, p.pendingSponsor = caller, ""
	p.clearPendingGovernance()
	chain.Emit("SponsorTransferred", "program", number(programID), "old_sponsor", string(old), "sponsor", string(caller))
}

func UpdateReserveFloor(cur realm, programID, newFloor int64) {
	p := sponsorProgram(programID, callerAddress(cur))
	if p.govDelay != 0 {
		panic("governance delay requires QueueReserveFloor and ExecuteReserveFloor")
	}
	p.requireActiveGovernance()
	requireFloor(newFloor)
	p.setReserveFloor(newFloor)
}

// QueueReserveFloor returns the first block at which the change may take effect.
// With a zero delay, the change takes effect immediately.
func QueueReserveFloor(cur realm, programID, newFloor int64) int64 {
	p := sponsorProgram(programID, callerAddress(cur))
	height := p.requireActiveGovernance()
	requireFloor(newFloor)
	if p.govDelay == 0 {
		p.setReserveFloor(newFloor)
		return height
	}
	eta := budget.Add(height, p.govDelay)
	p.pendingFloor, p.pendingFloorETA = newFloor, eta
	chain.Emit("ReserveFloorQueued", "program", number(programID), "reserve_floor", number(newFloor), "eta", number(eta))
	return eta
}

func ExecuteReserveFloor(cur realm, programID int64) {
	callerAddress(cur)
	p := mustProgram(programID)
	requireReady(p.pendingFloorETA, p.requireActiveGovernance())
	p.setReserveFloor(p.pendingFloor)
	p.pendingFloor, p.pendingFloorETA = 0, 0
}

func CancelPendingReserveFloor(cur realm, programID int64) {
	p := sponsorProgram(programID, callerAddress(cur))
	if p.pendingFloorETA == 0 {
		panic("no reserve floor change is queued")
	}
	p.pendingFloor, p.pendingFloorETA = 0, 0
	chain.Emit("ReserveFloorCanceled", "program", number(programID))
}

// QueuePolicyCaps changes an active lane's spending limits without altering prior usage.
func QueuePolicyCaps(cur realm, programID int64, lane string, periodCap, itemCap int64) int64 {
	p := sponsorProgram(programID, callerAddress(cur))
	height := p.requireActiveGovernance()
	rule := p.rule(lane)
	requireCaps(periodCap, itemCap)
	if p.govDelay == 0 {
		p.setPolicyCaps(rule, periodCap, itemCap)
		return height
	}
	eta := budget.Add(height, p.govDelay)
	rule.pendingCaps = capChange{periodCap: periodCap, itemCap: itemCap, eta: eta}
	chain.Emit("PolicyCapsQueued", "program", number(programID), "lane", lane, "period_cap", number(periodCap),
		"item_cap", number(itemCap), "eta", number(eta))
	return eta
}

func ExecutePolicyCaps(cur realm, programID int64, lane string) {
	callerAddress(cur)
	p := mustProgram(programID)
	rule := p.rule(lane)
	pending := rule.pendingCaps
	requireReady(pending.eta, p.requireActiveGovernance())
	p.setPolicyCaps(rule, pending.periodCap, pending.itemCap)
	rule.pendingCaps = capChange{}
}

func CancelPendingPolicyCaps(cur realm, programID int64, lane string) {
	p := sponsorProgram(programID, callerAddress(cur))
	rule := p.rule(lane)
	if rule.pendingCaps.eta == 0 {
		panic("no policy cap change is queued")
	}
	rule.pendingCaps = capChange{}
	chain.Emit("PolicyCapsCanceled", "program", number(programID), "lane", lane)
}

func (p *program) requireActiveGovernance() int64 {
	height := runtime.ChainHeight()
	if p.statusAt(height) != Active {
		panic("governance changes require an active program")
	}
	return height
}

func requireReady(eta, height int64) {
	if eta == 0 {
		panic("no governance change is queued")
	}
	if height < eta {
		panic("governance change is timelocked until block " + number(eta))
	}
}

func requireCaps(periodCap, itemCap int64) {
	if itemCap <= 0 || itemCap > periodCap {
		panic("policy caps require 0 < item cap <= period cap")
	}
}

func (p *program) setReserveFloor(newFloor int64) {
	oldFloor := p.reserveFloor
	p.reserveFloor = newFloor
	chain.Emit("ReserveFloorUpdated", "program", number(p.id), "old_floor", number(oldFloor), "reserve_floor", number(newFloor))
}

func (p *program) setPolicyCaps(rule *policy, periodCap, itemCap int64) {
	rule.periodCap, rule.itemCap = periodCap, itemCap
	chain.Emit("PolicyCapsUpdated", "program", number(p.id), "lane", rule.lane,
		"period_cap", number(periodCap), "item_cap", number(itemCap))
}

func (p *program) clearPendingGovernance() {
	p.pendingFloor, p.pendingFloorETA = 0, 0
	for _, rule := range p.policies {
		rule.pendingCaps = capChange{}
	}
}

render.gno

package treasury

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

	"gno.land/p/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/budget/v3"
	"gno.land/p/moul/txlink/v0"
	"gno.land/p/nt/mdalert/v0"
	"gno.land/p/nt/ufmt/v0"
	"gno.land/r/sys/users"
)

func Render(path string) string {
	path = strings.TrimPrefix(path, ":")
	height := runtime.ChainHeight()
	if path == "" {
		return renderDirectory(height, 1)
	}
	parts := strings.SplitN(path, "/", 5)
	if len(parts) == 2 && parts[0] == "page" {
		page, err := strconv.Atoi(parts[1])
		if err == nil && page > 0 {
			return renderDirectory(height, page)
		}
		return "# Shared Budget\n\nDirectory page not found."
	}
	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, page int) string {
	header := "# Shared Budget\n\n**Total value locked (ugnot)** " + budget.FormatUGNOT(assetOutstanding(budget.Denom)) +
		" · **Programs** " + 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"
	}
	pageCount := (programs.Size()-1)/MaxPageSize + 1
	if page > pageCount {
		return header + "Directory page not found."
	}
	var table strings.Builder
	programs.ReverseIterateByOffset((page-1)*MaxPageSize, MaxPageSize, func(_ string, value any) bool {
		p := value.(*program)
		locked := p.ledger.Funded - p.ledger.Paid
		table.WriteString(ufmt.Sprintf("| [%s](%s) | %s | %d | %s |\n",
			programTitle(p), programURL(p.id), p.statusAt(height), len(p.policies), p.renderAmount(locked)))
		return false
	})
	nav := "\nPage " + strconv.Itoa(page) + " of " + strconv.Itoa(pageCount)
	if page > 1 {
		nav += " · [Previous](" + directoryURL(page-1) + ")"
	}
	if page < pageCount {
		nav += " · [Next](" + directoryURL(page+1) + ")"
	}
	return header + "| Program | Status | Policies | Locked |\n| --- | --- | ---: | ---: |\n" + table.String() + nav + "\n"
}

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** " + renderAddress(p.sponsor) + " · **Asset** " + budget.MarkdownText(p.asset) + "\n\n")
	if view.PendingSponsor != "" {
		page.WriteString("**Pending sponsor** " + renderAddress(view.PendingSponsor) + " · " +
			txLink("Accept sponsorship", "AcceptSponsorTransfer", "programID", id) + "\n\n")
	}
	if view.Status != Draft && view.Status != Canceled {
		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, view.AssetSymbol) + "\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 + " | " + p.renderAmount(entry.amount) + " |\n")
	}
	if view.PendingFloorETA > 0 && view.Status == Active {
		page.WriteString("\n**Pending reserve floor** " + p.renderAmount(view.PendingFloor) +
			" · **Executable at block** " + number(view.PendingFloorETA) + " · " +
			txLink("Execute floor change", "ExecuteReserveFloor", "programID", id) + " · " +
			txLink("Cancel floor change", "CancelPendingReserveFloor", "programID", id) + "\n")
	}
	if len(view.Policies) == 0 && view.Status == Draft {
		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.")
	case Canceled:
		return mdalert.Info("Canceled", "The sponsor canceled this draft.")
	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)
	handoff := txLink("Propose sponsor transfer", "ProposeSponsorTransfer", "programID", id)
	switch status {
	case Draft:
		actions := "\n" + txLink("Add a policy", "AddPolicy", "programID", id) + " · " +
			txLink("Cancel draft", "CancelDraft", "programID", id) + " · " + handoff
		if len(p.policies) > 0 {
			for _, rule := range p.policies {
				if !rule.registered {
					return actions + "\n"
				}
			}
			open := "Open"
			if isTokenAsset(p.asset) {
				open = "OpenToken"
			}
			actions += " · " + txLink("Open and fund", open, "programID", id)
		}
		return actions + "\n"
	case Active:
		fund := "Fund"
		if isTokenAsset(p.asset) {
			fund = "FundToken"
		}
		floor := txLink("Update reserve floor", "UpdateReserveFloor", "programID", id)
		if p.govDelay > 0 {
			floor = txLink("Queue reserve floor", "QueueReserveFloor", "programID", id)
		}
		return "\n" + txLink("Top up", fund, "programID", id) + " · " + floor + " · " +
			handoff + " · " + 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](" + budget.PolicyLaneURL(policy.Path, p.id, lane) + ")\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 {
		symbol, decimals := p.assetDisplay()
		if p.asset == budget.Denom {
			decimals = 0
		}
		page.WriteString(budget.CapMeterSVG("Period budget", policy.Used, policy.PeriodCap, color, symbol, decimals) + "\n\n")
	}
	page.WriteString("**Item cap** " + p.renderAmount(policy.ItemCap) +
		" · **Period cap** " + p.renderAmount(policy.PeriodCap) + " · " + floor + "\n\n")
	rule := p.rule(lane)
	page.WriteString("**Spending check** " + comparisonLinks(p, rule) + "\n")
	args := []string{"programID", number(p.id), "lane", lane}
	switch p.statusAt(runtime.ChainHeight()) {
	case Draft:
		page.WriteString("\n" + txLink("Remove lane", "RemovePolicy", args...) + "\n")
	case Active:
		page.WriteString("\n" + txLink("Change lane caps", "QueuePolicyCaps", args...) + "\n")
		if policy.PendingCapsETA > 0 {
			page.WriteString("\n**Pending item cap** " + p.renderAmount(policy.PendingItemCap) +
				" · **Pending period cap** " + p.renderAmount(policy.PendingPeriodCap) +
				" · **Executable at block** " + number(policy.PendingCapsETA) + " · " +
				txLink("Execute cap change", "ExecutePolicyCaps", args...) + " · " +
				txLink("Cancel cap change", "CancelPendingPolicyCaps", args...) + "\n")
		}
	}
	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),
			p.renderAmount(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 the program asset's base units."
	}
	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 := p.renderAmount(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** " + p.renderAmount(amount) + "\n\n" +
		"| Guardrail | Remaining room | Result |\n| --- | ---: | --- |\n" +
		p.guardRow("Item cap", result.ItemRoom, amount) +
		p.guardRow("Period budget", result.PeriodRoom, amount) +
		"| Reserve floor | " + floorAvailable + " | " + floorResult + " |\n" +
		p.guardRow("Shared available", result.Available, amount) + "\n" +
		"**Maximum reservable** " + p.renderAmount(maxAllowed) +
		" · **Shortfall** " + p.renderAmount(shortfall) + "\n\n" +
		"**Compare amounts** " + comparisonLinks(p, rule) + "\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 (p *program) guardRow(label string, room, amount int64) string {
	return "| " + label + " | " + p.renderAmount(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 || p.status == Canceled {
		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),
			p.renderAmount(row.Used), p.renderAmount(row.PeriodCap), comparisonLinks(p, p.rule(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 := budget.PolicyLaneURL(rule.path, p.id, lane) + "/" + 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 | " + renderAddress(view.Recipient) +
		" |\n| Amount | " + p.renderAmount(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 | " + renderAddress(refund.Recipient) +
		" |\n| Amount | " + p.renderAmount(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(realmPath, "gno.land") + ":" + number(id)
}

func directoryURL(page int) string {
	return strings.TrimPrefix(realmPath, "gno.land") + ":page/" + strconv.Itoa(page)
}

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

func comparisonLinks(p *program, rule *policy) string {
	path := programURL(p.id) + "/check/" + rule.lane
	limit := p.evaluate(rule, p.periodAt(runtime.ChainHeight()), 1).MaxAllowed
	link := func(amount int64) string {
		return "[" + p.renderAmount(amount) + "](" + path + "/" + number(amount) + ")"
	}
	switch limit {
	case 0:
		return link(1)
	case 1<<63 - 1:
		return link(limit)
	default:
		return link(limit) + " · " + link(limit+1)
	}
}

func (p *program) renderAmount(amount int64) string {
	if p.asset == budget.Denom {
		return budget.FormatUGNOT(amount)
	}
	symbol, decimals := p.assetDisplay()
	return budget.MarkdownText(budget.FormatAsset(amount, symbol, decimals))
}

func renderAddress(addr address) string {
	if user := users.ResolveAddress(addr); user != nil {
		return "@" + budget.MarkdownText(user.Name()) + " (" + string(addr) + ")"
	}
	return string(addr)
}

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

treasury.gno

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

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

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

const (
	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
	pendingCaps    capChange
	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
	pendingSponsor    address
	title             string
	asset             string
	status            string
	reserveFloor      int64
	govDelay          int64
	pendingFloor      int64
	pendingFloorETA   int64
	periodBlocks      int64
	issueBlocks       int64
	maxHold           int64
	start             int64
	issueEnd          int64
	issueClosedHeight int64
	closedHeight      int64
	closedPeriod      int64
	pruned            bool
	policies          []*policy
	ledger            budget.Ledger
	activeCount       int64
	refund            claim
}

var (
	realmPath       = unsafe.CurrentRealm().PkgPath()
	programs        = avl.NewTree()
	latestProgramID int64
)

func CreateProgram(cur realm, title, asset string, reserveFloor, periodBlocks, issueBlocks, maxHold, govDelay int64) int64 {
	sponsor := callerAddress(cur)
	budget.RequireMemo(title)
	requireFloor(reserveFloor)
	if asset == "" {
		asset = budget.Denom
	}
	budget.RequireAsset(asset)
	if isTokenAsset(asset) {
		tokenForAsset(asset)
	}
	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")
	}
	if govDelay < 0 || govDelay > maxScheduleBlocks {
		panic("governance delay must be 0 to 2147483647 blocks")
	}
	id := budget.Add(latestProgramID, 1)
	programs.Set(numericKey(id), &program{
		id: id, sponsor: sponsor, title: title, asset: asset, status: Draft, reserveFloor: reserveFloor,
		periodBlocks: periodBlocks, issueBlocks: issueBlocks, maxHold: maxHold, govDelay: govDelay,
	})
	latestProgramID = id
	chain.Emit("ProgramCreated", "program", number(id), "sponsor", string(sponsor),
		"title", title, "reserve_floor", number(reserveFloor), "asset", asset, "gov_delay", number(govDelay))
	return id
}

func AddPolicy(cur realm, programID int64, lane, policyPath string, periodCap, itemCap int64, canBreachFloor bool) {
	p := sponsorProgram(programID, callerAddress(cur))
	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, cur.PkgPath())
	requireCaps(periodCap, itemCap)
	if p.findRule(lane) != nil {
		panic("policy lane already added")
	}
	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 RemovePolicy(cur realm, programID int64, lane string) {
	p := sponsorProgram(programID, callerAddress(cur))
	if p.status != Draft {
		panic("policies can only be removed from a draft")
	}
	for i, rule := range p.policies {
		if rule.lane == lane {
			copy(p.policies[i:], p.policies[i+1:])
			last := len(p.policies) - 1
			p.policies[last] = nil
			p.policies = p.policies[:last]
			chain.Emit("PolicyRemoved", "program", number(programID), "lane", lane)
			return
		}
	}
	panic("unknown policy lane")
}

func CancelDraft(cur realm, programID int64) {
	p := sponsorProgram(programID, callerAddress(cur))
	if p.status != Draft {
		panic("only a draft can be canceled")
	}
	p.policies = nil
	p.pendingSponsor = ""
	p.status = Canceled
	chain.Emit("DraftCanceled", "program", number(programID))
}

func RegisterPolicy(cur realm, programID int64, lane string) {
	requireTreasury(cur)
	requireNoSend()
	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)
}

// Reserve assigns the next item ID in the lane and returns it with the remaining available balance.
func Reserve(cur realm, programID int64, lane string, recipient address, amount, deadline int64, memo string) (int64, int64) {
	p := mustProgram(programID)
	rule := p.policyCaller(cur, lane)
	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 int64, lane string, itemID int64) {
	p := mustProgram(programID)
	rule := p.policyCaller(cur, lane)
	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 int64, lane string, itemID int64) {
	p := mustProgram(programID)
	rule := p.policyCaller(cur, lane)
	p.release(rule, rule.pendingBeforeDeadline(itemID), Rejected, "Rejected")
}

func Cancel(cur realm, programID int64, lane string, itemID int64) {
	p := mustProgram(programID)
	rule := p.policyCaller(cur, lane)
	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 := callerAddress(cur)
	p := sponsorProgram(programID, sponsor)
	height := runtime.ChainHeight()
	if p.statusAt(height) != Active {
		panic("issuance is not active")
	}
	p.issueClosedHeight = height
	p.status = IssuanceClosed
	p.clearPendingGovernance()
	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.issueClosedHeight = p.issuanceCutoff()
	p.closedHeight = height
	p.status = Closed
	p.clearPendingGovernance()
	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) {
	caller := callerAddress(cur)
	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)
	setOutstanding(p.asset, budget.Subtract(assetOutstanding(p.asset), payment.amount))
	payment.paid = true
	p.pay(cur, payment)
	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, callerAddress(cur))
	if !p.canPrune() {
		panic("pruning requires an unpruned closed program with no unpaid claims or pending reservations")
	}
	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, self string) {
	const prefix = "gno.land/r/"
	if len(path) > 256 || !strings.HasPrefix(path, prefix) || path == self {
		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) 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, Canceled:
		return 0
	case Closed:
		return p.closedPeriod
	default:
		if cutoff := p.issuanceCutoff(); height > cutoff {
			height = cutoff
		}
		return budget.PeriodAt(height, p.start, p.periodBlocks)
	}
}

func (p *program) issuanceCutoff() int64 {
	if p.status == IssuanceClosed || p.status == Closed {
		return p.issueClosedHeight
	}
	return p.issueEnd
}

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, lane string) *policy {
	requireTreasury(cur)
	requireNoSend()
	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 !rule.registered {
		panic("policy is not registered")
	}
	return rule
}

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 requireTreasury(cur realm) {
	if !cur.IsCurrent() || cur.PkgPath() != realmPath {
		panic("invalid treasury context")
	}
}

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

func callerAddress(cur realm) address {
	requireTreasury(cur)
	requireNoSend()
	return cur.Previous().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/v3"
)

const MaxPageSize = 20

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

type ProgramView struct {
	ID                 int64
	Title              string
	Sponsor            address
	PendingSponsor     address
	Status             string
	Asset              string
	AssetSymbol        string
	AssetDecimals      int
	ReserveFloor       int64
	GovDelay           int64
	PendingFloor       int64
	PendingFloorETA    int64
	CurrentHeight      int64
	StartHeight        int64
	IssueEndHeight     int64
	IssueClosedHeight  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
}

type TokenView struct {
	Exists   bool
	ID       string
	Name     string
	Symbol   string
	Decimals int
}

func GetTokenMetadata(key string) TokenView {
	token := GetRegisteredToken(key)
	if token == nil {
		return TokenView{}
	}
	return TokenView{Exists: true, ID: token.ID(), Name: token.GetName(), Symbol: token.GetSymbol(), Decimals: token.GetDecimals()}
}

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())
}

// PolicyRenderRoute resolves a policy route against the lanes registered to its realm.
// A bare program route may return several lanes for the caller to display.
func PolicyRenderRoute(path, policyPath string) (ProgramView, []string, int64) {
	id, lane, itemID := budget.ParsePolicyLanePath(path)
	p := findProgram(id)
	if p == nil {
		return ProgramView{}, nil, 0
	}
	var lanes []string
	for _, rule := range p.policies {
		if rule.path == policyPath && rule.registered && (lane == "" || lane == rule.lane) {
			lanes = append(lanes, rule.lane)
		}
	}
	return p.view(runtime.ChainHeight()), lanes, itemID
}

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),
			PendingPeriodCap: rule.pendingCaps.periodCap, PendingItemCap: rule.pendingCaps.itemCap,
			PendingCapsETA: rule.pendingCaps.eta,
		})
	}
	status := p.statusAt(height)
	symbol, decimals := p.assetDisplay()
	issueClosedHeight := int64(0)
	if status == IssuanceClosed || status == Closed {
		issueClosedHeight = p.issuanceCutoff()
	}
	return ProgramView{
		ID: p.id, Title: p.title, Sponsor: p.sponsor, PendingSponsor: p.pendingSponsor, Status: status,
		Asset: p.asset, AssetSymbol: symbol, AssetDecimals: decimals, ReserveFloor: p.reserveFloor,
		GovDelay: p.govDelay, PendingFloor: p.pendingFloor, PendingFloorETA: p.pendingFloorETA, CurrentHeight: height,
		StartHeight: p.start, IssueEndHeight: p.issueEnd, IssueClosedHeight: issueClosedHeight, 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,
	}
}

func (p *program) assetDisplay() (string, int) {
	if isTokenAsset(p.asset) {
		token := tokenForAsset(p.asset)
		return token.GetSymbol(), token.GetDecimals()
	}
	if p.asset == budget.Denom {
		return p.asset, 6
	}
	return p.asset, 0
}

func (view ProgramView) FormatAmount(amount int64) string {
	if view.Asset == budget.Denom {
		return budget.FormatUGNOT(amount)
	}
	return budget.FormatAsset(amount, view.AssetSymbol, view.AssetDecimals)
}

// 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) {
	return GetTreasuryAssetBalance(budget.Denom)
}

// GetTreasuryAssetBalance returns physical custody and outstanding claims and allocations.
func GetTreasuryAssetBalance(asset string) (int64, int64) {
	budget.RequireAsset(asset)
	addr := chain.PackageAddress(realmPath)
	if isTokenAsset(asset) {
		return tokenForAsset(asset).BalanceOf(addr), assetOutstanding(asset)
	}
	return banker.NewReadonlyBanker().GetCoin(addr, asset), assetOutstanding(asset)
}

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")
	}
}