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"
GRC20Prefix = "grc20:"
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
Available int64
MaxAllowed int64
Shortfall int64
BindingConstraint string
ItemRoom int64
PeriodRoom int64
PoolRoom int64
}
// EvaluateSpend reports the raw available balance and the room under each
// limit. Ties favor the item cap, then the period cap, then the pool.
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,
Available: available,
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 lane == RefundLane || lane == "period" || lane == "check" {
panic("reserved policy lane name")
}
if !validKey(lane) {
panic("invalid policy lane name")
}
}
// RequireAsset accepts a bank denomination or a GRC20 registry key.
func RequireAsset(asset string) {
if key, ok := strings.CutPrefix(asset, GRC20Prefix); ok {
if !validKey(key) {
panic("invalid GRC20 token key")
}
return
}
// Match the Gno bank grammar and the 256-byte realm path plus base denom limit.
if len(asset) < 3 || len(asset) > 274 ||
((asset[0] < 'a' || asset[0] > 'z') && asset[0] != '/') {
panic("invalid native denomination")
}
for i := 1; i < len(asset); i++ {
c := asset[i]
if (c < 'a' || c > 'z') && (c < '0' || c > '9') && !strings.ContainsRune("_.:/-", rune(c)) {
panic("invalid native denomination")
}
}
}
func validKey(key string) bool {
if len(key) == 0 || len(key) > 32 || key[0] < 'a' || key[0] > 'z' {
return false
}
for i := 1; i < len(key); i++ {
c := key[i]
if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '_' && c != '-' {
return false
}
}
return true
}
// 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
}
// ParsePolicyLanePath accepts programID, programID/lane, and
// programID/lane/itemID. The legacy programID/itemID route leaves lane empty.
func ParsePolicyLanePath(path string) (int64, string, int64) {
parts := strings.SplitN(strings.TrimPrefix(path, ":"), "/", 4)
if len(parts) > 3 {
return 0, "", 0
}
if len(parts) == 1 || (len(parts) == 2 && !validKey(parts[1])) {
programID, itemID := ParsePolicyViewPath(path)
return programID, "", itemID
}
programID, err := strconv.ParseInt(parts[0], 10, 64)
lane := parts[1]
if err != nil || programID <= 0 || !validKey(lane) {
return 0, "", 0
}
if len(parts) == 2 {
return programID, lane, 0
}
itemID, err := strconv.ParseInt(parts[2], 10, 64)
if err != nil || itemID <= 0 {
return 0, "", 0
}
return programID, lane, itemID
}
// PolicyLaneKey identifies a lane in a policy realm's configuration tree.
func PolicyLaneKey(programID int64, lane string) string {
return strconv.FormatInt(programID, 10) + "/" + lane
}
gnomod.toml
module = "gno.land/p/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/budget/v3" gno = "0.9" [addpkg] creator = "g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct" height = 1562601 max_deposit = "15000000ugnot"
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)"
}
// FormatAsset formats an amount in base units using the asset's precision.
func FormatAsset(amount int64, asset string, decimals int) string {
return formatQuantity(amount, decimals) + " " + asset
}
func formatQuantity(amount int64, decimals int) string {
if decimals < 0 || decimals > 18 {
panic("asset decimals must be 0 to 18")
}
if decimals == 0 {
return FormatInt(amount)
}
unit := int64(1)
for i := 0; i < decimals; i++ {
unit *= 10
}
whole := FormatInt(amount / unit)
fraction := amount % unit
if fraction == 0 {
return whole
}
if fraction < 0 {
fraction = -fraction
if amount > -unit {
whole = "-" + whole
}
}
digits := strconv.FormatInt(unit+fraction, 10)[1:]
return whole + "." + strings.TrimRight(digits, "0")
}
// MarkdownText escapes printable text for inline Markdown and table cells.
func MarkdownText(s string) string {
return strings.NewReplacer(
"\\", "\\\\", "`", "\\`", "*", "\\*", "_", "\\_", "~", "\\~", "#", "\\#",
"[", "\\[", "]", "\\]", "<", "\\<", ">", "\\>", "|", "\\|", "&", "\\&",
"!", "\\!", "(", "\\(", ")", "\\)",
).Replace(s)
}
func PolicyLaneURL(path string, programID int64, lane string) string {
return strings.TrimPrefix(path, "gno.land") + ":" + strconv.FormatInt(programID, 10) + "/" + lane
}
func PolicyLaneLinks(path string, programID int64, lanes []string) string {
var links strings.Builder
for _, lane := range lanes {
links.WriteString("- [" + MarkdownText(lane) + "](" + PolicyLaneURL(path, programID, lane) + ")\n")
}
return links.String()
}
func AllocationBarSVG(ledger Ledger, reserveFloor int64, asset string) 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 of " + MarkdownText(asset) +
" across available funds, protected reserve floor, reserved funds, claims and payments")
}
func CapMeterSVG(label string, used, cap int64, colorHex, asset string, decimals int) string {
RequireMemo(label)
color := strings.TrimPrefix(colorHex, "#")
if _, err := hex.DecodeString(color); err != nil || len(color) != 6 {
color = "2563eb"
}
usedText, capText := formatQuantity(used, decimals), formatQuantity(cap, decimals)
title := label + " · " + usedText + " / " + capText
// Long realm denoms remain in the accessible label and the surrounding page.
if len(asset) <= 24 {
title += " " + asset
}
canvasWidth := 436
if textWidth := len(title)*8 + 24; textWidth > canvasWidth {
canvasWidth = textWidth
}
barWidth := canvasWidth - 24
canvas := svg.NewCanvas(canvasWidth, 56).WithViewBox(0, 0, canvasWidth, 56)
width := scaledWidth(nonnegative(min64(used, cap)), cap, barWidth)
canvas.Append(svg.NewRectangle(0, 0, canvasWidth, 56, "#f8fafc"),
svgLabel(12, 20, title),
svg.NewRectangle(12, 31, barWidth, 13, "#e2e8f0"))
if width > 0 {
canvas.Append(svg.NewRectangle(12, 31, width, 13, "#"+color))
}
return canvas.Render(MarkdownText(label) + " · " + usedText + " of " + capText + " " + MarkdownText(asset) + " used")
}
func svgLabel(x, y int, text string) *svg.Text {
text = strings.NewReplacer("&", "&", "<", "<", ">", ">").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)
}