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

gnomod.toml

module = "gno.land/r/nt/grc20reg/v0"
gno = "0.9"

[addpkg]
  creator = "g1edq4dugw0sgat4zxcw9xardvuydqf6cgleuc8p"

grc20reg.gno

package grc20reg

import (
	"chain"
	"strings"

	"gno.land/p/moul/md/v0"
	"gno.land/p/nt/avl/rotree/v0"
	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/fqname/v0"
	"gno.land/p/nt/grc20/v0"
	"gno.land/p/nt/ufmt/v0"
)

var registry = avl.NewTree() // rlmPath.symbol -> *Token

// Construction lives in grc20.NewToken — it takes rlm realm last
// and binds origRealm from rlm.PkgPath() under an IsCurrent assertion.
// The registry key is the canonical fqname rlmPath.symbol (one token per
// realm+symbol), independent of Token.ID()'s trailing sequence id, so
// callers can look a token up from the (realm, symbol) pair they already
// know:
//
//	Token, ledger := grc20.NewToken(name, symbol, decimals, id, cur)
//	key := grc20reg.Register(cross(cur), Token, "")

// Register records token under its rlmPath.symbol key and returns that key.
// Token.ID() carries a trailing sequence id (rlmPath.symbol.<id>) that keeps
// token identities/events unique, but the registry deliberately keys by
// rlmPath.symbol so lookups don't need to know the id, and so a realm cannot
// register two tokens under the same symbol (overwrite/alias guard).
func Register(cur realm, token *grc20.Token, slug string) string {
	if token == nil {
		panic("grc20reg: nil token")
	}
	if slug != "" {
		validateSlug(slug)
	}
	rlmPath := cur.Previous().PkgPath()
	key := fqname.Construct(rlmPath, token.GetSymbol())
	// Token.ID() == key + "." + <id>; verify the token originates from the
	// registering realm and symbol.
	if !strings.HasPrefix(token.ID(), key+".") {
		panic("grc20reg: token must be registered from its own realm")
	}
	if registry.Has(key) {
		panic("grc20reg: token already registered")
	}
	registry.Set(key, token)
	chain.Emit(
		registerEvent,
		"token_path", key,
		"pkgpath", rlmPath,
		"slug", slug,
		"symbol", token.GetSymbol(),
	)
	return key
}

func Get(key string) *grc20.Token {
	token := registry.Get(key)
	if token == nil {
		return nil
	}
	return token.(*grc20.Token)
}

func MustGet(key string) *grc20.Token {
	token := Get(key)
	if token == nil {
		panic("unknown token: " + key)
	}
	return token
}

// Write wrappers: a registered token can be moved through the registry without
// importing the token's realm, which is the point of a registry. What makes
// that safe is the calling convention, so it is worth stating once here rather
// than three times below.
//
// These are NOT crossing functions. `_ int, rlm realm` is the only shape that
// gives a non-crossing realm parameter — a realm parameter in first position
// must be named `cur`, which makes the function crossing — and the distinction
// is load-bearing, not stylistic:
//
//   - Crossing (`func Transfer(cur realm, …)`) mints a fresh `cur` for THIS
//     realm. RealmTeller would then bind the actor to the registry's own
//     address and the registry would spend its own balance. Useless at best.
//   - Non-crossing (`func Transfer(_ int, rlm realm, …)`) declaring-borrows to
//     the registry without a realm-context change, so `rlm` is still the
//     caller's own live token and the actor is the caller.
//
// The safety comes from RealmTeller's IsCurrent() assertion. The actor is
// rlm.Address() on a token that must be the live crossing frame, so it is
// provably the immediate caller: a stale or foreign token is refused with
// ErrSpoofedRealm. Debiting anyone else would mean holding their live `cur`,
// which means executing inside their frame — authority they handed over
// deliberately, and the same trust model RealmTeller already carries.
//
// This is deliberately not grc20.CallerTeller. "Act as whoever called me" is
// the confused deputy: the debited account ends up chosen by whoever the hub
// can be induced to serve, and an intermediate realm frame silently changes who
// pays. CallerTeller is confined to the token's own realm for that reason and
// is not reachable from a *Token. "Act as the realm that called me, verified
// current" has nothing to induce — the caller cannot name a victim, only
// itself.
//
// Realm-only by construction: MsgCall cannot build a realm argument
// (convertArgToGno rejects non-primitive parameter types), so a signing user
// cannot reach these at all and there is no in-band case to guard against.
// Users move their own tokens through the token realm's own entry points
// (wugnot.Transfer, foo20.Transfer, …).

// Transfer moves `amount` out of the CALLING REALM's own balance.
//
// Call it non-crossing, forwarding your own `cur`:
//
//	grc20reg.Transfer(0, cur, "gno.land/r/demo/defi/foo20.FOO", to, 100)
func Transfer(_ int, rlm realm, tokenKey string, to address, amount int64) {
	checkErr(MustGet(tokenKey).RealmTeller(0, rlm).Transfer(0, rlm, to, amount))
}

// Approve sets an allowance owned by the CALLING REALM, letting `spender` draw
// on the calling realm's balance. It does not touch the signing user's
// allowances.
func Approve(_ int, rlm realm, tokenKey string, spender address, amount int64) {
	checkErr(MustGet(tokenKey).RealmTeller(0, rlm).Approve(0, rlm, spender, amount))
}

// TransferFrom spends an allowance with the CALLING REALM as the spender.
//
// Note the allowance direction this implies: `from` must have approved the
// calling realm, not the signing user. That is the supported way for a realm to
// move a user's funds — the user grants the realm an allowance, and the realm
// draws on it as itself, so every debit is one the owner authorized against
// that specific realm.
func TransferFrom(_ int, rlm realm, tokenKey string, from, to address, amount int64) {
	checkErr(MustGet(tokenKey).RealmTeller(0, rlm).TransferFrom(0, rlm, from, to, amount))
}

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}

func Render(path string) string {
	switch {
	case path == "": // home
		// TODO: add pagination
		s := ""
		count := 0
		registry.Iterate("", "", func(key string, tokenI any) bool {
			count++
			token := tokenI.(*grc20.Token)
			rlmPath, tokenID := fqname.Parse(key)
			rlmLink := fqname.RenderLink(rlmPath, tokenID)
			infoLink := "/r/nt/grc20reg/v0:" + key
			s += "- " + md.Bold(md.EscapeText(token.GetName())) + " - " + rlmLink + " - " + md.Link("info", infoLink) + "\n"
			return false
		})
		if count == 0 {
			return "No registered token."
		}
		return s
	default: // specific token
		key := path
		token := MustGet(key)
		rlmPath, tokenID := fqname.Parse(key)
		rlmLink := fqname.RenderLink(rlmPath, tokenID)
		s := ufmt.Sprintf("# %s\n", md.EscapeText(token.GetName()))
		s += "- symbol: " + md.Bold(md.EscapeText(token.GetSymbol())) + "\n"
		s += ufmt.Sprintf("- realm: %s\n", rlmLink)
		s += ufmt.Sprintf("- decimals: %d\n", token.GetDecimals())
		s += ufmt.Sprintf("- total supply: %d\n", token.TotalSupply())
		return s
	}
}

const (
	registerEvent = "register"
	maxSlugLen    = 128
)

func GetRegistry() *rotree.ReadOnlyTree {
	return rotree.Wrap(registry, nil)
}

// validateSlug panics if the slug is too long or contains non-alphanumeric characters.
// Only letters, digits, dashes, and underscores are allowed.
func validateSlug(slug string) {
	if len(slug) > maxSlugLen {
		panic("grc20reg: slug too long")
	}
	for _, c := range slug {
		if !isAlphanumeric(c) && c != '_' && c != '-' {
			panic("grc20reg: invalid slug character: " + string(c))
		}
	}
}

func isAlphanumeric(c rune) bool {
	return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
}

grc20reg_test.gno

package grc20reg

import (
	"chain"
	"strings"
	"testing"

	"gno.land/p/nt/grc20/v0"
	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
	"gno.land/p/nt/urequire/v0"
)

func TestRegistry(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/demo/foo"))
	token, ledger := grc20.NewToken("TestToken", "TST", 4, 0, cur)
	ledger.Mint(cur.Address(), 1234567)
	// register
	key := Register(cross(cur), token, "mySlug")
	regToken := Get(key)
	urequire.True(t, regToken != nil, "expected to find a token") // fixme: use urequire.NotNil
	urequire.Equal(t, regToken.GetSymbol(), "TST")

	expected := `- **TestToken** - [gno.land/r/demo/foo](/r/demo/foo).TST - [info](/r/nt/grc20reg/v0:gno.land/r/demo/foo.TST)
`
	got := Render("")
	urequire.True(t, strings.Contains(got, expected))
	// 404
	invalidToken := Get("0xdeadbeef")
	urequire.True(t, invalidToken == nil)

	got = Render("")
	urequire.True(t, strings.Contains(got, expected))

	expected = `# TestToken
- symbol: **TST**
- realm: [gno.land/r/demo/foo](/r/demo/foo).TST
- decimals: 4
- total supply: 1234567
`
	got = Render(key)
	urequire.Equal(t, expected, got)

	// The registry keys by rlmPath.symbol, so a second token with the same
	// symbol in the same realm is rejected even though its Token.ID() differs
	// (distinct trailing sequence id). See TestRegisterRejectsOverwrite.
	second, _ := grc20.NewToken("Second", "TST", 4, 1, cur)
	urequire.NotEqual(t, token.ID(), second.ID()) // ids are decoupled from symbol
	urequire.AbortsContains(t, cur, "token already registered", func() {
		Register(cross(cur), second, "")
	})
}

// TestRegistryLookupGrantsNoSpendAuthority pins the property that replaced the
// former Transfer/Approve/TransferFrom wrappers: a registry lookup yields a
// *Token, and a *Token alone carries no authority to debit anybody. The
// frame-relative teller is reachable only from the ledger, which never leaves
// the token's own realm, so this realm cannot act on behalf of its caller —
// that shape was the confused deputy.
//
// The supported route for a realm that must move a user's funds is the one
// exercised below: the user grants an allowance, and the realm spends it as
// itself through a RealmTeller, which is eagerly bound to its own address.
func TestRegistryLookupGrantsNoSpendAuthority(cur realm, t *testing.T) {
	const (
		tokenPath    = "gno.land/r/demo/token"
		consumerPath = "gno.land/r/demo/grc20reg_consumer"
	)
	alice := testutils.TestAddress("alice")
	bob := testutils.TestAddress("bob")
	consumer := chain.PackageAddress(consumerPath)

	testing.SetRealm(testing.NewCodeRealm(tokenPath))
	token, ledger := grc20.NewToken("TestToken", "TST", 4, 0, cur)
	urequire.NoError(t, ledger.Mint(alice, 1_000))
	tokenKey := Register(cross(cur), token, "")
	uassert.Equal(t, "TestToken", MustGet(tokenKey).GetName())
	uassert.Equal(t, int64(1_000), MustGet(tokenKey).BalanceOf(alice))
	uassert.Equal(t, int64(0), MustGet(tokenKey).Allowance(alice, consumer))

	// alice approves the consumer realm on the token. On chain she does this
	// through the token realm's own entry point; the ledger stands in for it.
	urequire.NoError(t, ledger.ImpersonateTeller(alice).Approve(0, cur, consumer, 300))
	uassert.Equal(t, int64(300), MustGet(tokenKey).Allowance(alice, consumer))

	// The consumer spends that allowance as ITSELF, over a token it found in
	// the registry and does not own. The actor is fixed at construction, so it
	// cannot be redirected by whoever calls in.
	testing.SetRealm(testing.NewCodeRealm(consumerPath))
	spender := MustGet(tokenKey).RealmTeller(0, cur)
	urequire.NoError(t, spender.TransferFrom(0, cur, alice, bob, 200))
	uassert.Equal(t, int64(800), MustGet(tokenKey).BalanceOf(alice))
	uassert.Equal(t, int64(200), MustGet(tokenKey).BalanceOf(bob))
	uassert.Equal(t, int64(100), MustGet(tokenKey).Allowance(alice, consumer))

	// Beyond the allowance it stops: the balance is not reachable directly.
	uassert.ErrorContains(t,
		spender.TransferFrom(0, cur, alice, bob, 101),
		"insufficient allowance")
	uassert.Equal(t, int64(800), MustGet(tokenKey).BalanceOf(alice))
	uassert.Equal(t, int64(200), MustGet(tokenKey).BalanceOf(bob))
}

// TestRegistryConsumerCannotRedirectItsActor is the negative half of the
// property above: a realm holding a registered token pays out of its own
// balance, not the signing user's. The actor is bound at construction, so the
// transaction's origin caller has no bearing on who is debited — which is what
// made the frame-relative teller in a foreign realm a phishing primitive.
func TestRegistryConsumerCannotRedirectItsActor(cur realm, t *testing.T) {
	const (
		tokenPath    = "gno.land/r/demo/token_actor_binding"
		consumerPath = "gno.land/r/demo/grc20reg_actor_consumer"
	)
	alice := testutils.TestAddress("alice")
	bob := testutils.TestAddress("bob")
	consumer := chain.PackageAddress(consumerPath)

	testing.SetRealm(testing.NewCodeRealm(tokenPath))
	token, ledger := grc20.NewToken("ActorBinding", "ACTB", 4, 0, cur)
	urequire.NoError(t, ledger.Mint(alice, 1_000))
	urequire.NoError(t, ledger.Mint(consumer, 500))
	tokenKey := Register(cross(cur), token, "")

	// alice signs the transaction, and holds a balance the consumer would love
	// to spend. The consumer pays out of its own instead.
	testing.SetOriginCaller(alice)
	testing.SetRealm(testing.NewCodeRealm(consumerPath))
	urequire.NoError(t, MustGet(tokenKey).RealmTeller(0, cur).Transfer(0, cur, bob, 100))
	uassert.Equal(t, int64(1_000), MustGet(tokenKey).BalanceOf(alice))
	uassert.Equal(t, int64(400), MustGet(tokenKey).BalanceOf(consumer))
	uassert.Equal(t, int64(100), MustGet(tokenKey).BalanceOf(bob))
}

func TestRegisterRejectsOverwrite(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/demo/grc20reg_overwrite"))
	token, ledger := grc20.NewToken("Bar", "BAR", 4, 0, cur)
	ledger.Mint(cur.Address(), 11)
	key := Register(cross(cur), token, "")

	urequire.Equal(t, "BAR", Get(key).GetSymbol())
	urequire.Equal(t, int64(11), Get(key).BalanceOf(cur.Address()))

	replacement, _ := grc20.NewToken("Replacement", "BAR", 6, 0, cur)
	urequire.AbortsContains(t, cur, "token already registered", func() {
		Register(cross(cur), replacement, "")
	})
}

func TestRegisterRejectsAliasedTokenPaths(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/demo/grc20reg_alias"))
	token, _ := grc20.NewToken("Aliased Token", "ALIAS", 4, 0, cur)
	Register(cross(cur), token, "first")

	urequire.AbortsContains(t, cur, "token already registered", func() {
		Register(cross(cur), token, "second")
	})
}

func TestRegisterRejectsTokenFromDifferentRealm(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/demo/grc20reg_id_source"))
	token, _ := grc20.NewToken("Mismatch Token", "MISMATCH", 4, 0, cur)

	testing.SetRealm(testing.NewCodeRealm("gno.land/r/demo/grc20reg_id_target"))
	urequire.AbortsContains(t, cur, "token must be registered from its own realm", func() {
		Register(cross(cur), token, "")
	})
}

func TestValidateSlug(cur realm, t *testing.T) {
	// Valid slugs — should not panic
	valid := []string{"mytoken", "my-token", "my_token", "Token123", "a", "A-B_c", strings.Repeat("a", maxSlugLen)}
	for _, slug := range valid {
		validateSlug(slug) // no panic = pass
	}
}

func TestValidateSlugPanicsOnTooLong(cur realm, t *testing.T) {
	defer func() { recover() }()
	validateSlug(strings.Repeat("a", maxSlugLen+1))
	t.Errorf("should have panicked")
}

func TestValidateSlugPanicsOnSpace(cur realm, t *testing.T) {
	defer func() { recover() }()
	validateSlug("has space")
	t.Errorf("should have panicked")
}

func TestValidateSlugPanicsOnDot(cur realm, t *testing.T) {
	defer func() { recover() }()
	validateSlug("has.dot")
	t.Errorf("should have panicked")
}

func TestValidateSlugPanicsOnSlash(cur realm, t *testing.T) {
	defer func() { recover() }()
	validateSlug("has/slash")
	t.Errorf("should have panicked")
}

func TestValidateSlugPanicsOnBrackets(cur realm, t *testing.T) {
	defer func() { recover() }()
	validateSlug("[brackets]")
	t.Errorf("should have panicked")
}

func TestValidateSlugPanicsOnParens(cur realm, t *testing.T) {
	defer func() { recover() }()
	validateSlug("(parens)")
	t.Errorf("should have panicked")
}

func TestValidateSlugPanicsOnInjection(cur realm, t *testing.T) {
	defer func() { recover() }()
	validateSlug(`) [Claim](https://evil.com`)
	t.Errorf("should have panicked")
}

func TestRegisterRejectsNilToken(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/demo/grc20reg_nil"))
	urequire.AbortsContains(t, cur, "nil token", func() {
		Register(cross(cur), nil, "")
	})
}

// TestWrappersBindActorToCallingRealm pins the property that makes the write
// wrappers safe: they are non-crossing, so `rlm` reaches RealmTeller as the
// caller's own live token and the debit lands on the caller. A crossing wrapper
// would mint a fresh `cur` for grc20reg and spend the registry's balance
// instead, which is why the convention is not a stylistic choice.
//
// Both the consumer and the registry hold a balance, so whichever one is
// debited is observable rather than inferred.
func TestWrappersBindActorToCallingRealm(cur realm, t *testing.T) {
	const (
		tokenPath    = "gno.land/r/demo/token_wrapper_actor"
		consumerPath = "gno.land/r/demo/grc20reg_wrapper_consumer"
	)
	bob := testutils.TestAddress("bob")
	consumer := chain.PackageAddress(consumerPath)
	registry := chain.PackageAddress("gno.land/r/nt/grc20reg/v0")

	testing.SetRealm(testing.NewCodeRealm(tokenPath))
	token, ledger := grc20.NewToken("WrapperActor", "WRPA", 4, 0, cur)
	urequire.NoError(t, ledger.Mint(consumer, 1_000))
	urequire.NoError(t, ledger.Mint(registry, 1_000))
	tokenKey := Register(cross(cur), token, "")

	testing.SetRealm(testing.NewCodeRealm(consumerPath))
	Transfer(0, cur, tokenKey, bob, 100)

	uassert.Equal(t, int64(900), MustGet(tokenKey).BalanceOf(consumer))
	uassert.Equal(t, int64(1_000), MustGet(tokenKey).BalanceOf(registry))
	uassert.Equal(t, int64(100), MustGet(tokenKey).BalanceOf(bob))
}

// TestWrapperActorIgnoresSigningUser is the negative half: the signing user has
// a balance the calling realm would like to spend, and does not lose it. The
// actor comes from rlm.Address(), so the transaction's origin has no say in who
// pays — a hub cannot be induced to debit its caller's caller.
func TestWrapperActorIgnoresSigningUser(cur realm, t *testing.T) {
	const (
		tokenPath    = "gno.land/r/demo/token_wrapper_origin"
		consumerPath = "gno.land/r/demo/grc20reg_wrapper_origin_consumer"
	)
	alice := testutils.TestAddress("alice")
	bob := testutils.TestAddress("bob")
	consumer := chain.PackageAddress(consumerPath)

	testing.SetRealm(testing.NewCodeRealm(tokenPath))
	token, ledger := grc20.NewToken("WrapperOrigin", "WRPO", 4, 0, cur)
	urequire.NoError(t, ledger.Mint(alice, 1_000))
	urequire.NoError(t, ledger.Mint(consumer, 500))
	tokenKey := Register(cross(cur), token, "")

	testing.SetOriginCaller(alice)
	testing.SetRealm(testing.NewCodeRealm(consumerPath))
	Transfer(0, cur, tokenKey, bob, 100)

	uassert.Equal(t, int64(1_000), MustGet(tokenKey).BalanceOf(alice))
	uassert.Equal(t, int64(400), MustGet(tokenKey).BalanceOf(consumer))
}

// TestTransferFromSpendsAllowanceGrantedToCallingRealm records the semantic
// shift that comes with binding the actor to the caller: the owner must have
// approved the CALLING REALM, not the signing user. An allowance granted to
// anyone else does not authorize the wrapper.
func TestTransferFromSpendsAllowanceGrantedToCallingRealm(cur realm, t *testing.T) {
	const (
		tokenPath    = "gno.land/r/demo/token_wrapper_allowance"
		consumerPath = "gno.land/r/demo/grc20reg_wrapper_allowance_consumer"
	)
	alice := testutils.TestAddress("alice")
	bob := testutils.TestAddress("bob")
	consumer := chain.PackageAddress(consumerPath)

	testing.SetRealm(testing.NewCodeRealm(tokenPath))
	token, ledger := grc20.NewToken("WrapperAllowance", "WRPL", 4, 0, cur)
	urequire.NoError(t, ledger.Mint(alice, 1_000))
	tokenKey := Register(cross(cur), token, "")

	// No allowance yet: the wrapper cannot touch alice's balance.
	testing.SetRealm(testing.NewCodeRealm(consumerPath))
	uassert.PanicsContains(t, cur, "insufficient allowance", func() {
		TransferFrom(0, cur, tokenKey, alice, bob, 100)
	})
	uassert.Equal(t, int64(1_000), MustGet(tokenKey).BalanceOf(alice))

	// alice approves the consuming realm itself, and only then does it work.
	urequire.NoError(t, ledger.Approve(alice, consumer, 100))

	testing.SetRealm(testing.NewCodeRealm(consumerPath))
	TransferFrom(0, cur, tokenKey, alice, bob, 100)
	uassert.Equal(t, int64(900), MustGet(tokenKey).BalanceOf(alice))
	uassert.Equal(t, int64(100), MustGet(tokenKey).BalanceOf(bob))
}