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