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/p/nt/grc721/v0"
gno = "0.9"

[addpkg]
  creator = "g1edq4dugw0sgat4zxcw9xardvuydqf6cgleuc8p"

tellers.gno

package grc721

import (
	"chain"
)

// CallerTeller resolves the acting account at each write as rlm.Previous() —
// the realm that crossed into the realm holding the teller.
//
// SECURITY: this accessor hangs off *PrivateLedger, not *Token, and that is
// load-bearing. A frame-relative teller acts as whoever crossed into its
// holder, so it is only meaningful inside the token's own realm, where the
// wrappers act for a caller who knowingly invoked the collection. Anywhere
// else it is a confused deputy: a realm a user merely calls could move that
// user's tokens. The *Token pointer is published — exported vars, the
// collection facade, grc721reg — while the ledger is not, since NewToken hands
// it to the creating realm and nowhere else. So a foreign realm cannot mint
// one.
//
// Construction privacy alone is not enough: a realm may legally build a teller
// and then export the VALUE. The write methods therefore also verify that the
// invoking realm is the token's own (see guardHome), which leaves a leaked
// teller inert everywhere but home.
func (led *PrivateLedger) CallerTeller() Teller {
	if led == nil {
		panic("Ledger cannot be nil")
	}

	return &fnTeller{
		accountFn: func(_ int, rlm realm) address {
			return rlm.Previous().Address()
		},
		homeGuard: true,
		Token:     led.token,
	}
}

// Write methods return ErrReadonly.
func (tok *Token) ReadonlyTeller() Teller {
	if tok == nil {
		panic("Token cannot be nil")
	}

	return &fnTeller{
		accountFn: nil,
		Token:     tok,
	}
}

// Permanently acts as the calling realm (verified via IsCurrent).
func (tok *Token) RealmTeller(_ int, rlm realm) Teller {
	if tok == nil {
		panic("Token cannot be nil")
	}

	if !rlm.IsCurrent() {
		panic(ErrSpoofedRealm)
	}

	caller := rlm.Address()

	return &fnTeller{
		accountFn: func(_ int, _ realm) address {
			return caller
		},
		Token: tok,
	}
}

// Like RealmTeller but acts as a sub-account derived from slug.
func (tok *Token) RealmSubTeller(_ int, rlm realm, slug string) Teller {
	if tok == nil {
		panic("Token cannot be nil")
	}

	if !rlm.IsCurrent() {
		panic(ErrSpoofedRealm)
	}

	account := accountSlugAddr(rlm.Address(), slug)

	return &fnTeller{
		accountFn: func(_ int, _ realm) address {
			return account
		},
		Token: tok,
	}
}

// Admin-grade: issuer-only (holds the PrivateLedger). Panics on invalid addr to close the empty-sentinel hole.
func (led *PrivateLedger) ImpersonateTeller(addr address) Teller {
	if led == nil {
		panic("Ledger cannot be nil")
	}

	if !addr.IsValid() {
		panic(ErrInvalidAddress)
	}

	return &fnTeller{
		accountFn: func(_ int, _ realm) address {
			return addr
		},
		Token: led.token,
	}
}

// guardHome confines a frame-relative teller to the token's own realm.
// Construction privacy stops a foreign realm from minting one; this stops a
// minted one from travelling, which is what happens when a realm legally builds
// a teller and then exports the value.
//
// The check is on the invoking realm's path alone — deliberately NOT on whether
// the resolved actor is an end user. Keying on the actor only blocks the case
// where the debited party is the signing user, and leaves two doors open: a
// realm can be charged by a realm it calls, and TransferFrom resolves the
// *spender* from the frame, so a realm reached from an honest hub spends that
// hub's approvals against any owner who granted one. Both are the same defect
// as the original one level up — frame-relative resolution means whoever you
// call can act as you — and neither is reachable once the teller only works at
// home.
//
// The host is compared after stripping any "#subpath" synthesized by realm.Sub,
// so the token's own sub-realms are not falsely rejected.
//
// A foreign realm that needs to move a user's tokens uses the ordinary route:
// the owner Approves it, and it spends as itself through RealmTeller, which is
// eagerly bound to its own address and approval-gated.
//
// The leading int keeps this a plain method.
func (ft *fnTeller) guardHome(_ int, rlm realm) error {
	if !ft.homeGuard {
		return nil
	}

	host, _, _ := chain.SplitPkgSubPath(rlm.PkgPath())
	if host != ft.Token.origRealm {
		return ErrForeignCallerTeller
	}

	return nil
}

func (ft *fnTeller) Approve(_ int, rlm realm, to address, tid TokenID) error {
	if ft.accountFn == nil {
		return ErrReadonly
	}

	if !rlm.IsCurrent() {
		return ErrSpoofedRealm
	}

	if err := ft.guardHome(0, rlm); err != nil {
		return err
	}

	caller := ft.accountFn(0, rlm)

	return ft.Token.ledger.Approve(caller, to, tid)
}

func (ft *fnTeller) SetApprovalForAll(_ int, rlm realm, operator address, approved bool) error {
	if ft.accountFn == nil {
		return ErrReadonly
	}

	if !rlm.IsCurrent() {
		return ErrSpoofedRealm
	}

	if err := ft.guardHome(0, rlm); err != nil {
		return err
	}

	caller := ft.accountFn(0, rlm)

	return ft.Token.ledger.SetApprovalForAll(caller, operator, approved)
}

func (ft *fnTeller) TransferFrom(_ int, rlm realm, from, to address, tid TokenID) error {
	if ft.accountFn == nil {
		return ErrReadonly
	}

	if !rlm.IsCurrent() {
		return ErrSpoofedRealm
	}

	if err := ft.guardHome(0, rlm); err != nil {
		return err
	}

	spender := ft.accountFn(0, rlm)

	return ft.Token.ledger.TransferFrom(spender, from, to, tid)
}

func accountSlugAddr(addr address, slug string) address {
	if slug == "" {
		return addr
	}

	key := addr.String() + "/" + slug

	return chain.PackageAddress(key)
}

tellers_test.gno

package grc721

import (
	"testing"

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

type evilTeller struct{ Teller }

func TestIsCanonicalTeller(cur realm, t *testing.T) {
	tok, led := newTestToken("Foo", "FOO", 0, cur)

	var realmTeller Teller
	func(cur realm) {
		realmTeller = tok.RealmTeller(0, cur)
	}(cross(cur))

	tests := []struct {
		name string
		te   Teller
		want bool
	}{
		{"CallerTeller is canonical", led.CallerTeller(), true},
		{"ReadonlyTeller is canonical", tok.ReadonlyTeller(), true},
		{"RealmTeller is canonical", realmTeller, true},
		{"ImpersonateTeller is canonical", led.ImpersonateTeller(alice), true},
		{"embedding wrapper is rejected", &evilTeller{led.CallerTeller()}, false},
	}

	for _, tc := range tests {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			uassert.Equal(t, tc.want, IsCanonicalTeller(tc.te))
		})
	}
}

func TestTellerNilGuards(cur realm, t *testing.T) {
	var nilTok *Token
	var nilLed *PrivateLedger

	tests := []struct {
		name string
		msg  string
		fn   func()
	}{
		{"CallerTeller on nil ledger panics", "Ledger cannot be nil", func() {
			nilLed.CallerTeller()
		}},
		{"ReadonlyTeller on nil token panics", "Token cannot be nil", func() {
			nilTok.ReadonlyTeller()
		}},
		{"RealmTeller on nil token panics", "Token cannot be nil", func() {
			nilTok.RealmTeller(0, cur)
		}},
		{"RealmSubTeller on nil token panics", "Token cannot be nil", func() {
			nilTok.RealmSubTeller(0, cur, "slug")
		}},
		{"ImpersonateTeller on nil ledger panics", "Ledger cannot be nil", func() {
			nilLed.ImpersonateTeller(alice)
		}},
	}

	for _, tc := range tests {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			uassert.PanicsWithMessage(t, cur, tc.msg, tc.fn)
		})
	}
}

func TestReadonlyTeller(cur realm, t *testing.T) {
	tok, led := newTestToken("Foo", "FOO", 0, cur)
	urequire.NoError(t, led.Mint(alice, "1"))
	ro := tok.ReadonlyTeller()

	tests := []struct {
		name string
		op   string
	}{
		{"Approve rejected with ErrReadonly", "approve"},
		{"TransferFrom rejected with ErrReadonly", "transfer"},
		{"SetApprovalForAll rejected with ErrReadonly", "setall"},
	}

	for _, tc := range tests {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			var err error
			testing.SetRealm(testing.NewUserRealm(alice))
			func(cur realm) {
				switch tc.op {
				case "approve":
					err = ro.Approve(0, cur, bob, "1")
				case "transfer":
					err = ro.TransferFrom(0, cur, alice, bob, "1")
				case "setall":
					err = ro.SetApprovalForAll(0, cur, bob, true)
				}
			}(cross(cur))
			uassert.ErrorIs(t, err, ErrReadonly)
		})
	}
}

func TestCallerTellerFlow(cur realm, t *testing.T) {
	tok, led := newTestToken("Foo", "FOO", 0, cur)
	urequire.NoError(t, led.Mint(alice, "1"))
	urequire.NoError(t, led.Mint(alice, "2"))

	teller := led.CallerTeller()

	testing.SetRealm(testing.NewUserRealm(alice))
	func(cur realm) {
		urequire.NoError(t, teller.Approve(0, cur, bob, "1"))
	}(cross(cur))

	testing.SetRealm(testing.NewUserRealm(alice))
	func(cur realm) {
		urequire.NoError(t, teller.SetApprovalForAll(0, cur, bob, true))
	}(cross(cur))
	uassert.True(t, tok.IsApprovedForAll(alice, bob))

	testing.SetRealm(testing.NewUserRealm(bob))
	func(cur realm) {
		urequire.NoError(t, teller.TransferFrom(0, cur, alice, carl, "1"))
	}(cross(cur))

	owner, err := tok.OwnerOf("1")
	urequire.NoError(t, err)
	uassert.Equal(t, carl, owner)

	testing.SetRealm(testing.NewUserRealm(bob))
	func(cur realm) {
		uassert.ErrorIs(t, teller.TransferFrom(0, cur, carl, bob, "1"), ErrCallerIsNotOwnerOrApproved)
	}(cross(cur))
}

func TestCallerTellerSpoofedRealm(cur realm, t *testing.T) {
	_, led := newTestToken("Foo", "FOO", 0, cur)
	urequire.NoError(t, led.Mint(alice, "1"))
	teller := led.CallerTeller()

	// Stale outer cur while a fresh frame is current → ErrSpoofedRealm.
	tests := []struct {
		name string
		op   string
	}{
		{"Approve rejects spoofed realm", "approve"},
		{"TransferFrom rejects spoofed realm", "transfer"},
		{"SetApprovalForAll rejects spoofed realm", "setall"},
	}

	for _, tc := range tests {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			var err error
			stale := cur
			func(cur realm) {
				switch tc.op {
				case "approve":
					err = teller.Approve(0, stale, bob, "1")
				case "transfer":
					err = teller.TransferFrom(0, stale, alice, bob, "1")
				case "setall":
					err = teller.SetApprovalForAll(0, stale, bob, true)
				}
			}(cross(cur))
			uassert.ErrorIs(t, err, ErrSpoofedRealm)
		})
	}
}

func TestRealmTellerFlow(cur realm, t *testing.T) {
	tok, led := newTestToken("Foo", "FOO", 0, cur)

	var teller Teller
	var realmAddr address
	func(cur realm) {
		teller = tok.RealmTeller(0, cur)
		realmAddr = cur.Address()
	}(cross(cur))

	urequire.NoError(t, led.Mint(realmAddr, "1"))

	testing.SetRealm(testing.NewUserRealm(alice))
	func(cur realm) {
		urequire.NoError(t, teller.TransferFrom(0, cur, realmAddr, bob, "1"))
	}(cross(cur))

	owner, err := tok.OwnerOf("1")
	urequire.NoError(t, err)
	uassert.Equal(t, bob, owner)
}

func TestRealmSubTellerFlow(cur realm, t *testing.T) {
	tok, led := newTestToken("Foo", "FOO", 0, cur)

	tests := []struct {
		name           string
		slug           string
		tid            TokenID
		wantsRealmAddr bool
	}{
		{"empty slug derives the realm address itself", "", "10", true},
		{"non-empty slug derives a sub-account", "vault", "11", false},
	}

	for _, tc := range tests {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			var teller Teller
			var realmAddr, account address
			func(cur realm) {
				teller = tok.RealmSubTeller(0, cur, tc.slug)
				realmAddr = cur.Address()
				account = accountSlugAddr(cur.Address(), tc.slug)
			}(cross(cur))

			if tc.wantsRealmAddr {
				uassert.Equal(t, realmAddr, account)
			} else {
				uassert.True(t, realmAddr != account, "sub-account must differ from realm address")
			}

			urequire.NoError(t, led.Mint(account, tc.tid))
			testing.SetRealm(testing.NewUserRealm(alice))
			func(cur realm) {
				urequire.NoError(t, teller.TransferFrom(0, cur, account, bob, tc.tid))
			}(cross(cur))

			owner, err := tok.OwnerOf(tc.tid)
			urequire.NoError(t, err)
			uassert.Equal(t, bob, owner)
		})
	}
}

func TestRealmTellerSpoofedRealm(cur realm, t *testing.T) {
	tok, _ := newTestToken("Foo", "FOO", 0, cur)

	tests := []struct {
		name string
		fn   func()
	}{
		{"RealmTeller rejects spoofed realm", func() {
			stale := cur
			func(cur realm) {
				tok.RealmTeller(0, stale)
			}(cross(cur))
		}},
		{"RealmSubTeller rejects spoofed realm", func() {
			stale := cur
			func(cur realm) {
				tok.RealmSubTeller(0, stale, "vault")
			}(cross(cur))
		}},
	}

	for _, tc := range tests {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			urequire.AbortsContains(t, cur, "rlm does not match the current crossing frame", tc.fn)
		})
	}
}

func TestImpersonateTeller(cur realm, t *testing.T) {
	tok, led := newTestToken("Foo", "FOO", 0, cur)
	urequire.NoError(t, led.Mint(alice, "1"))

	teller := led.ImpersonateTeller(alice)
	testing.SetRealm(testing.NewUserRealm(bob))
	func(cur realm) {
		urequire.NoError(t, teller.TransferFrom(0, cur, alice, bob, "1"))
	}(cross(cur))

	owner, err := tok.OwnerOf("1")
	urequire.NoError(t, err)
	uassert.Equal(t, bob, owner)
}

func TestImpersonateTellerRejectsInvalidAddress(cur realm, t *testing.T) {
	_, led := newTestToken("Foo", "FOO", 0, cur)
	uassert.PanicsWithMessage(t, cur, "invalid address", func() {
		led.ImpersonateTeller(zeroAddress)
	})
}

token.gno

package grc721

import (
	"chain"
	"math/overflow"
	"strconv"

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

// NewToken creates a core token and its ledger.
// rlm must be the caller's own captured cur (IsCurrent); its PkgPath becomes the unforgeable origRealm.
//
// Every successful call emits a NewToken event carrying the resulting Token.ID().
// Because Token's fields are unexported, NewToken is the only way a Token can come
// into existence, so this event makes token creation fully observable: an indexer
// that sees the same Token.ID() announced twice knows the realm built two
// independent ledgers behind one identifier, and that every later
// Mint/Burn/Transfer/Approval carrying that id is ambiguous. Such a realm is
// emitting untrustworthy events and should be flagged or ignored wholesale.
func NewToken(name, symbol string, id seqid.ID, rlm realm) (*Token, *PrivateLedger) {
	if !rlm.IsCurrent() {
		panic(ErrSpoofedRealm)
	}

	pkgPath := rlm.PkgPath()
	if pkgPath == "" {
		panic(ErrNotRealm)
	}

	if !validName(name) {
		panic(ErrInvalidName)
	}

	if !validSymbol(symbol) {
		panic(ErrInvalidSymbol)
	}

	// origRealm is the host path, with any "#subpath" synthesized by realm.Sub
	// stripped. guardHome strips the invoking path the same way, so a token
	// created from a sub frame is not locked out of its own host realm, and a
	// host's sub-realms are not falsely rejected. Token.ID() keeps the raw
	// pkgPath, so identities and the NewToken event are unaffected.
	origRealm, _, _ := chain.SplitPkgSubPath(pkgPath)

	ledger := &PrivateLedger{}
	token := &Token{
		id:        pkgPath + "." + symbol + "." + id.String(),
		name:      name,
		symbol:    symbol,
		ledger:    ledger,
		origRealm: origRealm,
	}
	ledger.token = token

	chain.Emit(
		NewTokenEvent,
		"token", token.id,
		"name", name,
		"symbol", symbol,
	)

	return token, ledger
}

func validName(name string) bool {
	if name == "" || len(name) > MaxNameLen {
		return false
	}

	for _, c := range name {
		if c < 0x20 || c == 0x7f {
			return false
		}
	}

	return true
}

func validSymbol(s string) bool {
	if s == "" || len(s) > MaxSymbolLen {
		return false
	}

	for _, c := range s {
		if !isAlnum(c) && c != '_' && c != '-' {
			return false
		}
	}

	return true
}

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

func (tok *Token) GetName() string { return tok.name }

func (tok *Token) GetSymbol() string { return tok.symbol }

func (tok *Token) ID() string { return tok.id }

func (tok *Token) TotalSupply() int64 { return tok.ledger.totalSupply }

func (tok *Token) KnownAccounts() int { return tok.ledger.balances.Size() }

// EIP-721: balanceOf throws for queries about the zero address,
// since NFTs assigned to it are considered invalid.
func (tok *Token) BalanceOf(addr address) (int64, error) {
	if !addr.IsValid() {
		return 0, ErrInvalidAddress
	}

	return tok.ledger.balanceOf(addr), nil
}

func (tok *Token) OwnerOf(tid TokenID) (address, error) { return tok.ledger.ownerOf(tid) }

// EIP-721: getApproved throws for a token that is not a valid NFT, so a missing
// token is ErrInvalidTokenId and a live but unapproved one is ErrTokenIdNotApproved.
func (tok *Token) GetApproved(tid TokenID) (address, error) {
	if !tok.ledger.exists(tid) {
		return zeroAddress, ErrInvalidTokenId
	}

	addr := tok.ledger.tokenApprovals.Get(tid.String())
	if addr == nil {
		return zeroAddress, ErrTokenIdNotApproved
	}

	return addr.(address), nil
}

func (tok *Token) IsApprovedForAll(owner, operator address) bool {
	return tok.ledger.isApprovedForAll(owner, operator)
}

func (tok *Token) RenderHome() string {
	str := ""
	str += ufmt.Sprintf("# %s ($%s)\n\n", tok.name, tok.symbol)
	str += ufmt.Sprintf("* **Total supply**: %d\n", tok.ledger.totalSupply)
	str += ufmt.Sprintf("* **Known accounts**: %d\n", tok.KnownAccounts())

	return str
}

// RegisterExtension attaches an issuer-supplied hook set. Issuer-only (holds the
// PrivateLedger), which keeps the surface from being attacker-attachable — but the
// attachment is still a privilege: per the Extension doc, an attached hook can veto
// transfers (a panic aborts the transaction before the Transfer event is emitted) and
// adds gas to every movement.
// One extension per kind; a second registration of an attached kind panics.
func (led *PrivateLedger) RegisterExtension(ext Extension) {
	if ext == nil {
		panic("grc721: nil extension")
	}

	kind := ext.ExtensionKind()
	for _, e := range led.extensions {
		if e.ExtensionKind() == kind {
			panic("grc721: extension kind already registered: " + kind)
		}
	}

	led.extensions = append(led.extensions, ext)
}

func (led *PrivateLedger) ReadToken() *Token { return led.token }

func (led *PrivateLedger) Mint(to address, tid TokenID) error {
	if !to.IsValid() {
		return ErrInvalidAddress
	}

	if tid == "" {
		return ErrInvalidTokenId
	}

	if led.exists(tid) {
		return ErrTokenIdAlreadyExists
	}

	led.balances.Set(to.String(), overflow.Add64p(led.balanceOf(to), 1))
	led.owners.Set(tid.String(), to)
	led.totalSupply = overflow.Add64p(led.totalSupply, 1)

	for _, ext := range led.extensions {
		ext.OnMint(to, tid)
	}

	// Mint emits Transfer from the empty address (EIP-721); indexers reconstruct ownership from Transfer alone.
	chain.Emit(
		TransferEvent,
		"token", led.token.id,
		"from", "",
		"to", to.String(),
		"tokenId", tid.String(),
	)

	return nil
}

// Fans OnBurn out to every extension so per-token state cannot resurface if tid is re-minted.
func (led *PrivateLedger) Burn(tid TokenID) error {
	owner, err := led.ownerOf(tid)
	if err != nil {
		return err
	}

	tidStr := tid.String()
	led.tokenApprovals.Remove(tidStr)
	led.setBalance(owner, overflow.Sub64p(led.balanceOf(owner), 1))
	led.owners.Remove(tidStr)
	led.totalSupply = overflow.Sub64p(led.totalSupply, 1)

	for _, ext := range led.extensions {
		ext.OnBurn(tid)
	}

	// Burn emits Transfer to the empty address (EIP-721).
	chain.Emit(
		TransferEvent,
		"token", led.token.id,
		"from", owner.String(),
		"to", "",
		"tokenId", tidStr,
	)

	return nil
}

// spender must own or be approved for tid; callers derive it from a trusted per-frame identity.
func (led *PrivateLedger) TransferFrom(spender, from, to address, tid TokenID) error {
	if !led.isApprovedOrOwner(spender, tid) {
		return ErrCallerIsNotOwnerOrApproved
	}

	return led.transfer(from, to, tid)
}

// caller must own tid or be an approved operator of the owner.
// EIP-721: approving the zero address clears (revokes) any single-token approval.
func (led *PrivateLedger) Approve(caller, to address, tid TokenID) error {
	revoke := to == zeroAddress
	if !revoke && !to.IsValid() {
		return ErrInvalidAddress
	}

	owner, err := led.ownerOf(tid)
	if err != nil {
		return err
	}

	if owner == to {
		return ErrApprovalToCurrentOwner
	}

	if caller != owner && !led.isApprovedForAll(owner, caller) {
		return ErrCallerIsNotOwnerOrApproved
	}

	if revoke {
		led.tokenApprovals.Remove(tid.String())
	} else {
		led.tokenApprovals.Set(tid.String(), to)
	}

	chain.Emit(
		ApprovalEvent,
		"token", led.token.id,
		"owner", owner.String(),
		"to", to.String(), // empty for a revoke
		"tokenId", tid.String(),
	)

	return nil
}

func (led *PrivateLedger) SetApprovalForAll(owner, operator address, approved bool) error {
	if !owner.IsValid() || !operator.IsValid() {
		return ErrInvalidAddress
	}

	if owner == operator {
		return ErrApprovalToCurrentOwner
	}

	key := operatorKey(owner, operator)
	if approved {
		led.operatorApprovals.Set(key, approved)
	} else {
		led.operatorApprovals.Remove(key)
	}

	chain.Emit(
		ApprovalForAllEvent,
		"token", led.token.id,
		"owner", owner.String(),
		"to", operator.String(),
		"approved", strconv.FormatBool(approved),
	)

	return nil
}

func (led *PrivateLedger) transfer(from, to address, tid TokenID) error {
	if !from.IsValid() || !to.IsValid() {
		return ErrInvalidAddress
	}

	if from == to {
		return ErrCannotTransferToSelf
	}

	owner, err := led.ownerOf(tid)
	if err != nil {
		return err
	}

	if owner != from {
		return ErrTransferFromIncorrectOwner
	}

	tidStr := tid.String()
	led.tokenApprovals.Remove(tidStr)
	led.setBalance(from, overflow.Sub64p(led.balanceOf(from), 1))
	led.setBalance(to, overflow.Add64p(led.balanceOf(to), 1))
	led.owners.Set(tidStr, to)

	for _, ext := range led.extensions {
		ext.OnTransfer(from, to, tid)
	}

	chain.Emit(
		TransferEvent,
		"token", led.token.id,
		"from", from.String(),
		"to", to.String(),
		"tokenId", tidStr,
	)

	return nil
}

func (led *PrivateLedger) ownerOf(tid TokenID) (address, error) {
	owner := led.owners.Get(tid.String())
	if owner == nil {
		return zeroAddress, ErrInvalidTokenId
	}

	return owner.(address), nil
}

func (led *PrivateLedger) balanceOf(addr address) int64 {
	balance := led.balances.Get(addr.String())
	if balance == nil {
		return 0
	}

	return balance.(int64)
}

func (led *PrivateLedger) setBalance(addr address, balance int64) {
	if balance == 0 {
		led.balances.Remove(addr.String())

		return
	}

	led.balances.Set(addr.String(), balance)
}

func (led *PrivateLedger) isApprovedForAll(owner, operator address) bool {
	approved := led.operatorApprovals.Get(operatorKey(owner, operator))
	if approved == nil {
		return false
	}

	return approved.(bool)
}

func (led *PrivateLedger) isApprovedOrOwner(addr address, tid TokenID) bool {
	owner := led.owners.Get(tid.String())
	if owner == nil {
		return false
	}

	ownerAddr := owner.(address)
	if addr == ownerAddr || led.isApprovedForAll(ownerAddr, addr) {
		return true
	}

	approved := led.tokenApprovals.Get(tid.String())

	return approved != nil && approved.(address) == addr
}

func (led *PrivateLedger) exists(tid TokenID) bool {
	return led.owners.Has(tid.String())
}

func operatorKey(owner, operator address) string {
	return owner.String() + ":" + operator.String()
}

token_test.gno

package grc721

import (
	"strings"
	"testing"

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

func mustBalanceOf(t *testing.T, tok *Token, addr address) int64 {
	balance, err := tok.BalanceOf(addr)
	urequire.NoError(t, err)
	return balance
}

// newTestToken builds via same-realm cross (NewToken requires rlm.IsCurrent()).
func newTestToken(name, symbol string, id seqid.ID, rlm realm) (tok *Token, led *PrivateLedger) {
	func(cur realm) {
		tok, led = NewToken(name, symbol, id, cur)
	}(cross(rlm))
	return
}

type mockExtension struct {
	mints, transfers, burns int
	lastMintTo              address
	lastTransferFrom        address
	lastTransferTo          address
	lastBurn                TokenID
}

func (m *mockExtension) ExtensionKind() string { return "mock" }

func (m *mockExtension) OnMint(to address, tid TokenID) {
	m.mints++
	m.lastMintTo = to
}

func (m *mockExtension) OnTransfer(from, to address, tid TokenID) {
	m.transfers++
	m.lastTransferFrom = from
	m.lastTransferTo = to
}

func (m *mockExtension) OnBurn(tid TokenID) {
	m.burns++
	m.lastBurn = tid
}

// Value type holding a slice: uncomparable, so `==` on two of them is a runtime fault.
type journalExtension struct{ seen []TokenID }

func (e journalExtension) ExtensionKind() string                    { return "journal" }
func (e journalExtension) OnMint(to address, tid TokenID)           {}
func (e journalExtension) OnTransfer(from, to address, tid TokenID) {}
func (e journalExtension) OnBurn(tid TokenID)                       {}

var (
	alice = testutils.TestAddress("alice")
	bob   = testutils.TestAddress("bob")
	carl  = testutils.TestAddress("carl")
)

func TestNewToken(cur realm, t *testing.T) {
	tok, led := newTestToken("Foo NFT", "FOO", 0, cur)
	urequire.False(t, tok == nil, "token should not be nil")
	urequire.False(t, led == nil, "ledger should not be nil")

	uassert.Equal(t, "Foo NFT", tok.GetName())
	uassert.Equal(t, "FOO", tok.GetSymbol())
	uassert.Equal(t, int64(0), tok.TotalSupply())
	uassert.Equal(t, 0, tok.KnownAccounts())
	uassert.True(t, strings.HasSuffix(tok.ID(), ".FOO."+seqid.ID(0).String()), "ID must end with .symbol.id")
	uassert.True(t, strings.HasPrefix(tok.ID(), "gno.land/"), "ID must begin with the origin realm path")
	uassert.Equal(t, tok.ID(), led.ReadToken().ID())
}

func TestNewTokenDistinctIDs(cur realm, t *testing.T) {
	first, _ := newTestToken("Same", "DUP", 1, cur)
	second, _ := newTestToken("Same", "DUP", 2, cur)
	uassert.True(t, first.ID() != second.ID(), "distinct seqid must yield distinct IDs")

	a, _ := newTestToken("Same", "DUP", 3, cur)
	b, _ := newTestToken("Same", "DUP", 3, cur)
	uassert.Equal(t, a.ID(), b.ID())
}

func TestNewTokenValidation(cur realm, t *testing.T) {
	longName := strings.Repeat("a", MaxNameLen+1)
	maxName := strings.Repeat("a", MaxNameLen)
	longSymbol := strings.Repeat("A", MaxSymbolLen+1)

	tests := []struct {
		name       string
		tokenName  string
		symbol     string
		wantAbort  bool
		wantSubstr string
	}{
		{"valid name and symbol succeeds", "Foo", "FOO", false, ""},
		{"symbol with full slug charset succeeds", "Foo", "aZ9_-", false, ""},
		{"name at max length succeeds", maxName, "FOO", false, ""},
		{"empty name returns ErrInvalidName", "", "FOO", true, "invalid token name"},
		{"name over max length returns ErrInvalidName", longName, "FOO", true, "invalid token name"},
		{"name with low control char returns ErrInvalidName", "Foo\x01", "FOO", true, "invalid token name"},
		{"name with DEL control char returns ErrInvalidName", "Foo\x7f", "FOO", true, "invalid token name"},
		{"empty symbol returns ErrInvalidSymbol", "Foo", "", true, "invalid token symbol"},
		{"symbol over max length returns ErrInvalidSymbol", "Foo", longSymbol, true, "invalid token symbol"},
		{"symbol with space returns ErrInvalidSymbol", "Foo", "has space", true, "invalid token symbol"},
		{"symbol with dot returns ErrInvalidSymbol", "Foo", "FO.O", true, "invalid token symbol"},
		{"symbol with slash returns ErrInvalidSymbol", "Foo", "FO/O", true, "invalid token symbol"},
	}

	for _, tc := range tests {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			if tc.wantAbort {
				urequire.AbortsContains(t, cur, tc.wantSubstr, func() {
					newTestToken(tc.tokenName, tc.symbol, 0, cur)
				})
				return
			}
			tok, _ := newTestToken(tc.tokenName, tc.symbol, 0, cur)
			uassert.Equal(t, tc.tokenName, tok.GetName())
			uassert.Equal(t, tc.symbol, tok.GetSymbol())
		})
	}
}

func TestNewTokenRejectsSpoofedRealm(cur realm, t *testing.T) {
	// Stale outer cur in a fresh frame → ErrSpoofedRealm.
	urequire.AbortsContains(t, cur, "rlm does not match the current crossing frame", func() {
		stale := cur
		func(cur realm) {
			NewToken("Foo", "FOO", 0, stale)
		}(cross(cur))
	})
}

func TestMint(cur realm, t *testing.T) {
	tests := []struct {
		name    string
		action  func(led *PrivateLedger) error
		wantErr error
		verify  func(t *testing.T, tok *Token, led *PrivateLedger)
	}{
		{
			name: "mint to valid address succeeds",
			action: func(led *PrivateLedger) error {
				return led.Mint(alice, "1")
			},
			wantErr: nil,
			verify: func(t *testing.T, tok *Token, led *PrivateLedger) {
				uassert.Equal(t, int64(1), tok.TotalSupply())
				uassert.Equal(t, int64(1), mustBalanceOf(t, tok, alice))
				uassert.Equal(t, 1, tok.KnownAccounts())
				owner, err := tok.OwnerOf("1")
				urequire.NoError(t, err)
				uassert.Equal(t, alice, owner)
			},
		},
		{
			name: "mint to invalid address returns ErrInvalidAddress",
			action: func(led *PrivateLedger) error {
				return led.Mint(zeroAddress, "1")
			},
			wantErr: ErrInvalidAddress,
			verify: func(t *testing.T, tok *Token, led *PrivateLedger) {
				uassert.Equal(t, int64(0), tok.TotalSupply())
			},
		},
		{
			name: "mint duplicate token id returns ErrTokenIdAlreadyExists",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				return led.Mint(bob, "1")
			},
			wantErr: ErrTokenIdAlreadyExists,
			verify: func(t *testing.T, tok *Token, led *PrivateLedger) {
				owner, err := tok.OwnerOf("1")
				urequire.NoError(t, err)
				uassert.Equal(t, alice, owner)
				uassert.Equal(t, int64(1), tok.TotalSupply())
			},
		},
		{
			name: "minting distinct ids to same owner accumulates balance",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				return led.Mint(alice, "2")
			},
			wantErr: nil,
			verify: func(t *testing.T, tok *Token, led *PrivateLedger) {
				uassert.Equal(t, int64(2), mustBalanceOf(t, tok, alice))
				uassert.Equal(t, int64(2), tok.TotalSupply())
				uassert.Equal(t, 1, tok.KnownAccounts())
			},
		},
	}

	for _, tc := range tests {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			tok, led := newTestToken("Foo", "FOO", 0, cur)
			err := tc.action(led)
			if tc.wantErr == nil {
				uassert.NoError(t, err)
			} else {
				uassert.ErrorIs(t, err, tc.wantErr)
			}
			if tc.verify != nil {
				tc.verify(t, tok, led)
			}
		})
	}
}

func TestBurn(cur realm, t *testing.T) {
	tests := []struct {
		name    string
		action  func(led *PrivateLedger) error
		wantErr error
		verify  func(t *testing.T, tok *Token, led *PrivateLedger)
	}{
		{
			name: "burn existing token clears all state",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				return led.Burn("1")
			},
			wantErr: nil,
			verify: func(t *testing.T, tok *Token, led *PrivateLedger) {
				uassert.Equal(t, int64(0), tok.TotalSupply())
				uassert.Equal(t, int64(0), mustBalanceOf(t, tok, alice))
				uassert.Equal(t, 0, tok.KnownAccounts())
				_, err := tok.OwnerOf("1")
				uassert.ErrorIs(t, err, ErrInvalidTokenId)
			},
		},
		{
			name: "burn clears any outstanding approval",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				urequire.NoError(t, led.Approve(alice, bob, "1"))
				return led.Burn("1")
			},
			wantErr: nil,
			verify: func(t *testing.T, tok *Token, led *PrivateLedger) {
				uassert.Equal(t, 0, led.tokenApprovals.Size())
				_, err := tok.GetApproved("1")
				uassert.ErrorIs(t, err, ErrInvalidTokenId)
			},
		},
		{
			name: "burn missing token returns ErrInvalidTokenId",
			action: func(led *PrivateLedger) error {
				return led.Burn("999")
			},
			wantErr: ErrInvalidTokenId,
		},
		{
			name: "burn one of two tokens keeps the account known",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				urequire.NoError(t, led.Mint(alice, "2"))
				return led.Burn("1")
			},
			wantErr: nil,
			verify: func(t *testing.T, tok *Token, led *PrivateLedger) {
				uassert.Equal(t, int64(1), mustBalanceOf(t, tok, alice))
				uassert.Equal(t, 1, tok.KnownAccounts())
				uassert.Equal(t, int64(1), tok.TotalSupply())
			},
		},
	}

	for _, tc := range tests {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			tok, led := newTestToken("Foo", "FOO", 0, cur)
			err := tc.action(led)
			if tc.wantErr == nil {
				uassert.NoError(t, err)
			} else {
				uassert.ErrorIs(t, err, tc.wantErr)
			}
			if tc.verify != nil {
				tc.verify(t, tok, led)
			}
		})
	}
}

func TestApprove(cur realm, t *testing.T) {
	tests := []struct {
		name    string
		action  func(led *PrivateLedger) error
		wantErr error
		verify  func(t *testing.T, tok *Token, led *PrivateLedger)
	}{
		{
			name: "owner approves another account",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				return led.Approve(alice, bob, "1")
			},
			wantErr: nil,
			verify: func(t *testing.T, tok *Token, led *PrivateLedger) {
				approved, err := tok.GetApproved("1")
				urequire.NoError(t, err)
				uassert.Equal(t, bob, approved)
			},
		},
		{
			name: "operator approves on behalf of owner",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				urequire.NoError(t, led.SetApprovalForAll(alice, bob, true))
				return led.Approve(bob, carl, "1")
			},
			wantErr: nil,
			verify: func(t *testing.T, tok *Token, led *PrivateLedger) {
				approved, err := tok.GetApproved("1")
				urequire.NoError(t, err)
				uassert.Equal(t, carl, approved)
			},
		},
		{
			name: "approve to zero address revokes an existing approval (EIP-721)",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				urequire.NoError(t, led.Approve(alice, bob, "1"))
				return led.Approve(alice, zeroAddress, "1")
			},
			wantErr: nil,
			verify: func(t *testing.T, tok *Token, led *PrivateLedger) {
				_, err := tok.GetApproved("1")
				uassert.ErrorIs(t, err, ErrTokenIdNotApproved)
			},
		},
		{
			name: "revoke with no prior approval is a no-op",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				return led.Approve(alice, zeroAddress, "1")
			},
			wantErr: nil,
			verify: func(t *testing.T, tok *Token, led *PrivateLedger) {
				_, err := tok.GetApproved("1")
				uassert.ErrorIs(t, err, ErrTokenIdNotApproved)
			},
		},
		{
			name: "approve on missing token returns ErrInvalidTokenId",
			action: func(led *PrivateLedger) error {
				return led.Approve(alice, bob, "999")
			},
			wantErr: ErrInvalidTokenId,
		},
		{
			name: "approve to current owner returns ErrApprovalToCurrentOwner",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				return led.Approve(alice, alice, "1")
			},
			wantErr: ErrApprovalToCurrentOwner,
		},
		{
			name: "non-owner non-operator approve returns ErrCallerIsNotOwnerOrApproved",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				return led.Approve(bob, carl, "1")
			},
			wantErr: ErrCallerIsNotOwnerOrApproved,
		},
	}

	for _, tc := range tests {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			tok, led := newTestToken("Foo", "FOO", 0, cur)
			err := tc.action(led)
			if tc.wantErr == nil {
				uassert.NoError(t, err)
			} else {
				uassert.ErrorIs(t, err, tc.wantErr)
			}
			if tc.verify != nil {
				tc.verify(t, tok, led)
			}
		})
	}
}

func TestSetApprovalForAll(cur realm, t *testing.T) {
	tests := []struct {
		name    string
		action  func(led *PrivateLedger) error
		wantErr error
		verify  func(t *testing.T, tok *Token, led *PrivateLedger)
	}{
		{
			name: "grant operator approval",
			action: func(led *PrivateLedger) error {
				return led.SetApprovalForAll(alice, bob, true)
			},
			wantErr: nil,
			verify: func(t *testing.T, tok *Token, led *PrivateLedger) {
				uassert.True(t, tok.IsApprovedForAll(alice, bob))
			},
		},
		{
			name: "revoke operator approval releases the node",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.SetApprovalForAll(alice, bob, true))
				return led.SetApprovalForAll(alice, bob, false)
			},
			wantErr: nil,
			verify: func(t *testing.T, tok *Token, led *PrivateLedger) {
				uassert.False(t, tok.IsApprovedForAll(alice, bob))
				uassert.Equal(t, 0, led.operatorApprovals.Size())
			},
		},
		{
			name: "revoke without a prior grant stores nothing",
			action: func(led *PrivateLedger) error {
				return led.SetApprovalForAll(alice, bob, false)
			},
			wantErr: nil,
			verify: func(t *testing.T, tok *Token, led *PrivateLedger) {
				uassert.False(t, tok.IsApprovedForAll(alice, bob))
				uassert.Equal(t, 0, led.operatorApprovals.Size())
			},
		},
		{
			name: "invalid operator returns ErrInvalidAddress",
			action: func(led *PrivateLedger) error {
				return led.SetApprovalForAll(alice, zeroAddress, true)
			},
			wantErr: ErrInvalidAddress,
		},
		{
			name: "owner equals operator returns ErrApprovalToCurrentOwner",
			action: func(led *PrivateLedger) error {
				return led.SetApprovalForAll(alice, alice, true)
			},
			wantErr: ErrApprovalToCurrentOwner,
		},
	}

	for _, tc := range tests {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			tok, led := newTestToken("Foo", "FOO", 0, cur)
			err := tc.action(led)
			if tc.wantErr == nil {
				uassert.NoError(t, err)
			} else {
				uassert.ErrorIs(t, err, tc.wantErr)
			}
			if tc.verify != nil {
				tc.verify(t, tok, led)
			}
		})
	}
}

func TestTransferFrom(cur realm, t *testing.T) {
	tests := []struct {
		name    string
		action  func(led *PrivateLedger) error
		wantErr error
		verify  func(t *testing.T, tok *Token, led *PrivateLedger)
	}{
		{
			name: "owner transfers own token",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				return led.TransferFrom(alice, alice, bob, "1")
			},
			wantErr: nil,
			verify: func(t *testing.T, tok *Token, led *PrivateLedger) {
				owner, err := tok.OwnerOf("1")
				urequire.NoError(t, err)
				uassert.Equal(t, bob, owner)
				uassert.Equal(t, int64(0), mustBalanceOf(t, tok, alice))
				uassert.Equal(t, int64(1), mustBalanceOf(t, tok, bob))
			},
		},
		{
			name: "approved spender transfers and approval is cleared",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				urequire.NoError(t, led.Approve(alice, bob, "1"))
				return led.TransferFrom(bob, alice, carl, "1")
			},
			wantErr: nil,
			verify: func(t *testing.T, tok *Token, led *PrivateLedger) {
				owner, err := tok.OwnerOf("1")
				urequire.NoError(t, err)
				uassert.Equal(t, carl, owner)
				_, err = tok.GetApproved("1")
				uassert.ErrorIs(t, err, ErrTokenIdNotApproved)
			},
		},
		{
			name: "operator transfers owner token",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				urequire.NoError(t, led.SetApprovalForAll(alice, bob, true))
				return led.TransferFrom(bob, alice, carl, "1")
			},
			wantErr: nil,
			verify: func(t *testing.T, tok *Token, led *PrivateLedger) {
				owner, err := tok.OwnerOf("1")
				urequire.NoError(t, err)
				uassert.Equal(t, carl, owner)
			},
		},
		{
			name: "unauthorized spender returns ErrCallerIsNotOwnerOrApproved",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				return led.TransferFrom(bob, alice, carl, "1")
			},
			wantErr: ErrCallerIsNotOwnerOrApproved,
		},
		{
			name: "spender on missing token returns ErrCallerIsNotOwnerOrApproved",
			action: func(led *PrivateLedger) error {
				return led.TransferFrom(alice, alice, bob, "999")
			},
			wantErr: ErrCallerIsNotOwnerOrApproved,
		},
		{
			name: "transfer to self returns ErrCannotTransferToSelf",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				return led.TransferFrom(alice, alice, alice, "1")
			},
			wantErr: ErrCannotTransferToSelf,
		},
		{
			name: "transfer from invalid address returns ErrInvalidAddress",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				return led.TransferFrom(alice, zeroAddress, bob, "1")
			},
			wantErr: ErrInvalidAddress,
		},
		{
			name: "transfer to invalid address returns ErrInvalidAddress",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				return led.TransferFrom(alice, alice, zeroAddress, "1")
			},
			wantErr: ErrInvalidAddress,
		},
		{
			name: "transfer from incorrect owner returns ErrTransferFromIncorrectOwner",
			action: func(led *PrivateLedger) error {
				urequire.NoError(t, led.Mint(alice, "1"))
				return led.TransferFrom(alice, bob, carl, "1")
			},
			wantErr: ErrTransferFromIncorrectOwner,
		},
	}

	for _, tc := range tests {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			tok, led := newTestToken("Foo", "FOO", 0, cur)
			err := tc.action(led)
			if tc.wantErr == nil {
				uassert.NoError(t, err)
			} else {
				uassert.ErrorIs(t, err, tc.wantErr)
			}
			if tc.verify != nil {
				tc.verify(t, tok, led)
			}
		})
	}
}

func TestReadViews(cur realm, t *testing.T) {
	tok, led := newTestToken("Foo NFT", "FOO", 0, cur)
	urequire.NoError(t, led.Mint(alice, "1"))
	urequire.NoError(t, led.Mint(alice, "2"))
	urequire.NoError(t, led.Mint(bob, "3"))
	urequire.NoError(t, led.Approve(alice, carl, "1"))
	urequire.NoError(t, led.SetApprovalForAll(alice, bob, true))

	tests := []struct {
		name  string
		check func(t *testing.T)
	}{
		{"GetName returns collection name", func(t *testing.T) {
			uassert.Equal(t, "Foo NFT", tok.GetName())
		}},
		{"GetSymbol returns collection symbol", func(t *testing.T) {
			uassert.Equal(t, "FOO", tok.GetSymbol())
		}},
		{"ID carries realm, symbol and seqid", func(t *testing.T) {
			uassert.True(t, strings.HasPrefix(tok.ID(), "gno.land/"))
			uassert.True(t, strings.Contains(tok.ID(), ".FOO."))
		}},
		{"TotalSupply counts live tokens", func(t *testing.T) {
			uassert.Equal(t, int64(3), tok.TotalSupply())
		}},
		{"KnownAccounts counts distinct holders", func(t *testing.T) {
			uassert.Equal(t, 2, tok.KnownAccounts())
		}},
		{"BalanceOf of a holder", func(t *testing.T) {
			uassert.Equal(t, int64(2), mustBalanceOf(t, tok, alice))
		}},
		{"BalanceOf of a non-holder is zero", func(t *testing.T) {
			uassert.Equal(t, int64(0), mustBalanceOf(t, tok, carl))
		}},
		{"BalanceOf of the zero address returns ErrInvalidAddress", func(t *testing.T) {
			_, err := tok.BalanceOf(zeroAddress)
			uassert.ErrorIs(t, err, ErrInvalidAddress)
		}},
		{"OwnerOf existing token", func(t *testing.T) {
			owner, err := tok.OwnerOf("3")
			urequire.NoError(t, err)
			uassert.Equal(t, bob, owner)
		}},
		{"OwnerOf missing token returns ErrInvalidTokenId", func(t *testing.T) {
			_, err := tok.OwnerOf("999")
			uassert.ErrorIs(t, err, ErrInvalidTokenId)
		}},
		{"GetApproved returns the approved account", func(t *testing.T) {
			approved, err := tok.GetApproved("1")
			urequire.NoError(t, err)
			uassert.Equal(t, carl, approved)
		}},
		{"GetApproved on unapproved token returns ErrTokenIdNotApproved", func(t *testing.T) {
			_, err := tok.GetApproved("2")
			uassert.ErrorIs(t, err, ErrTokenIdNotApproved)
		}},
		{"GetApproved on missing token returns ErrInvalidTokenId", func(t *testing.T) {
			_, err := tok.GetApproved("999")
			uassert.ErrorIs(t, err, ErrInvalidTokenId)
		}},
		{"IsApprovedForAll true for operator", func(t *testing.T) {
			uassert.True(t, tok.IsApprovedForAll(alice, bob))
		}},
		{"IsApprovedForAll false for non-operator", func(t *testing.T) {
			uassert.False(t, tok.IsApprovedForAll(alice, carl))
		}},
		{"RenderHome renders header and counters", func(t *testing.T) {
			out := tok.RenderHome()
			uassert.True(t, strings.Contains(out, "# Foo NFT ($FOO)"), "header")
			uassert.True(t, strings.Contains(out, "**Total supply**: 3"), "supply")
			uassert.True(t, strings.Contains(out, "**Known accounts**: 2"), "accounts")
		}},
	}

	for _, tc := range tests {
		tc := tc
		t.Run(tc.name, tc.check)
	}
}

func TestRegisterExtensionNil(cur realm, t *testing.T) {
	_, led := newTestToken("Foo", "FOO", 0, cur)
	uassert.PanicsWithMessage(t, cur, "grc721: nil extension", func() {
		led.RegisterExtension(nil)
	})
}

func TestRegisterExtensionRejectsDuplicateKind(cur realm, t *testing.T) {
	_, led := newTestToken("Foo", "FOO", 0, cur)
	ext := &mockExtension{}
	led.RegisterExtension(ext)

	uassert.PanicsWithMessage(t, cur, "grc721: extension kind already registered: mock", func() {
		led.RegisterExtension(ext)
	})
	uassert.PanicsWithMessage(t, cur, "grc721: extension kind already registered: mock", func() {
		led.RegisterExtension(&mockExtension{})
	})
}

func TestRegisterExtensionRejectsDuplicateKindOfUncomparableType(cur realm, t *testing.T) {
	_, led := newTestToken("Foo", "FOO", 0, cur)
	led.RegisterExtension(journalExtension{seen: []TokenID{"1"}})

	uassert.PanicsWithMessage(t, cur, "grc721: extension kind already registered: journal", func() {
		led.RegisterExtension(journalExtension{seen: []TokenID{"2"}})
	})
}

func TestExtensionHookFanOut(cur realm, t *testing.T) {
	tests := []struct {
		name   string
		run    func(t *testing.T, led *PrivateLedger, ext *mockExtension)
		verify func(t *testing.T, ext *mockExtension)
	}{
		{
			name: "mint, transfer and burn each notify the extension",
			run: func(t *testing.T, led *PrivateLedger, ext *mockExtension) {
				led.RegisterExtension(ext)
				urequire.NoError(t, led.Mint(alice, "1"))
				urequire.NoError(t, led.TransferFrom(alice, alice, bob, "1"))
				urequire.NoError(t, led.Burn("1"))
			},
			verify: func(t *testing.T, ext *mockExtension) {
				uassert.Equal(t, 1, ext.mints)
				uassert.Equal(t, 1, ext.transfers)
				uassert.Equal(t, alice, ext.lastTransferFrom)
				uassert.Equal(t, bob, ext.lastTransferTo)
				uassert.Equal(t, 1, ext.burns)
				uassert.Equal(t, "1", ext.lastBurn.String())
			},
		},
		{
			name: "failed operations do not notify the extension",
			run: func(t *testing.T, led *PrivateLedger, ext *mockExtension) {
				led.RegisterExtension(ext)
				uassert.ErrorIs(t, led.Mint(zeroAddress, "1"), ErrInvalidAddress)
				uassert.ErrorIs(t, led.Burn("999"), ErrInvalidTokenId)
			},
			verify: func(t *testing.T, ext *mockExtension) {
				uassert.Equal(t, 0, ext.mints)
				uassert.Equal(t, 0, ext.burns)
			},
		},
	}

	for _, tc := range tests {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			_, led := newTestToken("Foo", "FOO", 0, cur)
			ext := &mockExtension{}
			tc.run(t, led, ext)
			tc.verify(t, ext)
		})
	}
}

func TestReadToken(cur realm, t *testing.T) {
	tok, led := newTestToken("Foo", "FOO", 0, cur)
	uassert.Equal(t, tok.ID(), led.ReadToken().ID())
	uassert.True(t, led.ReadToken() == tok, "ReadToken returns the same *Token")
}

types.gno

package grc721

import (
	"errors"

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

type TokenID string

func (t TokenID) String() string { return string(t) }

// A Teller is a capability that acts as some account whenever it writes.
// IsCanonicalTeller confirms a Teller was minted by this package — an embedding
// forgery fails the check — but it does NOT reveal which account the Teller acts
// as: a caller-scoped CallerTeller and the admin-grade ImpersonateTeller (which
// acts as an arbitrary address) are both canonical. So it is an authenticity
// check on the implementation, not an authorization guard on the acting account;
// a caller accepting a Teller from outside must still establish, out of band, what
// account that Teller is entitled to act as.
// safeTransferFrom is omitted: EIP-721's receiver check needs a registry, and aliasing it would imply false safety.
type Teller interface {
	GetName() string
	GetSymbol() string
	ID() string
	TotalSupply() int64
	BalanceOf(owner address) (int64, error)
	OwnerOf(tid TokenID) (address, error)
	GetApproved(tid TokenID) (address, error)
	IsApprovedForAll(owner, operator address) bool

	Approve(_ int, rlm realm, to address, tid TokenID) error
	SetApprovalForAll(_ int, rlm realm, operator address, approved bool) error
	TransferFrom(_ int, rlm realm, from, to address, tid TokenID) error
}

// Extension hooks fire on every mint/transfer/burn. This is a trust grant to the
// issuer, not an EIP-721 feature: only the issuer can attach one (RegisterExtension
// holds the PrivateLedger), but once attached the hook runs arbitrary issuer code on
// every movement, a panic in OnMint/OnTransfer/OnBurn aborts the transaction before
// the movement is announced — an implicit veto over transfers — and gas scales
// linearly with the extension count. Hooks run after the ledger write so they observe
// the post-movement state; only a caller that recovers from the panic keeps that write.
// Holders of a collection's tokens are therefore trusting the issuer not to freeze or
// tax movement through this surface. Hooks take no rlm params (they cannot capture cur);
// attach only via RegisterExtension.
type Extension interface {
	ExtensionKind() string // unique; duplicates rejected at register
	OnMint(to address, tid TokenID)
	OnTransfer(from, to address, tid TokenID)
	OnBurn(tid TokenID)
}

type ExtensionView interface {
	ExtensionKind() string
	TokenID() string // core Token.ID
}

type Token struct {
	id     string // raw creation pkgpath + "." + symbol + "." + id
	name   string
	symbol string
	ledger *PrivateLedger
	// origRealm is the PkgPath of the realm that created the token, captured
	// unforgeably in NewToken. A frame-relative teller only works there.
	origRealm string
}

type PrivateLedger struct {
	token             *Token
	totalSupply       int64
	owners            avl.Tree // TokenID -> owner address
	balances          avl.Tree // owner address -> int64
	tokenApprovals    avl.Tree // TokenID -> approved address
	operatorApprovals avl.Tree // "owner:operator" -> bool
	extensions        []Extension
}

var (
	ErrInvalidTokenId             = errors.New("invalid token id")
	ErrInvalidAddress             = errors.New("invalid address")
	ErrTokenIdNotApproved         = errors.New("token id not approved for anyone")
	ErrApprovalToCurrentOwner     = errors.New("approval to current owner")
	ErrCallerIsNotOwner           = errors.New("caller is not token owner")
	ErrCannotTransferToSelf       = errors.New("cannot send transfer to self")
	ErrTransferFromIncorrectOwner = errors.New("transfer from incorrect owner")
	ErrCallerIsNotOwnerOrApproved = errors.New("caller is not token owner or approved")
	ErrTokenIdAlreadyExists       = errors.New("token id already exists")
	ErrReadonly                   = errors.New("teller is readonly")
	ErrSpoofedRealm               = errors.New("rlm does not match the current crossing frame")
	ErrForeignCallerTeller        = errors.New("frame-relative teller used outside the token's realm")
	ErrNotRealm                   = errors.New("rlm must be a realm (got EOA/origin)")
	ErrInvalidName                = errors.New("invalid token name (empty, too long, or contains control chars)")
	ErrInvalidSymbol              = errors.New("invalid token symbol (empty, too long, or contains chars outside [A-Za-z0-9_-])")
)

// Symbol charset matches grc20reg slug (embedded in Token.ID / events).
const (
	MaxNameLen   = 64
	MaxSymbolLen = 11
)

const (
	// NewToken announces every token creation; see NewToken for why it is a
	// complete provenance signal.
	NewTokenEvent = "NewToken"
	// Mint emits from empty addr; burn emits to empty addr (EIP-721).
	TransferEvent       = "Transfer"
	ApprovalEvent       = "Approval"
	ApprovalForAllEvent = "ApprovalForAll"
)

var zeroAddress = address("")

type fnTeller struct {
	accountFn func(_ int, rlm realm) address
	// homeGuard marks a frame-relative teller, whose writes are confined to
	// the token's own realm. See fnTeller.guardHome.
	homeGuard bool
	*Token
}

var _ Teller = (*fnTeller)(nil)

// IsCanonicalTeller reports whether t was minted by this package, rejecting Tellers
// forged by embedding *fnTeller in a wrapper. It does NOT discriminate by capability
// grade: CallerTeller, ReadonlyTeller, RealmTeller, RealmSubTeller and the admin-grade
// ImpersonateTeller all return true. Do not treat a true result as proof that a Teller
// is a caller-scoped capability — establish the acting account separately.
func IsCanonicalTeller(t Teller) bool {
	_, ok := t.(*fnTeller)
	return ok
}