custom_policy.gno
2.51 Kb · 78 lines
1// Package custom_policy shows a lane where one approver can award a micro-grant.
2package custom_policy
3
4import (
5 "chain/runtime"
6 "chain/runtime/unsafe"
7 "strconv"
8
9 "gno.land/p/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/budget/v3"
10 "gno.land/p/moul/txlink/v0"
11 "gno.land/p/nt/avl/v0"
12 "gno.land/r/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/treasury/v4"
13)
14
15var (
16 realmPath = unsafe.CurrentRealm().PkgPath()
17 approvers = avl.NewTree()
18)
19
20func Configure(cur realm, programID int64, lane string, approver address) {
21 caller := callerAddress(cur)
22 if caller != treasury.GetProgram(programID).Sponsor {
23 panic("only the sponsor can configure micro-grants")
24 }
25 budget.RequireAddress(approver)
26 // Registration checks the draft, lane, and pinned realm identity.
27 treasury.RegisterPolicy(cross(cur), programID, lane)
28 approvers.Set(budget.PolicyLaneKey(programID, lane), approver)
29}
30
31func ApproveGrant(cur realm, programID int64, lane string, recipient address, amount int64, memo string) int64 {
32 caller := callerAddress(cur)
33 if caller != GetApprover(programID, lane) {
34 panic("only the configured micro-grant approver can award grants")
35 }
36 if caller == recipient {
37 panic("approver cannot award their own grant")
38 }
39 deadline := budget.Add(runtime.ChainHeight(), 1)
40 itemID, _ := treasury.Reserve(cross(cur), programID, lane, recipient, amount, deadline, memo)
41 treasury.Approve(cross(cur), programID, lane, itemID)
42 return itemID
43}
44
45func GetApprover(programID int64, lane string) address {
46 approver, _ := approvers.Get(budget.PolicyLaneKey(programID, lane)).(address)
47 return approver
48}
49
50func Render(path string) string {
51 const header = "# Micro-grants\n\n"
52 program, names, _ := treasury.PolicyRenderRoute(path, realmPath)
53 switch len(names) {
54 case 0:
55 return header + "Open a configured lane with `:programID/lane`."
56 case 1:
57 lane := names[0]
58 page := header + "**Lane** " + budget.MarkdownText(lane) +
59 " · **Approver** " + string(GetApprover(program.ID, lane)) + "\n"
60 if program.Status == treasury.Active {
61 tx := txlink.Realm(realmPath)
62 page += "\n[Award a grant](" + tx.Call("ApproveGrant", "programID", strconv.FormatInt(program.ID, 10), "lane", lane) + ")\n"
63 }
64 return page
65 default:
66 return header + budget.PolicyLaneLinks(realmPath, program.ID, names)
67 }
68}
69
70func callerAddress(cur realm) address {
71 if !cur.IsCurrent() || cur.PkgPath() != realmPath {
72 panic("invalid micro-grant policy context")
73 }
74 if len(unsafe.OriginSend()) != 0 {
75 panic("unexpected attached coins")
76 }
77 return cur.Previous().Address()
78}