render.gno
12.73 Kb · 352 lines
1package treasury
2
3import (
4 "chain/runtime"
5 "strconv"
6 "strings"
7
8 "gno.land/p/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/budget/v2"
9 "gno.land/p/moul/txlink/v0"
10 "gno.land/p/nt/mdalert/v0"
11 "gno.land/p/nt/ufmt/v0"
12)
13
14func Render(path string) string {
15 path = strings.TrimPrefix(path, ":")
16 height := runtime.ChainHeight()
17 if path == "" {
18 return renderDirectory(height)
19 }
20 parts := strings.SplitN(path, "/", 5)
21 id, err := strconv.ParseInt(parts[0], 10, 64)
22 p := findProgram(id)
23 if err != nil || p == nil {
24 return "# Shared Budget\n\nProgram not found."
25 }
26 switch len(parts) {
27 case 1:
28 return renderProgram(p, height)
29 case 3:
30 switch parts[1] {
31 case "period":
32 return renderPeriod(p, parts[2], height)
33 case budget.RefundLane:
34 if parts[2] == "0" {
35 return renderRefund(p)
36 }
37 default:
38 return renderItem(p, parts[1], parts[2], height)
39 }
40 case 4:
41 if parts[1] == "check" {
42 return renderCheck(p, parts[2], parts[3], height)
43 }
44 }
45 return "# Shared Budget\n\nUse a program, item, period, or spending check link."
46}
47
48func renderDirectory(height int64) string {
49 var table strings.Builder
50 active := 0
51 programs.ReverseIterate("", "", func(_ string, value any) bool {
52 p := value.(*program)
53 status := p.statusAt(height)
54 if status == Active {
55 active++
56 }
57 locked := p.ledger.Funded - p.ledger.Paid
58 table.WriteString(ufmt.Sprintf("| [%s](%s) | %s | %d | %s |\n",
59 programTitle(p), programURL(p.id), status, len(p.policies), budget.FormatUGNOT(locked)))
60 return false
61 })
62 header := "# Shared Budget\n\n**Total value locked** " + budget.FormatUGNOT(outstanding) +
63 " · **Active programs** " + budget.FormatInt(int64(active)) + " / " + budget.FormatInt(latestProgramID) +
64 "\n\n" + txLink("Create a program", "CreateProgram") + "\n\n## Program Directory\n\n"
65 if latestProgramID == 0 {
66 return header + "No programs yet.\n"
67 }
68 return header + "| Program | Status | Policies | Locked |\n| --- | --- | ---: | ---: |\n" + table.String()
69}
70
71func renderProgram(p *program, height int64) string {
72 view := p.view(height)
73 id := number(p.id)
74 var page strings.Builder
75 page.WriteString("# " + programTitle(p) + "\n\n")
76 page.WriteString(programStatus(view) + "\n")
77 page.WriteString("**Sponsor** " + string(p.sponsor) + "\n\n")
78 if view.Status != Draft {
79 page.WriteString(ufmt.Sprintf("**Period** [%d](%s/period/%d) · **Issuance ends at block** %d · **Pending holds** %d\n\n",
80 view.CurrentPeriod, programURL(p.id), view.CurrentPeriod, p.issueEnd, p.activeCount))
81 }
82 page.WriteString("## Fund allocation\n\n" + budget.AllocationBarSVG(p.ledger, p.reserveFloor) + "\n\n")
83 page.WriteString("| Ledger state | Amount |\n| --- | ---: |\n")
84 entries := []struct {
85 label string
86 amount int64
87 }{
88 {"Funded", p.ledger.Funded}, {"Available", p.ledger.Available},
89 {"Protected reserve floor", p.reserveFloor}, {"Reserved", p.ledger.Reserved},
90 {"Claimable", p.ledger.Claimable}, {"Paid", p.ledger.Paid},
91 }
92 for _, entry := range entries {
93 page.WriteString("| " + entry.label + " | " + budget.FormatUGNOT(entry.amount) + " |\n")
94 }
95 if len(view.Policies) == 0 {
96 page.WriteString("\nAdd a policy lane to prepare this draft for funding.\n")
97 }
98 if view.Pruned {
99 page.WriteString("\nReservation and period records were pruned. The final ledger and policy settings are available here.\n")
100 }
101 for _, rule := range view.Policies {
102 renderPolicy(&page, p, rule)
103 }
104 refund := GetClaim(p.id, budget.RefundLane, 0)
105 if refund.Exists {
106 page.WriteString("\n[View sponsor refund](" + programURL(p.id) + "/refund/0)")
107 if !refund.Paid {
108 page.WriteString(" · " + txLink("Withdraw refund", "Withdraw", "programID", id, "lane", budget.RefundLane, "itemID", "0"))
109 }
110 page.WriteString("\n")
111 }
112 return page.String() + renderProgramActions(p, view.Status)
113}
114
115func programStatus(view ProgramView) string {
116 switch view.Status {
117 case Draft:
118 return mdalert.Note("Draft", "The sponsor can add policies. Each policy must register before funding opens the program.")
119 case Active:
120 return mdalert.Success("Active", "Registered policies can reserve funds under their spending limits.")
121 case IssuanceClosed:
122 return mdalert.Warning("Issuance closed", "Pending reservations can still be resolved, and approved claims can be withdrawn.")
123 default:
124 return mdalert.Info("Closed", "Closed at block "+number(view.ClosedHeight)+" in period "+number(view.ClosedPeriod)+".")
125 }
126}
127
128func renderProgramActions(p *program, status string) string {
129 id := number(p.id)
130 switch status {
131 case Draft:
132 actions := "\n" + txLink("Add a policy", "AddPolicy", "programID", id)
133 if len(p.policies) > 0 {
134 for _, rule := range p.policies {
135 if !rule.registered {
136 return actions + "\n"
137 }
138 }
139 actions += " · " + txLink("Open and fund", "Open", "programID", id)
140 }
141 return actions + "\n"
142 case Active:
143 return "\n" + txLink("Top up", "Fund", "programID", id) + " · " +
144 txLink("Update reserve floor", "UpdateReserveFloor", "programID", id) + " · " +
145 txLink("Close issuance", "CloseIssuance", "programID", id) + "\n"
146 case IssuanceClosed:
147 if p.activeCount == 0 {
148 return "\n" + txLink("Finalize closure", "FinalizeClose", "programID", id) + "\n"
149 }
150 case Closed:
151 if p.canPrune() {
152 return "\n" + txLink("Prune closed records", "PruneClosed", "programID", id) + "\n"
153 }
154 }
155 return ""
156}
157
158func renderPolicy(page *strings.Builder, p *program, policy PolicyView) {
159 lane := policy.Lane
160 page.WriteString("\n## " + budget.MarkdownText(lane) + "\n\n")
161 page.WriteString("[Policy and roles](" + strings.TrimPrefix(policy.Path, "gno.land") + ":" + number(p.id) + ")\n\n")
162 if !policy.Registered {
163 page.WriteString("Awaiting policy registration.\n\n")
164 }
165 floor := "protected reserve applies"
166 color := "#2563eb"
167 if policy.CanBreachFloor {
168 floor = "can spend from protected reserve"
169 color = "#b45309"
170 }
171 if !p.pruned {
172 page.WriteString(budget.CapMeterSVG("Period budget", policy.Used, policy.PeriodCap, color) + "\n\n")
173 }
174 page.WriteString("**Item cap** " + budget.FormatUGNOT(policy.ItemCap) +
175 " · **Period cap** " + budget.FormatUGNOT(policy.PeriodCap) + " · " + floor + "\n\n")
176 page.WriteString("**Spending check** " + comparisonLinks(p.id, lane) + "\n")
177 rule := p.rule(lane)
178 if rule.items == nil || rule.items.Size() == 0 {
179 return
180 }
181 offset := rule.items.Size() - 4
182 if offset < 0 {
183 offset = 0
184 }
185 recent := ListReservations(p.id, lane, offset, 4)
186 page.WriteString("\n| Recent item | Amount | Status | Memo | Action |\n| --- | ---: | --- | --- | --- |\n")
187 for _, item := range recent {
188 memo := "—"
189 if item.Memo != "" {
190 memo = budget.MarkdownText(item.Memo)
191 }
192 page.WriteString(ufmt.Sprintf("| [%d](%s) | %s | %s | %s | %s |\n", item.ID, itemURL(p.id, lane, item.ID),
193 budget.FormatUGNOT(item.Amount), item.Status, memo, itemAction(p.id, item)))
194 }
195}
196
197func renderCheck(p *program, lane, rawAmount string, height int64) string {
198 rule := p.findRule(lane)
199 amount, err := strconv.ParseInt(rawAmount, 10, 64)
200 header := "# Spending Check\n\n[Back to program](" + programURL(p.id) + ")\n\n"
201 if rule == nil || err != nil || amount <= 0 {
202 return header + "Choose a registered lane and enter a positive amount in ugnot."
203 }
204 period := p.periodAt(height)
205 result := p.evaluate(rule, period, amount)
206 maxAllowed := result.MaxAllowed
207 shortfall := result.Shortfall
208 alert := mdalert.Success("PASS", "The amount fits the lane and shared treasury limits.")
209 switch {
210 case p.statusAt(height) != Active || !rule.registered:
211 alert = mdalert.Caution("FAIL", "The program is not accepting reservations in this lane.")
212 maxAllowed, shortfall = 0, amount
213 case !result.Allowed:
214 alert = mdalert.Caution("FAIL", constraintLabel(result.BindingConstraint)+" limits this reservation.")
215 }
216 floorAvailable := budget.FormatUGNOT(result.PoolRoom)
217 floorResult := guardResult(amount, result.PoolRoom)
218 if rule.canBreachFloor {
219 floorAvailable, floorResult = "Priority lane", "Bypassed"
220 }
221 return header + alert + "\n" +
222 "**Lane** " + budget.MarkdownText(lane) + " · **Period** [" + number(period) + "](" +
223 programURL(p.id) + "/period/" + number(period) + ")\n\n" +
224 "**Requested** " + budget.FormatUGNOT(amount) + "\n\n" +
225 "| Guardrail | Remaining room | Result |\n| --- | ---: | --- |\n" +
226 guardRow("Item cap", result.ItemRoom, amount) +
227 guardRow("Period budget", result.PeriodRoom, amount) +
228 "| Reserve floor | " + floorAvailable + " | " + floorResult + " |\n" +
229 guardRow("Shared available", p.ledger.Available, amount) + "\n" +
230 "**Maximum reservable** " + budget.FormatUGNOT(maxAllowed) +
231 " · **Shortfall** " + budget.FormatUGNOT(shortfall) + "\n\n" +
232 "**Compare amounts** " + comparisonLinks(p.id, lane) + "\n"
233}
234
235func constraintLabel(constraint string) string {
236 switch constraint {
237 case "item_cap":
238 return "Item cap"
239 case "period_cap":
240 return "Period budget"
241 case "reserve_floor":
242 return "Reserve floor"
243 default:
244 return "Shared available balance"
245 }
246}
247
248func guardRow(label string, room, amount int64) string {
249 return "| " + label + " | " + budget.FormatUGNOT(room) + " | " + guardResult(amount, room) + " |\n"
250}
251
252func guardResult(amount, room int64) string {
253 if amount > room {
254 return "Fail"
255 }
256 return "Pass"
257}
258
259func renderPeriod(p *program, rawPeriod string, height int64) string {
260 period, err := strconv.ParseInt(rawPeriod, 10, 64)
261 if err != nil || period < 0 || period > p.periodAt(height) || p.status == Draft {
262 return "# Shared Budget\n\nPeriod not found."
263 }
264 header := "# Period " + number(period) + "\n\n[Back to program](" + programURL(p.id) + ")\n\n"
265 if p.pruned {
266 return header + "Period records were pruned."
267 }
268 var page strings.Builder
269 page.WriteString(header + "| Lane | Used | Cap | Check |\n| --- | ---: | ---: | --- |\n")
270 for _, row := range GetPeriodUsage(p.id, period) {
271 page.WriteString(ufmt.Sprintf("| %s | %s | %s | %s |\n", budget.MarkdownText(row.Lane),
272 budget.FormatUGNOT(row.Used), budget.FormatUGNOT(row.PeriodCap), comparisonLinks(p.id, row.Lane)))
273 }
274 return page.String() + renderProgramActions(p, p.statusAt(height))
275}
276
277func renderItem(p *program, lane, rawID string, height int64) string {
278 rule := p.findRule(lane)
279 if rule == nil {
280 return "# Shared Budget\n\nPolicy lane not found."
281 }
282 if p.pruned {
283 return "# Shared Budget\n\nReservation records were pruned. [View program summary](" + programURL(p.id) + ")."
284 }
285 id, err := strconv.ParseInt(rawID, 10, 64)
286 item := rule.item(id)
287 if err != nil || item == nil {
288 return "# Shared Budget\n\nReservation not found."
289 }
290 view := item.view(lane, height)
291 policyURL := strings.TrimPrefix(rule.path, "gno.land") + ":" + number(p.id) + "/" + number(id)
292 return "# " + budget.MarkdownText(lane) + " · Item " + number(id) + "\n\n" +
293 "[Program](" + programURL(p.id) + ") · [Policy record](" + policyURL + ")\n\n" +
294 "| Reservation | Details |\n| --- | --- |\n" +
295 "| Status | " + view.Status + " |\n| Recipient | " + string(view.Recipient) +
296 " |\n| Amount | " + budget.FormatUGNOT(view.Amount) +
297 " |\n| Period | [" + number(view.Period) + "](" + programURL(p.id) + "/period/" + number(view.Period) +
298 ") |\n| Deadline | " + number(view.Deadline) +
299 " |\n| Memo | " + budget.MarkdownText(view.Memo) +
300 " |\n| Paid | " + strconv.FormatBool(view.Paid) + " |\n\n" + itemAction(p.id, view) + "\n"
301}
302
303func renderRefund(p *program) string {
304 header := "# Sponsor refund\n\n[Back to program](" + programURL(p.id) + ")\n\n"
305 refund := GetClaim(p.id, budget.RefundLane, 0)
306 if !refund.Exists {
307 return header + "No refund claim."
308 }
309 page := header + "| Claim | Details |\n| --- | --- |\n| Recipient | " + string(refund.Recipient) +
310 " |\n| Amount | " + budget.FormatUGNOT(refund.Amount) +
311 " |\n| Paid | " + strconv.FormatBool(refund.Paid) + " |\n"
312 if !refund.Paid {
313 page += "\n" + txLink("Withdraw refund", "Withdraw", "programID", number(p.id), "lane", budget.RefundLane, "itemID", "0") + "\n"
314 }
315 return page
316}
317
318func itemAction(programID int64, item ReservationView) string {
319 args := []string{"programID", number(programID), "lane", item.Lane, "itemID", number(item.ID)}
320 switch {
321 case item.ExpiredAtHeight:
322 return txLink("Expire", "Expire", args...)
323 case item.Status == Approved && !item.Paid:
324 return txLink("Withdraw", "Withdraw", args...)
325 default:
326 return "—"
327 }
328}
329
330func programTitle(p *program) string {
331 if p.title == "" {
332 return "Program " + number(p.id)
333 }
334 return budget.MarkdownText(p.title)
335}
336
337func programURL(id int64) string {
338 return strings.TrimPrefix(packagePath, "gno.land") + ":" + number(id)
339}
340
341func itemURL(programID int64, lane string, itemID int64) string {
342 return programURL(programID) + "/" + lane + "/" + number(itemID)
343}
344
345func comparisonLinks(id int64, lane string) string {
346 path := programURL(id) + "/check/" + lane
347 return "[200,000 ugnot](" + path + "/200000) · [100,000 ugnot](" + path + "/100000)"
348}
349
350func txLink(label, function string, args ...string) string {
351 return "[" + label + "](" + txlink.Realm(packagePath).Call(function, args...) + ")"
352}