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