treasury.gno
16.74 Kb · 613 lines
1// Package treasury holds funds and accounts for reservations across independent policies.
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/v2"
13 "gno.land/p/nt/avl/v0"
14)
15
16const (
17 packagePath = "gno.land/r/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/treasury/v3"
18 maxScheduleBlocks int64 = 2147483647
19 maxPolicies = 8
20
21 Draft = "draft"
22 Active = "active"
23 IssuanceClosed = "issuance_closed"
24 Closed = "closed"
25
26 Reserved = "reserved"
27 Approved = "approved"
28 Rejected = "rejected"
29 Canceled = "canceled"
30 Expired = "expired"
31)
32
33type policy struct {
34 lane string
35 path string
36 addr address
37 periodCap int64
38 itemCap int64
39 canBreachFloor bool
40 registered bool
41 lastItemID int64
42 usage *avl.Tree
43 items *avl.Tree
44}
45
46type claim struct {
47 recipient address
48 amount int64
49 paid bool
50}
51
52type reservation struct {
53 id int64
54 payment claim
55 status string
56 period int64
57 deadline int64
58 memo string
59}
60
61type program struct {
62 id int64
63 sponsor address
64 title string
65 status string
66 reserveFloor int64
67 periodBlocks int64
68 issueBlocks int64
69 maxHold int64
70 start int64
71 issueEnd int64
72 closedHeight int64
73 closedPeriod int64
74 pruned bool
75 policies []*policy
76 ledger budget.Ledger
77 activeCount int64
78 refund claim
79}
80
81var (
82 programs = avl.NewTree()
83 latestProgramID int64
84 outstanding int64
85)
86
87func CreateProgram(cur realm, title string, reserveFloor, periodBlocks, issueBlocks, maxHold int64) int64 {
88 sponsor := userCaller(cur, false)
89 budget.RequireMemo(title)
90 requireFloor(reserveFloor)
91 if periodBlocks <= 0 || issueBlocks <= 0 || maxHold <= 0 {
92 panic("program durations must be positive")
93 }
94 if periodBlocks > maxScheduleBlocks || issueBlocks > maxScheduleBlocks || maxHold > maxScheduleBlocks {
95 panic("program durations cannot exceed 2147483647 blocks")
96 }
97 runtime.AssertOriginCall()
98 id := budget.Add(latestProgramID, 1)
99 programs.Set(numericKey(id), &program{
100 id: id, sponsor: sponsor, title: title, status: Draft, reserveFloor: reserveFloor,
101 periodBlocks: periodBlocks, issueBlocks: issueBlocks, maxHold: maxHold,
102 })
103 latestProgramID = id
104 chain.Emit("ProgramCreated", "program", number(id), "sponsor", string(sponsor),
105 "title", title, "reserve_floor", number(reserveFloor))
106 return id
107}
108
109func AddPolicy(cur realm, programID int64, lane, policyPath string, periodCap, itemCap int64, canBreachFloor bool) {
110 p := sponsorProgram(programID, userCaller(cur, false))
111 if p.status != Draft {
112 panic("policies can only be added to a draft")
113 }
114 if len(p.policies) == maxPolicies {
115 panic("a program can have at most 8 policies")
116 }
117 budget.RequireLaneName(lane)
118 requirePolicyPath(policyPath)
119 if itemCap <= 0 || itemCap > periodCap {
120 panic("policy caps require 0 < item cap <= period cap")
121 }
122 for _, rule := range p.policies {
123 if lane == rule.lane {
124 panic("policy lane already added")
125 }
126 if policyPath == rule.path {
127 panic("policies must use distinct realm paths")
128 }
129 }
130 runtime.AssertOriginCall()
131 addr := chain.PackageAddress(policyPath)
132 p.policies = append(p.policies, &policy{
133 lane: lane, path: policyPath, addr: addr, periodCap: periodCap, itemCap: itemCap,
134 canBreachFloor: canBreachFloor, usage: avl.NewTree(), items: avl.NewTree(),
135 })
136 chain.Emit("PolicyAdded", "program", number(programID), "lane", lane, "path", policyPath,
137 "address", string(addr), "period_cap", number(periodCap), "item_cap", number(itemCap),
138 "can_breach_floor", strconv.FormatBool(canBreachFloor))
139}
140
141func RegisterPolicy(cur realm, programID int64, lane string) {
142 requireTreasury(cur)
143 p := mustProgram(programID)
144 rule := p.rule(lane)
145 caller := cur.Previous()
146 if !rule.matches(caller.PkgPath(), caller.Address()) {
147 panic("caller is not the pinned policy for this lane")
148 }
149 if p.status != Draft || rule.registered {
150 panic("policy registration requires an unconfigured draft")
151 }
152 rule.registered = true
153 chain.Emit("PolicyRegistered", "program", number(programID), "lane", lane, "path", rule.path)
154}
155
156func Open(cur realm, programID int64) {
157 sponsor := userCaller(cur, true)
158 p := sponsorProgram(programID, sponsor)
159 if p.status != Draft || len(p.policies) == 0 {
160 panic("opening requires a draft with at least one policy")
161 }
162 for _, rule := range p.policies {
163 if !rule.registered {
164 panic("all policies must be registered before opening")
165 }
166 }
167 amount := fundingAmount()
168 runtime.AssertOriginCall()
169 p.start = runtime.ChainHeight()
170 p.issueEnd = budget.Add(p.start, p.issueBlocks)
171 p.credit(amount)
172 p.status = Active
173 chain.Emit("ProgramOpened", "program", number(programID), "sponsor", string(sponsor),
174 "amount", number(amount), "start", number(p.start), "issue_end", number(p.issueEnd))
175}
176
177func Fund(cur realm, programID int64) {
178 sponsor := userCaller(cur, true)
179 p := sponsorProgram(programID, sponsor)
180 if p.statusAt(runtime.ChainHeight()) != Active {
181 panic("program is not accepting funds")
182 }
183 amount := fundingAmount()
184 runtime.AssertOriginCall()
185 p.credit(amount)
186 chain.Emit("ProgramFunded", "program", number(programID), "sponsor", string(sponsor), "amount", number(amount))
187}
188
189func UpdateReserveFloor(cur realm, programID, newFloor int64) {
190 p := sponsorProgram(programID, userCaller(cur, false))
191 if p.statusAt(runtime.ChainHeight()) != Active {
192 panic("reserve floor can only be updated while active")
193 }
194 requireFloor(newFloor)
195 runtime.AssertOriginCall()
196 oldFloor := p.reserveFloor
197 p.reserveFloor = newFloor
198 chain.Emit("ReserveFloorUpdated", "program", number(programID), "old_floor", number(oldFloor), "reserve_floor", number(newFloor))
199}
200
201// Reserve assigns the next item ID in the caller's lane and returns it with the remaining available balance.
202func Reserve(cur realm, programID int64, recipient address, amount, deadline int64, memo string) (int64, int64) {
203 requireTreasury(cur)
204 p := mustProgram(programID)
205 rule := p.policyCaller(cur)
206 height := runtime.ChainHeight()
207 if p.statusAt(height) != Active {
208 panic("program is not accepting reservations")
209 }
210 budget.RequireAddress(recipient)
211 if recipient == cur.Address() {
212 panic("the treasury cannot be an item recipient")
213 }
214 budget.RequirePositive(amount)
215 budget.CheckDeadline(height, deadline, p.maxHold)
216 budget.RequireMemo(memo)
217 period := p.periodAt(height)
218 check := p.evaluate(rule, period, amount)
219 if !check.Allowed {
220 switch check.BindingConstraint {
221 case "item_cap":
222 panic("item cap exceeded")
223 case "period_cap":
224 panic("period cap exceeded")
225 case "reserve_floor":
226 panic("reserve floor exceeded")
227 default:
228 panic("shared balance exceeded")
229 }
230 }
231
232 id := budget.Add(rule.lastItemID, 1)
233 item := &reservation{
234 id: id, payment: claim{recipient: recipient, amount: amount}, status: Reserved,
235 period: period, deadline: deadline, memo: memo,
236 }
237 p.ledger = p.ledger.Reserve(amount)
238 p.activeCount = budget.Add(p.activeCount, 1)
239 rule.usage.Set(numericKey(period), budget.Add(rule.used(period), amount))
240 rule.items.Set(numericKey(id), item)
241 rule.lastItemID = id
242 emitItem("Reserved", programID, rule.lane, item)
243 return id, p.ledger.Available
244}
245
246func Approve(cur realm, programID, itemID int64) {
247 requireTreasury(cur)
248 p := mustProgram(programID)
249 rule := p.policyCaller(cur)
250 item := rule.pendingBeforeDeadline(itemID)
251 p.ledger = p.ledger.Approve(item.payment.amount)
252 p.activeCount = budget.Subtract(p.activeCount, 1)
253 item.status = Approved
254 emitItem("Approved", programID, rule.lane, item)
255}
256
257func Reject(cur realm, programID, itemID int64) {
258 requireTreasury(cur)
259 p := mustProgram(programID)
260 rule := p.policyCaller(cur)
261 p.release(rule, rule.pendingBeforeDeadline(itemID), Rejected, "Rejected")
262}
263
264func Cancel(cur realm, programID, itemID int64) {
265 requireTreasury(cur)
266 p := mustProgram(programID)
267 rule := p.policyCaller(cur)
268 p.release(rule, rule.pendingBeforeDeadline(itemID), Canceled, "Canceled")
269}
270
271func Expire(cur realm, programID int64, lane string, itemID int64) {
272 requireTreasury(cur)
273 requireNoSend()
274 p := mustProgram(programID)
275 rule := p.rule(lane)
276 item := rule.pending(itemID)
277 if runtime.ChainHeight() < item.deadline {
278 panic("reservation has not reached its deadline")
279 }
280 p.release(rule, item, Expired, "Expired")
281}
282
283func CloseIssuance(cur realm, programID int64) {
284 sponsor := userCaller(cur, false)
285 p := sponsorProgram(programID, sponsor)
286 if p.statusAt(runtime.ChainHeight()) != Active {
287 panic("issuance is not active")
288 }
289 runtime.AssertOriginCall()
290 p.status = IssuanceClosed
291 chain.Emit("IssuanceClosed", "program", number(programID), "sponsor", string(sponsor))
292}
293
294// FinalizeClose creates a sponsor refund and freezes the period displayed for the program.
295func FinalizeClose(cur realm, programID int64) {
296 requireTreasury(cur)
297 requireNoSend()
298 p := mustProgram(programID)
299 height := runtime.ChainHeight()
300 if p.statusAt(height) != IssuanceClosed {
301 panic("close issuance before finalization")
302 }
303 if p.activeCount != 0 {
304 panic("program still has active reservations")
305 }
306 amount := p.ledger.Available
307 if amount > 0 {
308 p.refund = claim{recipient: p.sponsor, amount: amount}
309 }
310 p.ledger = p.ledger.RefundAvailable()
311 p.closedPeriod = p.periodAt(height)
312 p.closedHeight = height
313 p.status = Closed
314 chain.Emit("ProgramClosed", "program", number(programID), "actor", string(cur.Previous().Address()),
315 "refund", number(amount), "closed_height", number(height), "closed_period", number(p.closedPeriod))
316}
317
318// Withdraw pays an approved claim. Use lane "refund" and item ID 0 for the sponsor refund.
319func Withdraw(cur realm, programID int64, lane string, itemID int64) {
320 requireTreasury(cur)
321 requireNoSend()
322 caller := cur.Previous().Address()
323 p := mustProgram(programID)
324 payment := p.findClaim(lane, itemID)
325 if payment == nil || payment.recipient != caller {
326 panic("claim is payable only to its recipient")
327 }
328 if payment.paid {
329 panic("claim already paid")
330 }
331 p.ledger = p.ledger.Pay(payment.amount)
332 outstanding = budget.Subtract(outstanding, payment.amount)
333 payment.paid = true
334 coins := chain.Coins{chain.NewCoin(budget.Denom, payment.amount)}
335 banker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(cur.Address(), payment.recipient, coins)
336 chain.Emit("Withdrawn", "program", number(programID), "lane", lane, "item", number(itemID),
337 "recipient", string(caller), "amount", number(payment.amount))
338}
339
340func PruneClosed(cur realm, programID int64) int64 {
341 p := sponsorProgram(programID, userCaller(cur, false))
342 if !p.canPrune() {
343 panic("pruning requires an unpruned closed program with no unpaid claims or pending reservations")
344 }
345 runtime.AssertOriginCall()
346 count := int64(0)
347 for _, rule := range p.policies {
348 count = budget.Add(count, int64(rule.items.Size()))
349 rule.items = nil
350 rule.usage = nil
351 }
352 p.pruned = true
353 chain.Emit("ProgramPruned", "program", number(programID), "items", number(count))
354 return count
355}
356
357func (p *program) canPrune() bool {
358 return p.status == Closed && p.ledger.Claimable == 0 && p.activeCount == 0 && !p.pruned
359}
360
361func requireFloor(floor int64) {
362 if floor < 0 {
363 panic("reserve floor must be non-negative")
364 }
365}
366
367func requirePolicyPath(path string) {
368 const prefix = "gno.land/r/"
369 if len(path) > 256 || !strings.HasPrefix(path, prefix) || path == packagePath {
370 panic("expected a versioned policy realm path")
371 }
372 parts := strings.Split(path[len(prefix):], "/")
373 last := len(parts) - 1
374 if last < 1 || !versionSuffix(parts[last]) || versionSuffix(parts[last-1]) {
375 panic("expected a versioned policy realm path")
376 }
377 for _, part := range parts {
378 if !validPathSegment(part) {
379 panic("expected a versioned policy realm path")
380 }
381 }
382}
383
384func versionSuffix(part string) bool {
385 if part == "v0" {
386 return true
387 }
388 if len(part) < 2 || part[0] != 'v' || part[1] < '1' || part[1] > '9' {
389 return false
390 }
391 for i := 2; i < len(part); i++ {
392 if part[i] < '0' || part[i] > '9' {
393 return false
394 }
395 }
396 return true
397}
398
399// Each Gno package path segment starts with a letter and has interior separators only.
400func validPathSegment(part string) bool {
401 if part == "" || part[0] < 'a' || part[0] > 'z' {
402 return false
403 }
404 separator := false
405 for i := 1; i < len(part); i++ {
406 c := part[i]
407 switch {
408 case c >= 'a' && c <= 'z', c >= '0' && c <= '9':
409 separator = false
410 case (c == '-' || c == '_') && !separator:
411 separator = true
412 default:
413 return false
414 }
415 }
416 return !separator
417}
418
419func (p *program) credit(amount int64) {
420 p.ledger = p.ledger.Fund(amount)
421 outstanding = budget.Add(outstanding, amount)
422}
423
424func (p *program) release(rule *policy, item *reservation, status, event string) {
425 amount := item.payment.amount
426 p.ledger = p.ledger.Release(amount)
427 p.activeCount = budget.Subtract(p.activeCount, 1)
428 used := budget.Subtract(rule.used(item.period), amount)
429 key := numericKey(item.period)
430 if used == 0 {
431 rule.usage.Remove(key)
432 } else {
433 rule.usage.Set(key, used)
434 }
435 item.status = status
436 emitItem(event, p.id, rule.lane, item)
437}
438
439func (p *program) statusAt(height int64) string {
440 if p.status == Active && height >= p.issueEnd {
441 return IssuanceClosed
442 }
443 return p.status
444}
445
446func (p *program) periodAt(height int64) int64 {
447 switch p.status {
448 case Draft:
449 return 0
450 case Closed:
451 return p.closedPeriod
452 default:
453 return budget.PeriodAt(height, p.start, p.periodBlocks)
454 }
455}
456
457func (p *program) evaluate(rule *policy, period, amount int64) budget.SpendCheck {
458 return budget.EvaluateSpend(p.ledger.Available, p.reserveFloor, rule.canBreachFloor,
459 rule.itemCap, rule.periodCap, rule.used(period), amount)
460}
461
462func (p *program) findRule(lane string) *policy {
463 for _, rule := range p.policies {
464 if rule.lane == lane {
465 return rule
466 }
467 }
468 return nil
469}
470
471func (p *program) rule(lane string) *policy {
472 rule := p.findRule(lane)
473 if rule == nil {
474 panic("unknown policy lane")
475 }
476 return rule
477}
478
479func (p *program) policyCaller(cur realm) *policy {
480 caller := cur.Previous()
481 path, addr := caller.PkgPath(), caller.Address()
482 for _, rule := range p.policies {
483 if rule.matches(path, addr) {
484 if !rule.registered {
485 panic("policy is not registered")
486 }
487 return rule
488 }
489 }
490 panic("caller is not a pinned policy realm")
491}
492
493func (rule *policy) matches(path string, addr address) bool {
494 return path == rule.path && addr == rule.addr
495}
496
497func (p *program) findClaim(lane string, itemID int64) *claim {
498 if lane == budget.RefundLane {
499 if itemID == 0 && p.refund.amount > 0 {
500 return &p.refund
501 }
502 return nil
503 }
504 item := p.rule(lane).item(itemID)
505 if item == nil || item.status != Approved {
506 return nil
507 }
508 return &item.payment
509}
510
511func (rule *policy) used(period int64) int64 {
512 if rule.usage == nil {
513 return 0
514 }
515 amount, _ := rule.usage.Get(numericKey(period)).(int64)
516 return amount
517}
518
519func (rule *policy) item(id int64) *reservation {
520 if rule.items == nil || id <= 0 {
521 return nil
522 }
523 item, _ := rule.items.Get(numericKey(id)).(*reservation)
524 return item
525}
526
527func (rule *policy) pending(id int64) *reservation {
528 item := rule.item(id)
529 if item == nil || item.status != Reserved {
530 panic("reservation is not pending")
531 }
532 return item
533}
534
535func (rule *policy) pendingBeforeDeadline(id int64) *reservation {
536 item := rule.pending(id)
537 if runtime.ChainHeight() >= item.deadline {
538 panic("reservation deadline reached")
539 }
540 return item
541}
542
543func findProgram(id int64) *program {
544 if id <= 0 {
545 return nil
546 }
547 p, _ := programs.Get(numericKey(id)).(*program)
548 return p
549}
550
551func mustProgram(id int64) *program {
552 p := findProgram(id)
553 if p == nil {
554 panic("program not found")
555 }
556 return p
557}
558
559func sponsorProgram(id int64, caller address) *program {
560 p := mustProgram(id)
561 if p.sponsor != caller {
562 panic("only the program sponsor can do that")
563 }
564 return p
565}
566
567func fundingAmount() int64 {
568 coins := unsafe.OriginSend()
569 if len(coins) != 1 || coins[0].Denom != budget.Denom || coins[0].Amount <= 0 {
570 panic("attach a positive amount of ugnot")
571 }
572 return coins[0].Amount
573}
574
575func requireTreasury(cur realm) {
576 if !cur.IsCurrent() || cur.PkgPath() != packagePath {
577 panic("invalid treasury context")
578 }
579}
580
581func requireNoSend() {
582 if len(unsafe.OriginSend()) != 0 {
583 panic("unexpected attached coins")
584 }
585}
586
587func userCaller(cur realm, payable bool) address {
588 requireTreasury(cur)
589 caller := cur.Previous()
590 if !caller.IsUserCall() {
591 panic("direct treasury call required")
592 }
593 if !payable {
594 requireNoSend()
595 }
596 return caller.Address()
597}
598
599func emitItem(event string, programID int64, lane string, item *reservation) {
600 chain.Emit(event, "program", number(programID), "lane", lane, "item", number(item.id),
601 "recipient", string(item.payment.recipient), "amount", number(item.payment.amount),
602 "period", number(item.period), "deadline", number(item.deadline), "memo", item.memo)
603}
604
605func numericKey(n int64) string {
606 const zeros = "0000000000000000000"
607 digits := number(n)
608 return zeros[len(digits):] + digits
609}
610
611func number(n int64) string {
612 return strconv.FormatInt(n, 10)
613}