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