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