treasury.gno
12.79 Kb · 448 lines
1// Package treasury holds the funds and accounting for Shared Budget programs.
2package treasury
3
4import (
5 "chain"
6 "chain/banker"
7 "chain/runtime"
8 "chain/runtime/unsafe"
9 "strconv"
10 "strings"
11
12 "gno.land/p/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/budget/v1"
13)
14
15const (
16 packagePath = "gno.land/r/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/treasury/v1"
17
18 Draft = "draft"
19 Active = "active"
20 IssuanceClosed = "issuance_closed"
21 Closed = "closed"
22
23 Reserved = "reserved"
24 Approved = "approved"
25 Rejected = "rejected"
26 Expired = "expired"
27)
28
29type policy struct {
30 path string
31 addr address
32 periodCap int64
33 itemCap int64
34 registered bool
35 usage map[int64]int64
36 items map[int64]*reservation
37 itemIDs []int64
38}
39
40type claim struct {
41 recipient address
42 amount int64
43 paid bool
44}
45
46type reservation struct {
47 payment claim
48 status string
49 period int64
50 deadline int64
51}
52
53type program struct {
54 sponsor address
55 status string
56 periodBlocks int64
57 issueBlocks int64
58 maxHold int64
59 start int64
60 issueEnd int64
61 maintenance policy
62 reimbursements policy
63 ledger budget.Ledger
64 activeCount int64
65 refund claim
66}
67
68var (
69 programs = make(map[int64]*program)
70 latestProgramID int64
71 outstanding int64
72)
73
74// CreateProgram pins both policy packages. The sponsor can fund the program
75// after each policy has configured its roles and registered.
76func CreateProgram(cur realm, maintenancePath, reimbursementsPath string, maintenancePeriodCap, maintenanceItemCap, reimbursementsPeriodCap, reimbursementsItemCap, periodBlocks, issueBlocks, maxHold int64) int64 {
77 runtime.AssertOriginCall()
78 sponsor := userCaller(cur, false)
79 if maintenancePath == reimbursementsPath {
80 panic("policies must use distinct realm paths")
81 }
82 if periodBlocks <= 0 || issueBlocks <= 0 || maxHold <= 0 {
83 panic("program durations must be positive")
84 }
85 p := &program{
86 sponsor: sponsor,
87 status: Draft,
88 periodBlocks: periodBlocks,
89 issueBlocks: issueBlocks,
90 maxHold: maxHold,
91 maintenance: newPolicy(maintenancePath, maintenancePeriodCap, maintenanceItemCap),
92 reimbursements: newPolicy(reimbursementsPath, reimbursementsPeriodCap, reimbursementsItemCap),
93 }
94 id := budget.Add(latestProgramID, 1)
95 programs[id] = p
96 latestProgramID = id
97 chain.Emit("ProgramCreated", "program", number(id), "sponsor", string(sponsor))
98 return id
99}
100
101func RegisterPolicy(cur realm, programID int64) {
102 requireTreasury(cur)
103 p := mustProgram(programID)
104 lane, rule := p.policyCaller(cur)
105 if p.status != Draft || rule.registered {
106 panic("policy registration requires an unconfigured draft")
107 }
108 rule.registered = true
109 chain.Emit("PolicyRegistered", "program", number(programID), "lane", lane, "path", rule.path)
110}
111
112func Open(cur realm, programID int64) {
113 runtime.AssertOriginCall()
114 sponsor := userCaller(cur, true)
115 p := sponsorProgram(programID, sponsor)
116 if p.status != Draft || !p.maintenance.registered || !p.reimbursements.registered {
117 panic("opening requires a draft with both policies registered")
118 }
119 amount := fundingAmount()
120 p.start = runtime.ChainHeight()
121 p.issueEnd = budget.Add(p.start, p.issueBlocks)
122 p.credit(amount)
123 p.status = Active
124 chain.Emit("ProgramOpened", "program", number(programID), "sponsor", string(sponsor), "amount", number(amount), "start", number(p.start), "issue_end", number(p.issueEnd))
125}
126
127func Fund(cur realm, programID int64) {
128 runtime.AssertOriginCall()
129 sponsor := userCaller(cur, true)
130 p := sponsorProgram(programID, sponsor)
131 if p.statusAt(runtime.ChainHeight()) != Active {
132 panic("program is not accepting funds")
133 }
134 amount := fundingAmount()
135 p.credit(amount)
136 chain.Emit("ProgramFunded", "program", number(programID), "sponsor", string(sponsor), "amount", number(amount))
137}
138
139// Reserve is callable by the registered policy for its own spending lane.
140func Reserve(cur realm, programID, itemID int64, recipient address, amount, deadline int64) int64 {
141 requireTreasury(cur)
142 p := mustProgram(programID)
143 lane, rule := p.policyCaller(cur)
144 height := runtime.ChainHeight()
145 if !rule.registered || p.statusAt(height) != Active {
146 panic("program is not accepting reservations")
147 }
148 if itemID <= 0 || rule.items[itemID] != nil {
149 panic("item ID must be positive and unused in this lane")
150 }
151 budget.RequireAddress(recipient)
152 if recipient == cur.Address() {
153 panic("the treasury cannot be an item recipient")
154 }
155 budget.RequirePositive(amount)
156 budget.CheckDeadline(height, deadline, p.maxHold)
157 if amount > rule.itemCap {
158 panic("item cap exceeded")
159 }
160 period := p.periodAt(height)
161 if amount > rule.periodCap-rule.usage[period] {
162 panic("period cap exceeded")
163 }
164 if amount > p.ledger.Available {
165 panic("shared balance exceeded")
166 }
167
168 p.ledger = p.ledger.Reserve(amount)
169 p.activeCount = budget.Add(p.activeCount, 1)
170 rule.usage[period] = budget.Add(rule.usage[period], amount)
171 item := &reservation{
172 payment: claim{recipient: recipient, amount: amount},
173 status: Reserved,
174 period: period,
175 deadline: deadline,
176 }
177 rule.items[itemID] = item
178 rule.itemIDs = append(rule.itemIDs, itemID)
179 emitItem("Reserved", programID, lane, itemID, item)
180 return p.ledger.Available
181}
182
183func Approve(cur realm, programID, itemID int64) {
184 requireTreasury(cur)
185 p := mustProgram(programID)
186 lane, rule := p.policyCaller(cur)
187 item := rule.pendingBeforeDeadline(itemID)
188 p.ledger = p.ledger.Approve(item.payment.amount)
189 p.activeCount = budget.Subtract(p.activeCount, 1)
190 item.status = Approved
191 emitItem("Approved", programID, lane, itemID, item)
192}
193
194func Reject(cur realm, programID, itemID int64) {
195 requireTreasury(cur)
196 p := mustProgram(programID)
197 lane, rule := p.policyCaller(cur)
198 item := rule.pendingBeforeDeadline(itemID)
199 p.release(rule, item, Rejected)
200 emitItem("Rejected", programID, lane, itemID, item)
201}
202
203func Expire(cur realm, programID int64, lane string, itemID int64) {
204 runtime.AssertOriginCall()
205 userCaller(cur, false)
206 p := mustProgram(programID)
207 rule := p.rule(lane)
208 item := rule.pending(itemID)
209 if runtime.ChainHeight() < item.deadline {
210 panic("reservation has not reached its deadline")
211 }
212 p.release(rule, item, Expired)
213 emitItem("Expired", programID, lane, itemID, item)
214}
215
216func CloseIssuance(cur realm, programID int64) {
217 runtime.AssertOriginCall()
218 sponsor := userCaller(cur, false)
219 p := sponsorProgram(programID, sponsor)
220 if p.statusAt(runtime.ChainHeight()) != Active {
221 panic("issuance is not active")
222 }
223 p.status = IssuanceClosed
224 chain.Emit("IssuanceClosed", "program", number(programID), "sponsor", string(sponsor))
225}
226
227// FinalizeClose turns the remainder into a sponsor claim. Recipient claims
228// continue to be payable after the program closes.
229func FinalizeClose(cur realm, programID int64) {
230 runtime.AssertOriginCall()
231 caller := userCaller(cur, false)
232 p := mustProgram(programID)
233 if p.statusAt(runtime.ChainHeight()) != IssuanceClosed {
234 panic("close issuance before finalization")
235 }
236 if p.activeCount != 0 {
237 panic("program still has active reservations")
238 }
239 amount := p.ledger.Available
240 if amount > 0 {
241 p.refund = claim{recipient: p.sponsor, amount: amount}
242 }
243 p.ledger = p.ledger.RefundAvailable()
244 p.status = Closed
245 chain.Emit("ProgramClosed", "program", number(programID), "actor", string(caller), "refund", number(amount))
246}
247
248// Withdraw pays an approved item. Use lane "refund" and item ID 0 for the
249// sponsor claim created by FinalizeClose.
250func Withdraw(cur realm, programID int64, lane string, itemID int64) {
251 runtime.AssertOriginCall()
252 caller := userCaller(cur, false)
253 p := mustProgram(programID)
254 payment := p.findClaim(lane, itemID)
255 if payment == nil || payment.recipient != caller {
256 panic("claim is payable only to its recipient")
257 }
258 if payment.paid {
259 panic("claim already paid")
260 }
261
262 p.ledger = p.ledger.Pay(payment.amount)
263 outstanding = budget.Subtract(outstanding, payment.amount)
264 payment.paid = true
265 coins := chain.Coins{chain.NewCoin(budget.Denom, payment.amount)}
266 banker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(cur.Address(), payment.recipient, coins)
267 chain.Emit("Withdrawn", "program", number(programID), "lane", lane, "item", number(itemID), "recipient", string(caller), "amount", number(payment.amount))
268}
269
270func newPolicy(path string, periodCap, itemCap int64) policy {
271 const prefix = "gno.land/r/"
272 if len(path) > 256 || !strings.HasPrefix(path, prefix) {
273 panic("expected a versioned policy realm path")
274 }
275 parts := strings.Split(path[len(prefix):], "/")
276 version := parts[len(parts)-1]
277 if len(parts) < 3 || len(version) < 2 || version[0] != 'v' || path == packagePath {
278 panic("expected a versioned policy realm path")
279 }
280 for _, part := range parts {
281 if !validPathSegment(part) {
282 panic("expected a versioned policy realm path")
283 }
284 }
285 n, err := strconv.ParseInt(version[1:], 10, 64)
286 if err != nil || n < 0 || version != "v"+number(n) {
287 panic("expected a versioned policy realm path")
288 }
289 if itemCap <= 0 || itemCap > periodCap {
290 panic("policy caps require 0 < item cap <= period cap")
291 }
292 return policy{
293 path: path,
294 addr: chain.PackageAddress(path),
295 periodCap: periodCap,
296 itemCap: itemCap,
297 usage: make(map[int64]int64),
298 items: make(map[int64]*reservation),
299 }
300}
301
302// Follow the Gno package path rules for each namespace and package segment.
303func validPathSegment(part string) bool {
304 if part == "" || part[0] < 'a' || part[0] > 'z' {
305 return false
306 }
307 separator := false
308 for i := 1; i < len(part); i++ {
309 c := part[i]
310 switch {
311 case c >= 'a' && c <= 'z', c >= '0' && c <= '9':
312 separator = false
313 case (c == '-' || c == '_') && !separator:
314 separator = true
315 default:
316 return false
317 }
318 }
319 return !separator
320}
321
322func (p *program) credit(amount int64) {
323 p.ledger = p.ledger.Fund(amount)
324 outstanding = budget.Add(outstanding, amount)
325}
326
327func (p *program) release(rule *policy, item *reservation, status string) {
328 amount := item.payment.amount
329 p.ledger = p.ledger.Release(amount)
330 p.activeCount = budget.Subtract(p.activeCount, 1)
331 rule.usage[item.period] = budget.Subtract(rule.usage[item.period], amount)
332 item.status = status
333}
334
335func (p *program) statusAt(height int64) string {
336 if p.status == Active && height >= p.issueEnd {
337 return IssuanceClosed
338 }
339 return p.status
340}
341
342func (p *program) periodAt(height int64) int64 {
343 return budget.PeriodAt(height, p.start, p.periodBlocks)
344}
345
346func (p *program) rule(lane string) *policy {
347 switch lane {
348 case budget.Maintenance:
349 return &p.maintenance
350 case budget.Reimbursements:
351 return &p.reimbursements
352 default:
353 panic("unknown policy lane")
354 }
355}
356
357func (p *program) policyCaller(cur realm) (string, *policy) {
358 caller := cur.Previous()
359 if caller.PkgPath() == p.maintenance.path && caller.Address() == p.maintenance.addr {
360 return budget.Maintenance, &p.maintenance
361 }
362 if caller.PkgPath() == p.reimbursements.path && caller.Address() == p.reimbursements.addr {
363 return budget.Reimbursements, &p.reimbursements
364 }
365 panic("caller is not a pinned policy realm")
366}
367
368func (p *program) findClaim(lane string, itemID int64) *claim {
369 if lane == budget.Refund {
370 if itemID == 0 && p.refund.amount > 0 {
371 return &p.refund
372 }
373 return nil
374 }
375 item := p.rule(lane).items[itemID]
376 if item == nil || item.status != Approved {
377 return nil
378 }
379 return &item.payment
380}
381
382func (rule *policy) pending(itemID int64) *reservation {
383 item := rule.items[itemID]
384 if item == nil || item.status != Reserved {
385 panic("reservation is not pending")
386 }
387 return item
388}
389
390func (rule *policy) pendingBeforeDeadline(itemID int64) *reservation {
391 item := rule.pending(itemID)
392 if runtime.ChainHeight() >= item.deadline {
393 panic("reservation deadline reached")
394 }
395 return item
396}
397
398func mustProgram(id int64) *program {
399 p := programs[id]
400 if p == nil {
401 panic("program not found")
402 }
403 return p
404}
405
406func sponsorProgram(id int64, caller address) *program {
407 p := mustProgram(id)
408 if p.sponsor != caller {
409 panic("only the program sponsor can do that")
410 }
411 return p
412}
413
414func fundingAmount() int64 {
415 coins := unsafe.OriginSend()
416 if len(coins) != 1 || coins[0].Denom != budget.Denom || coins[0].Amount <= 0 {
417 panic("attach a positive amount of ugnot")
418 }
419 return coins[0].Amount
420}
421
422func requireTreasury(cur realm) {
423 if !cur.IsCurrent() || cur.PkgPath() != packagePath {
424 panic("invalid treasury context")
425 }
426}
427
428func userCaller(cur realm, payable bool) address {
429 requireTreasury(cur)
430 caller := cur.Previous()
431 if !caller.IsUserCall() {
432 panic("direct treasury call required")
433 }
434 if !payable && len(unsafe.OriginSend()) != 0 {
435 panic("unexpected attached coins")
436 }
437 return caller.Address()
438}
439
440func emitItem(event string, programID int64, lane string, id int64, item *reservation) {
441 chain.Emit(event, "program", number(programID), "lane", lane, "item", number(id),
442 "recipient", string(item.payment.recipient), "amount", number(item.payment.amount),
443 "period", number(item.period), "deadline", number(item.deadline))
444}
445
446func number(n int64) string {
447 return strconv.FormatInt(n, 10)
448}