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

Playground

banker_coins.gno

package treasury

import (
	"chain"
	"chain/banker"
	"errors"

	"gno.land/p/aeddi/panictoerr/v0"
)

var ErrNonCanonicalBanker = errors.New("inner banker is not the canonical chain/banker.Banker")

// CoinsBanker is a Banker that sends banker.Coins.
type CoinsBanker struct {
	owner  address       // The address of this coins banker owner.
	banker banker.Banker // The underlying std banker, must be a BankerTypeRealmSend.
}

var _ Banker = (*CoinsBanker)(nil)

// ID implements Banker.
func (CoinsBanker) ID() string {
	return "Coins"
}

// Send implements Banker.
//
// rlm must be the caller's own captured cur (i.e. the cur of the
// immediate crossing-function caller). Sending with rlm = cur.Previous()
// or any other realm value is rejected: rlm.IsCurrent() asserts pointer
// identity against the topmost crossing frame. Combined with the
// rlm.Address() == cb.owner check, this restricts Send to the owning
// realm acting in its own frame.
func (cb *CoinsBanker) Send(_ int, rlm realm, p Payment) error {
	if !rlm.IsCurrent() {
		return ErrSpoofedRealm
	}
	if rlm.Address() != cb.owner {
		return ErrCurrentRealmIsNotOwner
	}
	// Check if payment is of type coinsPayment.
	payment, ok := p.(coinsPayment)
	if !ok {
		return ErrInvalidPaymentType
	}

	// Send the coins.
	return panictoerr.PanicToError(func() {
		cb.banker.SendCoins(cb.owner, payment.toAddress, payment.coins)
	})
}

// Balances implements Banker.
func (cb *CoinsBanker) Balances() []Balance {
	// Get the coins from the banker.
	coins := cb.banker.GetCoins(cb.owner)

	// Convert banker.Coins to []Balance.
	balances := make([]Balance, len(coins))
	for i := range coins {
		balances[i] = Balance{
			Denom:  coins[i].Denom,
			Amount: coins[i].Amount,
		}
	}

	return balances
}

// Address implements Banker.
func (cb *CoinsBanker) Address() string {
	return cb.owner.String()
}

// NewCoinsBankerWithOwner creates a new CoinsBanker with the given address.
//
// banker_ must be the canonical Banker produced by banker.NewBanker;
// hand-rolled Banker implementations (no-op fakes, decorators) are
// rejected via banker.IsCanonical. Without this check, a callee
// receiving a *CoinsBanker constructed from a fake banker would not
// be able to tell that Send is a no-op (no real coins move). The
// pkgAddr-vs-owner mismatch is still surfaced lazily by the inner
// banker's own SendCoins check.
func NewCoinsBankerWithOwner(owner address, banker_ banker.Banker) (*CoinsBanker, error) {
	if owner == "" {
		return nil, ErrNoOwnerProvided
	}

	if !banker.IsCanonical(banker_) {
		return nil, ErrNonCanonicalBanker
	}

	return &CoinsBanker{
		owner:  owner,
		banker: banker_,
	}, nil
}

// coinsPayment represents a payment that is issued by a CoinsBanker.
type coinsPayment struct {
	coins     chain.Coins // The coins being sent.
	toAddress address     // The recipient of the payment.
}

var _ Payment = (*coinsPayment)(nil)

// BankerID implements Payment.
func (coinsPayment) BankerID() string {
	return CoinsBanker{}.ID()
}

// String implements Payment.
func (cp coinsPayment) String() string {
	return cp.coins.String() + " to " + cp.toAddress.String()
}

// NewCoinsPayment creates a new coinsPayment.
//
// The coins are copied, so the caller cannot change the amount after the
// payment exists, and sorted and joined, so String() renders the set that will
// actually be paid. A non-positive amount is rejected here rather than by the
// bank keeper at execution, after a vote. A malformed denom is still only
// caught by the keeper.
func NewCoinsPayment(coins chain.Coins, toAddress address) Payment {
	cz := chain.Coins{}.Add(coins)

	for _, c := range cz {
		if !c.IsPositive() {
			panic("coins payment amounts must be positive, got " + c.String())
		}
	}

	return coinsPayment{
		coins:     cz,
		toAddress: toAddress,
	}
}

banker_grc20.gno

package treasury

import (
	"errors"
	"strconv"

	"gno.land/p/nt/grc20/v0"
	"gno.land/p/nt/ufmt/v0"
)

var (
	ErrNoListerProvided   = errors.New("no lister provided")
	ErrGRC20TokenNotFound = errors.New("GRC20 token not found")
)

// GRC20Banker is a Banker that sends GRC20 tokens listed using a getter
// set during initialization.
type GRC20Banker struct {
	owner  address         // The address of this GRC20 banker owner.
	lister TokenListerFunc // Allows to list tokens from methods that require it.
}

// TokenListerFunc is a function type that returns a map of GRC20 tokens.
type TokenListerFunc func() map[string]*grc20.Token

var _ Banker = (*GRC20Banker)(nil)

// ID implements Banker.
func (GRC20Banker) ID() string {
	return "GRC20"
}

// Send implements Banker.
//
// rlm must be the caller's own captured cur (i.e. the cur of the
// immediate crossing-function caller). Sending with rlm = cur.Previous()
// or any other realm value is rejected: rlm.IsCurrent() asserts pointer
// identity against the topmost crossing frame. Combined with the
// rlm.Address() == gb.owner check, this restricts Send to the owning
// realm acting in its own frame.
func (gb *GRC20Banker) Send(_ int, rlm realm, p Payment) error {
	if !rlm.IsCurrent() {
		return ErrSpoofedRealm
	}
	if rlm.Address() != gb.owner {
		return ErrCurrentRealmIsNotOwner
	}

	payment, ok := p.(grc20Payment)
	if !ok {
		return ErrInvalidPaymentType
	}

	// Get the GRC20 tokens using the lister.
	tokens := gb.lister()

	// Look for the token corresponding to the payment tokenKey.
	token, ok := tokens[payment.tokenKey]
	if !ok {
		return ufmt.Errorf("%v: %s", ErrGRC20TokenNotFound, payment.tokenKey)
	}

	// Send the token from the owner's balance.
	return token.RealmTeller(0, rlm).Transfer(0, rlm, payment.toAddress, payment.amount)
}

// Balances implements Banker.
func (gb *GRC20Banker) Balances() []Balance {
	// Get the GRC20 tokens from the lister.
	tokens := gb.lister()

	// Convert GRC20 tokens to []Balance.
	var balances []Balance
	for key, token := range tokens {
		balances = append(balances, Balance{
			Denom:  key,
			Amount: token.BalanceOf(gb.owner),
		})
	}
	return balances
}

// Address implements Banker.
func (gb *GRC20Banker) Address() string {
	return gb.owner.String()
}

// NewGRC20BankerWithOwner creates a new GRC20Banker with the given address.
func NewGRC20BankerWithOwner(owner address, lister TokenListerFunc) (*GRC20Banker, error) {
	if owner == "" {
		return nil, ErrNoOwnerProvided
	}

	if lister == nil {
		return nil, ErrNoListerProvided
	}

	return &GRC20Banker{
		owner:  owner,
		lister: lister,
	}, nil
}

// grc20Payment represents a payment that is issued by a GRC20Banker.
type grc20Payment struct {
	tokenKey  string  // The key associated with the GRC20 token.
	amount    int64   // The amount of token to send.
	toAddress address // The recipient of the payment.
}

var _ Payment = (*grc20Payment)(nil)

// BankerID implements Payment.
func (grc20Payment) BankerID() string {
	return GRC20Banker{}.ID()
}

// String implements Payment.
func (gp grc20Payment) String() string {
	amount := strconv.Itoa(int(gp.amount))
	return amount + gp.tokenKey + " to " + gp.toAddress.String()
}

// NewGRC20Payment creates a new grc20Payment.
func NewGRC20Payment(tokenKey string, amount int64, toAddress address) Payment {
	return grc20Payment{
		tokenKey:  tokenKey,
		amount:    amount,
		toAddress: toAddress,
	}
}

doc.gno

// v0 - Unaudited: This is an initial version that has not yet been formally audited.
// A fully audited version will be published as a subsequent release.
// Use in production at your own risk.
//
// Package treasury provides treasury management for handling coin and GRC20
// token transfers in Gno realms.
package treasury

gnomod.toml

module = "gno.land/p/nt/treasury/v0"
gno = "0.9"

[addpkg]
  creator = "g1edq4dugw0sgat4zxcw9xardvuydqf6cgleuc8p"

render.gno

package treasury

import (
	"net/url"
	"strconv"
	"strings"

	"gno.land/p/moul/md/v0"
	"gno.land/p/moul/mdtable/v0"
	"gno.land/p/nt/bptree/pager/v0"
	"gno.land/p/nt/mux/v0"
	"gno.land/p/nt/ufmt/v0"
)

const (
	DefaultHistoryPreviewSize = 5  // Number of payments in the history preview.
	DefaultHistoryPageSize    = 20 // Number of payments per page in the history.
)

// Render renders content based on the given path.
func (t *Treasury) Render(path string) string {
	return t.router.Render(path)
}

// RenderLanding renders the landing page of the treasury.
func (t *Treasury) RenderLanding(path string) string {
	var out string

	// Render each banker.
	for _, bankerID := range t.ListBankerIDs() {
		out += t.RenderBanker(bankerID, path)
	}

	return out
}

// RenderBanker renders the details of a specific banker.
func (t *Treasury) RenderBanker(bankerID string, path string) string {
	// Get the banker associated to this ID.
	br := t.bankers.Get(bankerID)
	if br == nil {
		return md.Paragraph("Banker not found: " + md.EscapeText(bankerID))
	}
	banker := br.(*bankerRecord).banker

	// Render banker title.
	out := md.H2(md.EscapeText(bankerID) + " Banker")

	// Render address section.
	out += md.H3("Address")
	out += md.Paragraph(banker.Address())

	// Render balances section.
	out += md.H3("Balances")
	balances := banker.Balances()
	if len(balances) == 0 {
		out += md.Paragraph("No balances found.")
	} else {
		table := mdtable.Table{Headers: []string{"Denom", "Amount"}}
		for _, balance := range balances {
			table.Append([]string{balance.Denom, strconv.FormatInt(balance.Amount, 10)})
		}
		out += table.String()
	}

	historySize := DefaultHistoryPreviewSize

	// Check if the query parameter "history_size" is present and parse it.
	if req, err := url.Parse(path); err == nil && req.Query() != nil {
		size, err := strconv.Atoi(req.Query().Get("history_size"))
		if err == nil && size >= 0 {
			historySize = size
		}
	}

	// Skip history rendering if historySize is 0.
	if historySize == 0 {
		return out
	}

	// Render history section.
	out += md.H3("History")
	history, _ := t.History(bankerID, 1, historySize)
	if len(history) == 0 {
		out += md.Paragraph("No payments sent yet.")
	} else {
		if len(history) == 1 {
			out += md.Paragraph("Last payment:")
		} else {
			count := strconv.FormatInt(int64(len(history)), 10)
			out += md.Paragraph("Last " + count + " payments:")
		}

		// Render each payment in the history.
		for _, payment := range history {
			out += md.BulletItem(payment.String())
		}
		out += "\n"

		// Build the "See full history" link from the owning realm's
		// path captured at New() time. Skipped if no path was supplied
		// (e.g. /p/ filetests that don't exercise rendering).
		if from := strings.IndexRune(t.realmPath, '/'); from >= 0 {
			out += md.Link(
				"See full history",
				ufmt.Sprintf("%s:%s/history", t.realmPath[from:], bankerID),
			)
		}
	}

	return out
}

// RenderBankerHistory renders the payment history of a specific banker.
func (t *Treasury) RenderBankerHistory(bankerID string, path string) string {
	// Get the banker record corresponding to this ID if it exists.
	br := t.bankers.Get(bankerID)
	if br == nil {
		return md.Paragraph("Banker not found: " + md.EscapeText(bankerID))
	}
	history := br.(*bankerRecord).history

	// Render banker history title.
	out := md.H2(md.EscapeText(bankerID) + " Banker History")

	// Get the current page of tokens based on the request path.
	p := pager.NewPager(history.Tree(), DefaultHistoryPageSize, true)
	page, err := p.GetPageByPath(path)
	if err != nil {
		return md.Paragraph("Error retrieving page: " + md.EscapeText(err.Error()))
	}

	// Render full history section.
	if history.Len() == 0 {
		out += md.Paragraph("No payments sent yet.")
	} else {
		if history.Len() == 1 {
			out += md.Paragraph("1 payment:")
		} else {
			count := strconv.FormatInt(int64(history.Len()), 10)
			out += md.Paragraph(count + " payments (sorted by latest, descending):")
		}
		for _, item := range page.Items {
			out += md.BulletItem(item.Value.(Payment).String())
		}
	}
	out += "\n"

	// Add the page picker.
	out += md.Paragraph(page.Picker(path))

	return out
}

// initRenderRouter registers the routes for rendering the treasury pages.
func (t *Treasury) initRenderRouter() {
	t.router = mux.NewRouter()

	// Landing page.
	t.router.HandleFunc("", func(res *mux.ResponseWriter, req *mux.Request) {
		res.Write(t.RenderLanding(req.RawPath))
	})

	// Banker details.
	t.router.HandleFunc("{banker}", func(res *mux.ResponseWriter, req *mux.Request) {
		res.Write(t.RenderBanker(req.GetVar("banker"), req.RawPath))
	})

	// Banker full history.
	t.router.HandleFunc("{banker}/history", func(res *mux.ResponseWriter, req *mux.Request) {
		res.Write(t.RenderBankerHistory(req.GetVar("banker"), req.RawPath))
	})
}

treasury.gno

package treasury

import (
	"errors"

	"gno.land/p/nt/bptree/pager/v0"
	"gno.land/p/nt/bptree/v0"
	"gno.land/p/nt/ufmt/v0"
)

var (
	ErrNoBankerProvided       = errors.New("no banker provided")
	ErrDuplicateBanker        = errors.New("duplicate banker")
	ErrBankerNotFound         = errors.New("banker not found")
	ErrSendPaymentFailed      = errors.New("failed to send payment")
	ErrNonCanonicalBankerImpl = errors.New("non-canonical Banker impl: only *CoinsBanker / *GRC20Banker accepted")
)

// New creates a new Treasury instance with the given bankers.
//
// pkgPath should be the package path of the owning realm. It is
// captured on the Treasury and used to build the "See full history"
// link in RenderBanker. Pass `cur.PkgPath()` from the owning realm's
// init (or another live-cur context). Passing "" disables the link.
//
// The path is stored as plain data — no IsCurrent guard inside this
// /p/ constructor. The caller is the trust boundary; it must derive
// the value from a real `cur realm` rather than accept it from
// untrusted input. The captured path is consumed only for render
// output (Class-2 designation-forgery shape, accepted as
// display-only — see docs/resources/gno-security.md).
//
// Each banker must be one of treasury's canonical concrete impls
// (*CoinsBanker, *GRC20Banker) per IsCanonicalBanker. Foreign-realm impls
// (including embedded wrappers around canonical types) are rejected: a
// malicious Send impl would receive a capability token via its rlm
// parameter when treasury.Send dispatches into it.
//
// The allowlist validates type only, not captured state. Treasury operators
// must construct their own bankers; never accept a pre-built *Banker value
// from an external realm.
func New(bankers []Banker, pkgPath string) (*Treasury, error) {
	if len(bankers) == 0 {
		return nil, ErrNoBankerProvided
	}

	// Canonical-impl allowlist: reject foreign types (embedding-based
	// bypasses fail here because type assertions are nominal).
	for _, b := range bankers {
		if !IsCanonicalBanker(b) {
			return nil, ErrNonCanonicalBankerImpl
		}
	}

	// Create a new Treasury instance.
	treasury := &Treasury{bankers: bptree.NewBPTree32(), realmPath: pkgPath}

	// Register the bankers.
	for _, banker := range bankers {
		if treasury.bankers.Has(banker.ID()) {
			return nil, ufmt.Errorf("%v: %s", ErrDuplicateBanker, banker.ID())
		}

		treasury.bankers.Set(
			banker.ID(),
			&bankerRecord{banker: banker},
		)
	}

	// Register the Render routes.
	treasury.initRenderRouter()

	return treasury, nil
}

// Send sends a payment using the corresponding banker. rlm is threaded
// to the banker's Send for IsCurrent + owner validation.
func (t *Treasury) Send(_ int, rlm realm, p Payment) error {
	// Get the banker record corresponding to this Payment.
	br := t.bankers.Get(p.BankerID())
	if br == nil {
		return ufmt.Errorf("%v: %s", ErrBankerNotFound, p.BankerID())
	}
	record := br.(*bankerRecord)

	// Send the payment using the corresponding banker.
	if err := record.banker.Send(0, rlm, p); err != nil {
		return ufmt.Errorf("%v: %s", ErrSendPaymentFailed, err)
	}

	// Add the payment to the history of the banker.
	record.history.Append(p)

	return nil
}

// History returns the payment history sent by the banker with the given ID.
// Payments are paginated, with the most recent payments first.
func (t *Treasury) History(
	bankerID string,
	pageNumber int,
	pageSize int,
) ([]Payment, error) {
	// Get the banker record corresponding to this ID.
	br := t.bankers.Get(bankerID)
	if br == nil {
		return nil, ufmt.Errorf("%v: %s", ErrBankerNotFound, bankerID)
	}
	history := br.(*bankerRecord).history

	// Get the page of payments from the history.
	p := pager.NewPager(history.Tree(), pageSize, true)
	page := p.GetPage(pageNumber)

	// Convert the items in the page to a slice of Payments.
	payments := make([]Payment, len(page.Items))
	for i := range page.Items {
		payments[i] = page.Items[i].Value.(Payment)
	}

	return payments, nil
}

// Balances returns the balances of the banker with the given ID.
func (t *Treasury) Balances(bankerID string) ([]Balance, error) {
	// Get the banker record corresponding to this ID.
	br := t.bankers.Get(bankerID)
	if br == nil {
		return nil, ufmt.Errorf("%v: %s", ErrBankerNotFound, bankerID)
	}

	// Get the balances from the banker.
	return br.(*bankerRecord).banker.Balances(), nil
}

// Address returns the address of the banker with the given ID.
func (t *Treasury) Address(bankerID string) (string, error) {
	// Get the banker record corresponding to this ID.
	br := t.bankers.Get(bankerID)
	if br == nil {
		return "", ufmt.Errorf("%v: %s", ErrBankerNotFound, bankerID)
	}

	// Get the address from the banker.
	return br.(*bankerRecord).banker.Address(), nil
}

// HasBanker checks if a banker with the given ID is registered.
func (t *Treasury) HasBanker(bankerID string) bool {
	return t.bankers.Has(bankerID)
}

// ListBankerIDs returns a list of all registered banker IDs.
func (t *Treasury) ListBankerIDs() []string {
	var bankerIDs []string

	t.bankers.Iterate("", "", func(bankerID string, _ any) bool {
		bankerIDs = append(bankerIDs, bankerID)
		return false
	})

	return bankerIDs
}

types.gno

package treasury

import (
	"errors"

	"gno.land/p/nt/bptree/list/v0"
	"gno.land/p/nt/bptree/v0"
	"gno.land/p/nt/mux/v0"
)

// Treasury is the main structure that holds all bankers and their payment
// history. It also provides a router for rendering the treasury pages.
type Treasury struct {
	bankers   *bptree.BPTree // string -> *bankerRecord
	router    *mux.Router
	realmPath string // owning realm's PkgPath, captured at New() (used for render links)
}

// bankerRecord holds a Banker and its payment history.
type bankerRecord struct {
	banker  Banker
	history list.List // List of Payment.
}

// Banker is an interface that allows for banking operations.
//
// SECURITY: Send takes (int, realm, Payment), so handing a Banker value to
// untrusted code yields a capability token to whatever Send impl that code
// dispatches into. The set of canonical impls is closed (*CoinsBanker,
// *GRC20Banker); any public function that accepts a Banker as a parameter
// from external callers MUST verify it via IsCanonicalBanker and reject
// otherwise. treasury.New enforces this for its own intake; future
// Banker-accepting APIs must do the same. An unexported-marker "seal" does
// NOT defend against this — see
// p/test/seal/filetests/z_seal_iface_embedding_filetest.gno.
//
// Note that IsCanonicalBanker validates dynamic TYPE only, not captured
// STATE: a canonical *CoinsBanker constructed via NewCoinsBankerWithOwner
// with a hostile owner argument passes the allowlist but its read methods
// (Balances, Address) report data tied to that hostile address. Treasury
// operators must construct their own bankers and NEVER accept pre-built
// *Banker values from external realms.
type Banker interface {
	ID() string                     // Get the ID of the banker.
	Send(int, realm, Payment) error // Send a payment to a recipient.
	Balances() []Balance            // Get the balances of the banker.
	Address() string                // Get the address of the banker to receive payments.
}

// IsCanonicalBanker reports whether b is one of treasury's canonical
// concrete Banker impls. Use this at any public entry point in /p/ or /r/
// that accepts a Banker from an external caller before invoking its methods.
//
// Foreign types — including embedding-based wrappers like
// `type Evil struct { *CoinsBanker }` — are rejected because type assertions
// are nominal: *Evil is not *CoinsBanker, regardless of method promotion.
//
// To add a new canonical type: extend the switch below AND add a regression
// test (under filetests/ in this package) that an embedded-impl bypass is
// rejected.
//
// Mirrors the precedent of chain/banker.IsCanonical and
// p/jaekwon/allowancesender's canonical-impl check.
func IsCanonicalBanker(b Banker) bool {
	switch b.(type) {
	case *CoinsBanker, *GRC20Banker:
		return true
	default:
		return false
	}
}

// Payment is an interface that allows getting details about a payment.
type Payment interface {
	BankerID() string // Get the ID of the banker that can process this payment.
	String() string   // Get a string representation of the payment.
}

// IsCanonicalPayment reports whether p is one of treasury's canonical concrete
// Payment impls. Use this at any public entry point that accepts a Payment
// from an external caller and shows it to a human before it is processed.
//
// The immutability the constructors provide is a property of these two types,
// not of the interface: a foreign impl's String() says whatever its realm
// likes, and no Banker will process it, because Banker.Send type-asserts and
// so fails only at execution — after a vote has been spent on it.
//
// Only the value types are listed, deliberately. Banker.Send asserting
// p.(coinsPayment) is what makes this check meaningful, so accepting
// *coinsPayment would pass a payment that still fails at execution.
//
// To add a new canonical type: extend the switch below AND add a regression
// test (under filetests/ in this package) that a foreign impl is rejected.
//
// Mirrors IsCanonicalBanker above.
func IsCanonicalPayment(p Payment) bool {
	switch p.(type) {
	case coinsPayment, grc20Payment:
		return true
	default:
		return false
	}
}

// Balance represents the balance of an asset held by a Banker.
type Balance struct {
	Denom  string // The denomination of the asset
	Amount int64  // The amount of the asset
}

// Common Banker errors.
var (
	ErrCurrentRealmIsNotOwner = errors.New("current realm is not the owner of the banker")
	ErrNoOwnerProvided        = errors.New("no owner provided")
	ErrInvalidPaymentType     = errors.New("invalid payment type")
	ErrSpoofedRealm           = errors.New("rlm does not match the current crossing frame")
)