Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

treasury.gno

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