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.

Playground

budget.gno

// Package budget provides accounting, spending limits, and presentation for a shared pool.
package budget

import (
	"crypto/bech32"
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"strings"
	"unicode"
	"unicode/utf8"
)

const (
	Denom      = "ugnot"
	RefundLane = "refund"
	maxInt64   = 1<<63 - 1
)

type Ledger struct {
	Funded    int64
	Available int64
	Reserved  int64
	Claimable int64
	Paid      int64
}

// AssertConserved checks that all balances are non-negative and account for all funding.
func (l Ledger) AssertConserved() {
	total := Add(Add(l.Available, l.Reserved), Add(l.Claimable, l.Paid))
	if l.Funded != total {
		panic("ledger does not conserve funds")
	}
}

type SpendCheck struct {
	Allowed           bool
	Amount            int64
	MaxAllowed        int64
	Shortfall         int64
	BindingConstraint string
	ItemRoom          int64
	PeriodRoom        int64
	PoolRoom          int64
}

// EvaluateSpend reports the tightest room, breaking ties in item, period, pool
// order. A pool failure identifies a shortfall of cash before floor protection.
func EvaluateSpend(available, reserveFloor int64, canBreachFloor bool, itemCap, periodCap, periodUsed, amount int64) SpendCheck {
	RequirePositive(amount)
	if available < 0 || reserveFloor < 0 || itemCap < 0 || periodCap < 0 || periodUsed < 0 {
		panic("spending limits and balances must be non-negative")
	}
	check := SpendCheck{
		Amount:     amount,
		ItemRoom:   itemCap,
		PeriodRoom: nonnegative(periodCap - periodUsed),
		PoolRoom:   available,
	}
	if !canBreachFloor {
		check.PoolRoom = nonnegative(available - reserveFloor)
	}
	check.MaxAllowed = min64(min64(check.ItemRoom, check.PeriodRoom), check.PoolRoom)
	check.Allowed = amount <= check.MaxAllowed
	if check.Allowed {
		return check
	}
	check.Shortfall = amount - check.MaxAllowed
	switch {
	case check.MaxAllowed == check.ItemRoom:
		check.BindingConstraint = "item_cap"
	case check.MaxAllowed == check.PeriodRoom:
		check.BindingConstraint = "period_cap"
	case amount > available:
		check.BindingConstraint = "shared_balance"
	default:
		check.BindingConstraint = "reserve_floor"
	}
	return check
}

func min64(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

func nonnegative(n int64) int64 {
	if n < 0 {
		return 0
	}
	return n
}

func Add(a, b int64) int64 {
	if a < 0 || b < 0 || a > maxInt64-b {
		panic("amount or height overflow")
	}
	return a + b
}

func Subtract(a, b int64) int64 {
	if b < 0 || a < b {
		panic("amount underflow")
	}
	return a - b
}

func RequirePositive(amount int64) {
	if amount <= 0 {
		panic("amount must be positive")
	}
}

func (l Ledger) Fund(amount int64) Ledger {
	RequirePositive(amount)
	l.Funded = Add(l.Funded, amount)
	l.Available = Add(l.Available, amount)
	return l
}

func (l Ledger) Reserve(amount int64) Ledger {
	RequirePositive(amount)
	l.Available = Subtract(l.Available, amount)
	l.Reserved = Add(l.Reserved, amount)
	return l
}

func (l Ledger) Approve(amount int64) Ledger {
	RequirePositive(amount)
	l.Reserved = Subtract(l.Reserved, amount)
	l.Claimable = Add(l.Claimable, amount)
	return l
}

func (l Ledger) Release(amount int64) Ledger {
	RequirePositive(amount)
	l.Reserved = Subtract(l.Reserved, amount)
	l.Available = Add(l.Available, amount)
	return l
}

func (l Ledger) RefundAvailable() Ledger {
	l.Claimable = Add(l.Claimable, l.Available)
	l.Available = 0
	return l
}

func (l Ledger) Pay(amount int64) Ledger {
	RequirePositive(amount)
	l.Claimable = Subtract(l.Claimable, amount)
	l.Paid = Add(l.Paid, amount)
	return l
}

func PeriodAt(height, start, periodBlocks int64) int64 {
	if start < 0 || height < start || periodBlocks <= 0 {
		panic("invalid period")
	}
	return (height - start) / periodBlocks
}

func CheckDeadline(height, deadline, maxHold int64) {
	if height < 0 || deadline <= height || deadline-height > maxHold {
		panic("deadline outside reservation window")
	}
}

func RequireAddress(addr address) {
	s := string(addr)
	if len(s) != 40 || !strings.HasPrefix(s, "g1") {
		panic("invalid Gno address")
	}
	hrp, data, version, err := bech32.DecodeGeneric(s)
	if err != nil || hrp != "g" || len(data) != 32 || version != bech32.Version0 {
		panic("invalid Gno address")
	}
}

func RequireDigest(digest string) {
	if len(digest) != 64 || strings.ToLower(digest) != digest {
		panic("evidence must be a lowercase SHA-256 digest")
	}
	if _, err := hex.DecodeString(digest); err != nil {
		panic("evidence must be a lowercase SHA-256 digest")
	}
}

func RequireLaneName(lane string) {
	if len(lane) == 0 || len(lane) > 32 || lane[0] < 'a' || lane[0] > 'z' {
		panic("invalid policy lane name")
	}
	if lane == RefundLane || lane == "period" || lane == "check" {
		panic("reserved policy lane name")
	}
	for i := 1; i < len(lane); i++ {
		c := lane[i]
		if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '_' && c != '-' {
			panic("invalid policy lane name")
		}
	}
}

// RequireMemo accepts a single line of up to 80 printable UTF-8 bytes.
func RequireMemo(memo string) {
	if len(memo) > 80 || !utf8.ValidString(memo) {
		panic("memo must be valid UTF-8 and at most 80 bytes")
	}
	for _, r := range memo {
		if !unicode.IsPrint(r) || strings.ContainsRune("|[]<>", r) {
			panic("memo contains a control or unsupported Markdown character")
		}
	}
}

// EvidenceCommitment binds a salted proof digest to its program and item.
func EvidenceCommitment(programID int64, lane string, itemID int64, proofDigest string) string {
	RequireDigest(proofDigest)
	payload := "shared-budget/v1\n" + strconv.FormatInt(programID, 10) + "\n" +
		lane + "\n" + strconv.FormatInt(itemID, 10) + "\n" + proofDigest + "\n"
	hash := sha256.Sum256([]byte(payload))
	return hex.EncodeToString(hash[:])
}

// ParsePolicyViewPath reads programID or programID/itemID for policy renders.
func ParsePolicyViewPath(path string) (int64, int64) {
	parts := strings.SplitN(strings.TrimPrefix(path, ":"), "/", 3)
	programID, err := strconv.ParseInt(parts[0], 10, 64)
	if err != nil || programID <= 0 {
		return 0, 0
	}
	if len(parts) == 1 {
		return programID, 0
	}
	itemID, err := strconv.ParseInt(parts[1], 10, 64)
	if len(parts) != 2 || err != nil || itemID <= 0 {
		return 0, 0
	}
	return programID, itemID
}

gnomod.toml

module = "gno.land/p/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/budget/v2"
gno = "0.9"

[addpkg]
  creator = "g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct"
  height = 1552667
  max_deposit = "30000000ugnot"

presentation.gno

package budget

import (
	"encoding/hex"
	"math/bits"
	"strconv"
	"strings"

	"gno.land/p/nt/svg/v0"
)

func FormatInt(n int64) string {
	digits := strconv.FormatInt(n, 10)
	var out strings.Builder
	if digits[0] == '-' {
		out.WriteByte('-')
		digits = digits[1:]
	}
	for i := 0; i < len(digits); i++ {
		if i > 0 && (len(digits)-i)%3 == 0 {
			out.WriteByte(',')
		}
		out.WriteByte(digits[i])
	}
	return out.String()
}

// FormatUGNOT shows the exact amount in both ugnot and GNOT.
func FormatUGNOT(amount int64) string {
	const unit int64 = 1000000
	whole := FormatInt(amount / unit)
	fraction := amount % unit
	if fraction < 0 {
		fraction = -fraction
	}
	if amount < 0 && amount > -unit {
		whole = "-" + whole
	}
	decimal := strconv.FormatInt(unit+fraction, 10)[1:]
	for len(decimal) > 2 && decimal[len(decimal)-1] == '0' {
		decimal = decimal[:len(decimal)-1]
	}
	return FormatInt(amount) + " ugnot (" + whole + "." + decimal + " GNOT)"
}

// MarkdownText escapes printable text for inline Markdown and table cells.
func MarkdownText(s string) string {
	return strings.NewReplacer(
		"\\", "\\\\", "`", "\\`", "*", "\\*", "_", "\\_", "~", "\\~", "#", "\\#",
		"[", "\\[", "]", "\\]", "<", "\\<", ">", "\\>", "|", "\\|", "&", "\\&",
		"!", "\\!", "(", "\\(", ")", "\\)",
	).Replace(s)
}

func AllocationBarSVG(ledger Ledger, reserveFloor int64) string {
	ledger.AssertConserved()
	protected := min64(ledger.Available, nonnegative(reserveFloor))
	segments := []struct {
		amount int64
		label  string
		color  string
		x      int
	}{
		{ledger.Available - protected, "Available", "#047857", 12},
		{protected, "Protected reserve floor", "#b45309", 111},
		{ledger.Reserved, "Reserved", "#2563eb", 296},
		{ledger.Claimable, "Claimable", "#6d28d9", 396},
		{ledger.Paid, "Paid", "#475569", 502},
	}
	const barWidth = 552
	canvas := svg.NewCanvas(576, 65).WithViewBox(0, 0, 576, 65)
	canvas.Append(svg.NewRectangle(0, 0, 576, 65, "#f8fafc"),
		svg.NewRectangle(12, 12, barWidth, 20, "#e2e8f0"))
	position := 0
	total := int64(0)
	for _, segment := range segments {
		total += segment.amount
		end := scaledWidth(total, ledger.Funded, barWidth)
		if end > position {
			canvas.Append(svg.NewRectangle(12+position, 12, end-position, 20, segment.color))
		}
		position = end
		canvas.Append(svg.NewRectangle(segment.x, 43, 10, 10, segment.color),
			svgLabel(segment.x+16, 52, segment.label))
	}
	return canvas.Render("Allocation across available funds, protected reserve floor, reserved funds, claims and payments")
}

func CapMeterSVG(label string, used, cap int64, colorHex string) string {
	RequireMemo(label)
	color := strings.TrimPrefix(colorHex, "#")
	if _, err := hex.DecodeString(color); err != nil || len(color) != 6 {
		color = "2563eb"
	}
	const barWidth = 412
	canvas := svg.NewCanvas(436, 56).WithViewBox(0, 0, 436, 56)
	width := scaledWidth(nonnegative(min64(used, cap)), cap, barWidth)
	canvas.Append(svg.NewRectangle(0, 0, 436, 56, "#f8fafc"),
		svgLabel(12, 20, label+" · "+FormatInt(used)+" / "+FormatInt(cap)+" ugnot"),
		svg.NewRectangle(12, 31, barWidth, 13, "#e2e8f0"))
	if width > 0 {
		canvas.Append(svg.NewRectangle(12, 31, width, 13, "#"+color))
	}
	return canvas.Render(MarkdownText(label) + " · " + FormatInt(used) + " of " + FormatInt(cap) + " ugnot used")
}

func svgLabel(x, y int, text string) *svg.Text {
	text = strings.NewReplacer("&", "&amp;", "<", "&lt;", ">", "&gt;").Replace(text)
	element := svg.NewText(x, y, text, "#0f172a")
	element.Attr.Style = "font-family:system-ui,sans-serif;font-size:13px"
	return element
}

func scaledWidth(amount, total int64, width int) int {
	if total <= 0 {
		return 0
	}
	// Use a 128-bit product so large ledgers retain exact pixel boundaries.
	hi, lo := bits.Mul64(uint64(amount), uint64(width))
	pixels, _ := bits.Div64(hi, lo, uint64(total))
	return int(pixels)
}