Playground
examples_test.gno
package grc20
// XXX: write Examples
func ExampleInit() {}
func ExampleExposeBankForMaketxRunOrImports() {}
func ExampleCustomTellerImpl() {}
func ExampleAllowance() {}
func ExampleRealmBanker() {}
func ExamplePreviousRealmBanker() {}
func ExampleAccountBanker() {}
func ExampleTransfer() {}
func ExampleApprove() {}
func ExampleTransferFrom() {}
func ExampleMint() {}
func ExampleBurn() {}
// ...
gnomod.toml
module = "gno.land/p/nt/grc20/v0" gno = "0.9" [addpkg] creator = "g1edq4dugw0sgat4zxcw9xardvuydqf6cgleuc8p"
mock.gno
package grc20 // XXX: func Mock(t *Token)
tellers.gno
package grc20
import (
"chain"
)
// CallerTeller returns a GRC20 compatible teller that, at each write call,
// resolves the caller as rlm.Previous() — the realm that crossed into the
// caller. rlm must be the caller's own captured cur (asserted via
// rlm.IsCurrent() inside the Teller methods).
//
// SECURITY: this accessor hangs off *PrivateLedger, not *Token, and that is
// load-bearing. A frame-relative teller debits whoever crossed into the realm
// holding it, so it is only ever meaningful inside the token's own realm,
// whose wrappers act for a caller who knowingly invoked the token. Anywhere
// else it is a confused deputy. The *Token pointer is published (exported
// vars, grc20factory, grc20reg) but the ledger is not — 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 makes a leaked
// teller inert everywhere but home.
func (ledger *PrivateLedger) CallerTeller() Teller {
if ledger == nil {
panic("Ledger cannot be nil")
}
return &fnTeller{
accountFn: func(_ int, rlm realm) address {
return rlm.Previous().Address()
},
homeGuard: true,
Token: ledger.token,
}
}
// ReadonlyTeller is a GRC20 compatible teller that panics for any write operation.
func (tok *Token) ReadonlyTeller() Teller {
if tok == nil {
panic("Token cannot be nil")
}
return &fnTeller{
accountFn: nil,
Token: tok,
}
}
// RealmTeller returns a GRC20 compatible teller that will store the
// caller realm permanently. Calling anything through this teller will
// result in allowance or balance changes for the realm that initialized the teller.
// The initializer of this teller should usually never share the resulting Teller from
// this method except maybe for advanced delegation flows such as a DAO treasury
// management.
//
// rlm must be the caller's own captured cur (asserted via rlm.IsCurrent()).
// The address is frozen eagerly at construction.
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,
}
}
// RealmSubTeller is like RealmTeller but uses the provided slug to derive a
// subaccount.
//
// rlm must be the caller's own captured cur (asserted via rlm.IsCurrent()).
// The subaccount address is frozen eagerly at construction.
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,
}
}
// ImpersonateTeller returns a GRC20 compatible teller that impersonates as a
// specified address. This allows operations to be performed as if they were
// executed by the given address, enabling the caller to manipulate tokens on
// behalf of that address.
//
// It is particularly useful in scenarios where a contract needs to perform
// actions on behalf of a user or another account, without exposing the
// underlying logic or requiring direct access to the user's account. The
// returned teller will use the provided address for all operations, effectively
// masking the original caller.
//
// This method should be used with caution, as it allows for potentially
// sensitive operations to be performed under the guise of another address.
func (ledger *PrivateLedger) ImpersonateTeller(addr address) Teller {
if ledger == nil {
panic("Ledger cannot be nil")
}
return &fnTeller{
accountFn: func(_ int, _ realm) address {
return addr
},
Token: ledger.token,
}
}
// generic tellers methods.
//
// guardHome confines a frame-relative (homeGuard) 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, which 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 allowance 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 funds uses the ordinary route:
// Approve, then RealmTeller().TransferFrom, which is eagerly bound to that
// realm's own address and allowance-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) Transfer(_ int, rlm realm, to address, amount int64) 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.Transfer(caller, to, amount)
}
func (ft *fnTeller) Approve(_ int, rlm realm, spender address, amount int64) 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, spender, amount)
}
func (ft *fnTeller) TransferFrom(_ int, rlm realm, owner, to address, amount int64) 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(owner, spender, to, amount)
}
// helpers
//
// accountSlugAddr returns the address derived from the specified address and slug.
func accountSlugAddr(addr address, slug string) address {
// XXX: use a new `std.XXX` call for this.
if slug == "" {
return addr
}
key := addr.String() + "/" + slug
return chain.PackageAddress(key) // temporarily using this helper
}
tellers_test.gno
package grc20
import (
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/ufmt/v0"
"gno.land/p/nt/urequire/v0"
)
func TestCallerTellerImpl(cur realm, t *testing.T) {
tok, ledger := newTestToken("Dummy", "DUMMY", 4, 0, cur)
teller := ledger.CallerTeller()
urequire.False(t, tok == nil)
var _ Teller = teller
}
// The sub-realm case (guardHome must not lock out the token's own realm when it
// operates under an identity minted by its own cur.Sub()) needs a real realm
// frame, since cur.Sub() refuses to mint from a p/ package. It lives in
// filetests/caller_teller_sub_realm_filetest.gno.
// evilWrap embeds Teller; the seal-marker pattern (if we had one) would be
// satisfied via promotion, but IsCanonicalTeller rejects it because *evilWrap
// is nominally distinct from *fnTeller.
type evilWrap struct {
Teller
}
func TestIsCanonicalTeller(cur realm, t *testing.T) {
_, ledger := newTestToken("Dummy", "DUMMY", 4, 0, cur)
legit := ledger.CallerTeller()
uassert.True(t, IsCanonicalTeller(legit),
"canonical *fnTeller from CallerTeller must pass")
evil := &evilWrap{Teller: legit}
uassert.False(t, IsCanonicalTeller(evil),
"foreign type embedding a canonical Teller must be rejected")
}
func TestTeller(cur realm, t *testing.T) {
var (
alice = testutils.TestAddress("alice")
bob = testutils.TestAddress("bob")
carl = testutils.TestAddress("carl")
)
token, ledger := newTestToken("Dummy", "DUMMY", 6, 0, cur)
checkBalances := func(aliceEB, bobEB, carlEB int64) {
t.Helper()
exp := ufmt.Sprintf("alice=%d bob=%d carl=%d", aliceEB, bobEB, carlEB)
aliceGB := token.BalanceOf(alice)
bobGB := token.BalanceOf(bob)
carlGB := token.BalanceOf(carl)
got := ufmt.Sprintf("alice=%d bob=%d carl=%d", aliceGB, bobGB, carlGB)
uassert.Equal(t, got, exp, "invalid balances")
}
checkAllowances := func(abEB, acEB, baEB, bcEB, caEB, cbEB int64) {
t.Helper()
exp := ufmt.Sprintf("ab=%d ac=%d ba=%d bc=%d ca=%d cb=%s", abEB, acEB, baEB, bcEB, caEB, cbEB)
abGB := token.Allowance(alice, bob)
acGB := token.Allowance(alice, carl)
baGB := token.Allowance(bob, alice)
bcGB := token.Allowance(bob, carl)
caGB := token.Allowance(carl, alice)
cbGB := token.Allowance(carl, bob)
got := ufmt.Sprintf("ab=%d ac=%d ba=%d bc=%d ca=%d cb=%s", abGB, acGB, baGB, bcGB, caGB, cbGB)
uassert.Equal(t, got, exp, "invalid allowances")
}
checkBalances(0, 0, 0)
checkAllowances(0, 0, 0, 0, 0, 0)
urequire.NoError(t, ledger.Mint(alice, 1000))
urequire.NoError(t, ledger.Mint(alice, 100))
checkBalances(1100, 0, 0)
checkAllowances(0, 0, 0, 0, 0, 0)
urequire.NoError(t, ledger.Approve(alice, bob, 99999999))
checkBalances(1100, 0, 0)
checkAllowances(99999999, 0, 0, 0, 0, 0)
urequire.NoError(t, ledger.Approve(alice, bob, 400))
checkBalances(1100, 0, 0)
checkAllowances(400, 0, 0, 0, 0, 0)
urequire.Error(t, ledger.TransferFrom(alice, bob, carl, 100000000))
checkBalances(1100, 0, 0)
checkAllowances(400, 0, 0, 0, 0, 0)
urequire.NoError(t, ledger.TransferFrom(alice, bob, carl, 100))
checkBalances(1000, 0, 100)
checkAllowances(300, 0, 0, 0, 0, 0)
urequire.Error(t, ledger.SpendAllowance(alice, bob, 2000000))
checkBalances(1000, 0, 100)
checkAllowances(300, 0, 0, 0, 0, 0)
urequire.NoError(t, ledger.SpendAllowance(alice, bob, 100))
checkBalances(1000, 0, 100)
checkAllowances(200, 0, 0, 0, 0, 0)
}
func TestCallerTeller(cur realm, t *testing.T) {
alice := testutils.TestAddress("alice")
bob := testutils.TestAddress("bob")
carl := testutils.TestAddress("carl")
token, ledger := newTestToken("Dummy", "DUMMY", 6, 0, cur)
teller := ledger.CallerTeller()
checkBalances := func(aliceEB, bobEB, carlEB int64) {
t.Helper()
exp := ufmt.Sprintf("alice=%d bob=%d carl=%d", aliceEB, bobEB, carlEB)
aliceGB := token.BalanceOf(alice)
bobGB := token.BalanceOf(bob)
carlGB := token.BalanceOf(carl)
got := ufmt.Sprintf("alice=%d bob=%d carl=%d", aliceGB, bobGB, carlGB)
uassert.Equal(t, got, exp, "invalid balances")
}
checkAllowances := func(abEB, acEB, baEB, bcEB, caEB, cbEB int64) {
t.Helper()
exp := ufmt.Sprintf("ab=%d ac=%d ba=%d bc=%d ca=%d cb=%s", abEB, acEB, baEB, bcEB, caEB, cbEB)
abGB := token.Allowance(alice, bob)
acGB := token.Allowance(alice, carl)
baGB := token.Allowance(bob, alice)
bcGB := token.Allowance(bob, carl)
caGB := token.Allowance(carl, alice)
cbGB := token.Allowance(carl, bob)
got := ufmt.Sprintf("ab=%d ac=%d ba=%d bc=%d ca=%d cb=%s", abGB, acGB, baGB, bcGB, caGB, cbGB)
uassert.Equal(t, got, exp, "invalid allowances")
}
urequire.NoError(t, ledger.Mint(alice, 1000))
checkBalances(1000, 0, 0)
checkAllowances(0, 0, 0, 0, 0, 0)
testing.SetRealm(testing.NewUserRealm(alice))
func(cur realm) { urequire.NoError(t, teller.Approve(0, cur, bob, 600)) }(cross(cur))
checkBalances(1000, 0, 0)
checkAllowances(600, 0, 0, 0, 0, 0)
testing.SetRealm(testing.NewUserRealm(bob))
func(cur realm) { urequire.Error(t, teller.TransferFrom(0, cur, alice, carl, 700)) }(cross(cur))
checkBalances(1000, 0, 0)
checkAllowances(600, 0, 0, 0, 0, 0)
func(cur realm) { urequire.NoError(t, teller.TransferFrom(0, cur, alice, carl, 400)) }(cross(cur))
checkBalances(600, 0, 400)
checkAllowances(200, 0, 0, 0, 0, 0)
}
token.gno
package grc20
import (
"chain"
"math"
"math/overflow"
"strconv"
"gno.land/p/nt/seqid/v0"
"gno.land/p/nt/ufmt/v0"
)
// NewToken creates a Token whose origRealm is bound to the calling realm.
// rlm must be the caller's own captured cur (asserted via rlm.IsCurrent()),
// and rlm.PkgPath() — the calling realm itself, with any realm.Sub subpath
// stripped — becomes the Token's origRealm. Token.ID() keeps the raw
// rlm.PkgPath(), and returns it + "." + symbol + "." + id.
//
// Because IsCurrent runtime-validates that rlm came from the live
// crossing frame, origRealm is unforgeable: an external realm cannot
// fabricate a Token claiming to belong to a different package.
//
// Realms that create multiple tokens should allocate id from one persistent
// seqid.ID, shared by every creation path, to avoid conflicting identifiers:
//
// var nextTokenID seqid.ID
// Token, ledger := grc20.NewToken("Foo", "FOO", 4, nextTokenID.Next(), cur)
//
// A realm that creates only a single token can pass 0 directly, since no
// other token of that realm can collide with it.
//
// If the Token should be discoverable, follow up with
// grc20reg.Register(cross(cur), Token, slug). The registry key is the
// rlmPath.symbol prefix of Token.ID(), without its trailing id.
//
// 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, decimals int, 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)
}
if decimals < 0 || decimals > MaxDecimals {
panic(ErrInvalidDecimals)
}
// origRealm drops any realm.Sub subpath: a token created while its realm
// operates under a sub identity still belongs to the host realm. guardHome
// resolves the invoking host the same way, so storing the raw path here
// would pin the token to that sub and lock its own realm out for good.
origRealm, _, _ := chain.SplitPkgSubPath(pkgPath)
ledger := &PrivateLedger{}
token := &Token{
id: pkgPath + "." + symbol + "." + id.String(),
name: name,
symbol: symbol,
decimals: decimals,
ledger: ledger,
origRealm: origRealm,
}
ledger.token = token
chain.Emit(
NewTokenEvent,
"token", token.id,
"name", name,
"symbol", symbol,
"decimals", strconv.Itoa(decimals),
)
return token, ledger
}
// validName reports whether name is a valid display name: non-empty,
// within MaxNameLen, and contains no control characters (any rune
// below 0x20 or 0x7f). Permits Unicode letters, digits, punctuation,
// and spaces — name is purely a display field.
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
}
// validSymbol reports whether s is valid slug-compatible metadata: non-empty,
// within MaxSymbolLen, and consists only of [A-Za-z0-9_-].
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')
}
// GetName returns the name of the token.
func (tok Token) GetName() string { return tok.name }
// GetSymbol returns the symbol of the token.
func (tok Token) GetSymbol() string { return tok.symbol }
// GetDecimals returns the number of decimals used to get the token's precision.
func (tok Token) GetDecimals() int { return tok.decimals }
// TotalSupply returns the total supply of the token.
func (tok Token) TotalSupply() int64 { return tok.ledger.totalSupply }
// KnownAccounts returns the number of known accounts in the bank.
func (tok Token) KnownAccounts() int { return tok.ledger.balances.Size() }
// ID returns the Identifier of the token.
// It is composed of the creating realm's raw pkgpath — including any
// realm.Sub subpath, unlike origRealm — the symbol, and the provided id.
func (tok *Token) ID() string {
return tok.id
}
// HasAddr checks if the specified address is a known account in the bank.
func (tok Token) HasAddr(addr address) bool {
return tok.ledger.hasAddr(addr)
}
// BalanceOf returns the balance of the specified address.
func (tok Token) BalanceOf(addr address) int64 {
return tok.ledger.balanceOf(addr)
}
// Allowance returns the allowance of the specified owner and spender.
func (tok Token) Allowance(owner, spender address) int64 {
return tok.ledger.allowance(owner, spender)
}
func (tok Token) RenderHome() string {
str := ""
str += ufmt.Sprintf("# %s ($%s)\n\n", tok.name, tok.symbol)
str += ufmt.Sprintf("* **Decimals**: %d\n", tok.decimals)
str += ufmt.Sprintf("* **Total supply**: %d\n", tok.ledger.totalSupply)
str += ufmt.Sprintf("* **Known accounts**: %d\n", tok.KnownAccounts())
return str
}
// SpendAllowance decreases the allowance of the specified owner and spender.
func (led *PrivateLedger) SpendAllowance(owner, spender address, amount int64) error {
if !owner.IsValid() || !spender.IsValid() {
return ErrInvalidAddress
}
if amount < 0 {
return ErrInvalidAmount
}
// do nothing
if amount == 0 {
return nil
}
currentAllowance := led.allowance(owner, spender)
if currentAllowance < amount {
return ErrInsufficientAllowance
}
key := allowanceKey(owner, spender)
newAllowance := overflow.Sub64p(currentAllowance, amount)
if newAllowance == 0 {
led.allowances.Remove(key)
} else {
led.allowances.Set(key, newAllowance)
}
return nil
}
// Transfer transfers tokens from the specified from address to the specified to address.
func (led *PrivateLedger) Transfer(from, to address, amount int64) error {
if !from.IsValid() {
return ErrInvalidAddress
}
if !to.IsValid() {
return ErrInvalidAddress
}
if from == to {
return ErrCannotTransferToSelf
}
if amount < 0 {
return ErrInvalidAmount
}
var (
toBalance = led.balanceOf(to)
fromBalance = led.balanceOf(from)
)
if fromBalance < amount {
return ErrInsufficientBalance
}
var (
newToBalance = overflow.Add64p(toBalance, amount)
newFromBalance = overflow.Sub64p(fromBalance, amount)
)
led.balances.Set(string(to), newToBalance)
if newFromBalance == 0 {
led.balances.Remove(string(from))
} else {
led.balances.Set(string(from), newFromBalance)
}
chain.Emit(
TransferEvent,
"token", led.token.ID(),
"from", from.String(),
"to", to.String(),
"value", strconv.Itoa(int(amount)),
)
return nil
}
// TransferFrom transfers tokens from the specified owner to the specified to address.
// It first checks if the owner has sufficient balance and then decreases the allowance.
func (led *PrivateLedger) TransferFrom(owner, spender, to address, amount int64) error {
if amount < 0 {
return ErrInvalidAmount
}
if !owner.IsValid() || !to.IsValid() {
return ErrInvalidAddress
}
if owner == to {
return ErrCannotTransferToSelf
}
if led.balanceOf(owner) < amount {
return ErrInsufficientBalance
}
// The check above guarantees that Transfer will succeed, ensuring
// atomicity for the subsequent operations.
if err := led.SpendAllowance(owner, spender, amount); err != nil {
return err
}
if err := led.Transfer(owner, to, amount); err != nil {
return err
}
return nil
}
// Approve sets the allowance of the specified owner and spender.
func (led *PrivateLedger) Approve(owner, spender address, amount int64) error {
if !owner.IsValid() || !spender.IsValid() {
return ErrInvalidAddress
}
if amount < 0 {
return ErrInvalidAmount
}
led.allowances.Set(allowanceKey(owner, spender), amount)
chain.Emit(
ApprovalEvent,
"token", led.token.ID(),
"owner", string(owner),
"spender", string(spender),
"value", strconv.Itoa(int(amount)),
)
return nil
}
// Mint increases the total supply of the token and adds the specified amount to the specified address.
func (led *PrivateLedger) Mint(addr address, amount int64) error {
if !addr.IsValid() {
return ErrInvalidAddress
}
if amount < 0 {
return ErrInvalidAmount
}
// limit amount to MaxInt64 - totalSupply
if amount > overflow.Sub64p(math.MaxInt64, led.totalSupply) {
return ErrMintOverflow
}
led.totalSupply += amount
currentBalance := led.balanceOf(addr)
newBalance := overflow.Add64p(currentBalance, amount)
led.balances.Set(string(addr), newBalance)
chain.Emit(
TransferEvent,
"token", led.token.ID(),
"from", "",
"to", string(addr),
"value", strconv.Itoa(int(amount)),
)
return nil
}
// Burn decreases the total supply of the token and subtracts the specified amount from the specified address.
func (led *PrivateLedger) Burn(addr address, amount int64) error {
if !addr.IsValid() {
return ErrInvalidAddress
}
if amount < 0 {
return ErrInvalidAmount
}
currentBalance := led.balanceOf(addr)
if currentBalance < amount {
return ErrInsufficientBalance
}
led.totalSupply = overflow.Sub64p(led.totalSupply, amount)
newBalance := overflow.Sub64p(currentBalance, amount)
if newBalance == 0 {
led.balances.Remove(string(addr))
} else {
led.balances.Set(string(addr), newBalance)
}
chain.Emit(
TransferEvent,
"token", led.token.ID(),
"from", string(addr),
"to", "",
"value", strconv.Itoa(int(amount)),
)
return nil
}
// hasAddr checks if the specified address is a known account in the ledger.
func (led PrivateLedger) hasAddr(addr address) bool {
return led.balances.Has(addr.String())
}
// balanceOf returns the balance of the specified address.
func (led PrivateLedger) balanceOf(addr address) int64 {
balance := led.balances.Get(addr.String())
if balance == nil {
return 0
}
return balance.(int64)
}
// allowance returns the allowance of the specified owner and spender.
func (led PrivateLedger) allowance(owner, spender address) int64 {
allowance := led.allowances.Get(allowanceKey(owner, spender))
if allowance == nil {
return 0
}
return allowance.(int64)
}
// allowanceKey returns the key for the allowance of the specified owner and spender.
func allowanceKey(owner, spender address) string {
return owner.String() + ":" + spender.String()
}
token_test.gno
package grc20
import (
"errors"
"math"
"strings"
"testing"
"gno.land/p/nt/seqid/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/ufmt/v0"
"gno.land/p/nt/urequire/v0"
)
// newTestToken constructs a Token. The IIFE same-realm cross
// promotes the test's EOA-origin cur into a fresh /p/grc20
// CodeRealm cur so NewToken's IsCurrent + non-empty rlm.PkgPath()
// checks pass.
func newTestToken(name, symbol string, decimals int, id seqid.ID, rlm realm) (tok *Token, adm *PrivateLedger) {
func(cur realm) {
tok, adm = NewToken(name, symbol, decimals, id, cur)
}(cross(rlm))
return
}
func TestTestImpl(cur realm, t *testing.T) {
bank, _ := newTestToken("Dummy", "DUMMY", 4, 0, cur)
urequire.False(t, bank == nil, "dummy should not be nil")
}
func TestNewTokenAllowsDuplicateSymbolInSameRealm(cur realm, t *testing.T) {
holder := testutils.TestAddress("holder")
first, firstLedger := newTestToken("Same", "DUP", 6, 1, cur)
second, secondLedger := newTestToken("Same", "DUP", 6, 2, cur)
urequire.True(t, first.ID() != second.ID(), "duplicate symbols should not force duplicate IDs")
urequire.NoError(t, firstLedger.Mint(holder, 11))
urequire.NoError(t, secondLedger.Mint(holder, 22))
urequire.Equal(t, int64(11), first.BalanceOf(holder))
urequire.Equal(t, int64(22), second.BalanceOf(holder))
}
func TestNewTokenValidation(cur realm, t *testing.T) {
// Wrap NewToken to satisfy IsCurrent and pkgPath requirements,
// then validate name, symbol, and decimals.
mustPanic := func(name, sym string, dec int, want error, label string) {
t.Helper()
// newTestToken wraps NewToken in cross(...), so the panic from
// NewToken's validators crosses a realm boundary — use revive()
// (defer-recover doesn't see cross-realm panics).
r := revive(func() {
newTestToken(name, sym, dec, 0, cur)
})
if r == nil {
t.Errorf("%s: expected panic, got none", label)
return
}
if r != want {
t.Errorf("%s: expected %v, got %v", label, want, r)
}
}
// Empty name / symbol.
mustPanic("", "OK", 4, ErrInvalidName, "empty name")
mustPanic("Name", "", 4, ErrInvalidSymbol, "empty symbol")
// Length caps.
mustPanic(strings.Repeat("a", MaxNameLen+1), "OK", 4, ErrInvalidName, "name too long")
mustPanic("Name", strings.Repeat("A", MaxSymbolLen+1), 4, ErrInvalidSymbol, "symbol too long")
// Name control characters.
mustPanic("bad\x01name", "OK", 4, ErrInvalidName, "name with control char")
mustPanic("bad\nname", "OK", 4, ErrInvalidName, "name with newline")
// Symbol charset — disallowed delimiters and whitespace.
mustPanic("Name", "BA.D", 4, ErrInvalidSymbol, "symbol with dot")
mustPanic("Name", "BA/D", 4, ErrInvalidSymbol, "symbol with slash")
mustPanic("Name", "BA D", 4, ErrInvalidSymbol, "symbol with space")
mustPanic("Name", "BA\"D", 4, ErrInvalidSymbol, "symbol with quote")
// Decimals out of range.
mustPanic("Name", "OK", -1, ErrInvalidDecimals, "negative decimals")
mustPanic("Name", "OK", MaxDecimals+1, ErrInvalidDecimals, "decimals over cap")
// Boundary positives — should NOT panic.
tok, _ := newTestToken(strings.Repeat("a", MaxNameLen), strings.Repeat("A", MaxSymbolLen), MaxDecimals, 0, cur)
urequire.True(t, tok != nil, "boundary name+symbol+decimals should succeed")
// UTF-8 name with non-ASCII is allowed.
tok2, _ := newTestToken("Доллар", "RUB", 2, 0, cur)
urequire.True(t, tok2 != nil, "UTF-8 name should be allowed")
}
func TestToken(cur realm, t *testing.T) {
var (
alice = testutils.TestAddress("alice")
bob = testutils.TestAddress("bob")
carl = testutils.TestAddress("carl")
)
bank, adm := newTestToken("Dummy", "DUMMY", 6, 0, cur)
checkBalances := func(aliceEB, bobEB, carlEB int64) {
t.Helper()
exp := ufmt.Sprintf("alice=%d bob=%d carl=%d", aliceEB, bobEB, carlEB)
aliceGB := bank.BalanceOf(alice)
bobGB := bank.BalanceOf(bob)
carlGB := bank.BalanceOf(carl)
got := ufmt.Sprintf("alice=%d bob=%d carl=%d", aliceGB, bobGB, carlGB)
uassert.Equal(t, got, exp, "invalid balances")
}
checkAllowances := func(abEB, acEB, baEB, bcEB, caEB, cbEB int64) {
t.Helper()
exp := ufmt.Sprintf("ab=%d ac=%d ba=%d bc=%d ca=%d cb=%s", abEB, acEB, baEB, bcEB, caEB, cbEB)
abGB := bank.Allowance(alice, bob)
acGB := bank.Allowance(alice, carl)
baGB := bank.Allowance(bob, alice)
bcGB := bank.Allowance(bob, carl)
caGB := bank.Allowance(carl, alice)
cbGB := bank.Allowance(carl, bob)
got := ufmt.Sprintf("ab=%d ac=%d ba=%d bc=%d ca=%d cb=%s", abGB, acGB, baGB, bcGB, caGB, cbGB)
uassert.Equal(t, got, exp, "invalid allowances")
}
checkBalances(0, 0, 0)
checkAllowances(0, 0, 0, 0, 0, 0)
urequire.NoError(t, adm.Mint(alice, 1000))
urequire.NoError(t, adm.Mint(alice, 100))
checkBalances(1100, 0, 0)
checkAllowances(0, 0, 0, 0, 0, 0)
urequire.NoError(t, adm.Approve(alice, bob, 99999999))
checkBalances(1100, 0, 0)
checkAllowances(99999999, 0, 0, 0, 0, 0)
urequire.NoError(t, adm.Approve(alice, bob, 400))
checkBalances(1100, 0, 0)
checkAllowances(400, 0, 0, 0, 0, 0)
urequire.Error(t, adm.TransferFrom(alice, bob, carl, 100000000))
checkBalances(1100, 0, 0)
checkAllowances(400, 0, 0, 0, 0, 0)
urequire.NoError(t, adm.TransferFrom(alice, bob, carl, 100))
checkBalances(1000, 0, 100)
checkAllowances(300, 0, 0, 0, 0, 0)
urequire.Error(t, adm.SpendAllowance(alice, bob, 2000000))
checkBalances(1000, 0, 100)
checkAllowances(300, 0, 0, 0, 0, 0)
urequire.NoError(t, adm.SpendAllowance(alice, bob, 100))
checkBalances(1000, 0, 100)
checkAllowances(200, 0, 0, 0, 0, 0)
}
func TestMintOverflow(cur realm, t *testing.T) {
alice := testutils.TestAddress("alice")
bob := testutils.TestAddress("bob")
tok, adm := newTestToken("Dummy", "DUMMY", 6, 0, cur)
safeValue := int64(1 << 62)
urequire.NoError(t, adm.Mint(alice, safeValue))
urequire.Equal(t, tok.BalanceOf(alice), safeValue)
err := adm.Mint(bob, safeValue)
uassert.Error(t, err, "expected ErrMintOverflow")
}
func TestTransferFromAtomicity(cur realm, t *testing.T) {
var (
owner = testutils.TestAddress("owner")
spender = testutils.TestAddress("spender")
invalidRecipient = address("")
recipient = testutils.TestAddress("to")
)
token, admin := newTestToken("Test", "TEST", 6, 0, cur)
// owner has 100 tokens, spender has 50 allowance
initialBalance := int64(100)
initialAllowance := int64(50)
urequire.NoError(t, admin.Mint(owner, initialBalance))
urequire.NoError(t, admin.Approve(owner, spender, initialAllowance))
// transfer to an invalid address to force a transfer failure
transferAmount := int64(30)
err := admin.TransferFrom(owner, spender, invalidRecipient, transferAmount)
uassert.Error(t, err, "transfer should fail due to invalid address")
ownerBalance := token.BalanceOf(owner)
uassert.Equal(t, ownerBalance, initialBalance, "owner balance should remain unchanged")
// check if allowance was incorrectly reduced
remainingAllowance := token.Allowance(owner, spender)
uassert.Equal(t, remainingAllowance, initialAllowance,
"allowance should not be reduced when transfer fails")
// Self-transfers fail in Transfer after SpendAllowance. TransferFrom must
// reject them before it can mutate the allowance.
err = admin.TransferFrom(owner, spender, owner, transferAmount)
uassert.True(t, errors.Is(err, ErrCannotTransferToSelf), "self-transfer should fail")
uassert.Equal(t, initialBalance, token.BalanceOf(owner),
"owner balance should not change when self-transfer fails")
uassert.Equal(t, initialAllowance, token.Allowance(owner, spender),
"allowance should not be reduced when self-transfer fails")
// transfer all tokens
admin.Transfer(owner, recipient, 100)
remainingBalance := token.BalanceOf(owner)
uassert.Equal(t, remainingBalance, int64(0),
"balance should be zero")
err = admin.TransferFrom(owner, spender, recipient, transferAmount)
uassert.Error(t, err, "transfer should fail due to insufficient balance")
}
func TestMintUntilOverflow(cur realm, t *testing.T) {
alice := testutils.TestAddress("alice")
bob := testutils.TestAddress("bob")
tok, adm := newTestToken("Dummy", "DUMMY", 6, 0, cur)
tests := []struct {
name string
addr address
amount int64
expectedError error
expectedSupply int64
description string
}{
{
name: "mint negative value",
addr: alice,
amount: -1,
expectedError: ErrInvalidAmount,
expectedSupply: 0,
description: "minting a negative number should fail with ErrInvalidAmount",
},
{
name: "mint MaxInt64",
addr: alice,
amount: math.MaxInt64 - 1000,
expectedError: nil,
expectedSupply: math.MaxInt64 - 1000,
description: "minting almost MaxInt64 should succeed",
},
{
name: "mint small value",
addr: bob,
amount: 1000,
expectedError: nil,
expectedSupply: math.MaxInt64,
description: "minting a small value when close to MaxInt64 should succeed",
},
{
name: "mint value that would exceed MaxInt64",
addr: bob,
amount: 1,
expectedError: ErrMintOverflow,
expectedSupply: math.MaxInt64,
description: "minting any value when at MaxInt64 should fail with ErrMintOverflow",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := adm.Mint(tt.addr, tt.amount)
if tt.expectedError != nil {
uassert.Error(t, err, tt.description)
if !errors.Is(err, tt.expectedError) {
t.Errorf("expected error %v, got %v", tt.expectedError, err)
}
} else {
uassert.NoError(t, err, tt.description)
}
totalSupply := tok.TotalSupply()
uassert.Equal(t, totalSupply, tt.expectedSupply, "totalSupply should match expected value")
})
}
}
types.gno
package grc20
import (
"errors"
"gno.land/p/nt/avl/v0"
)
// Teller interface defines the methods that a GRC20 token must implement. It
// extends the TokenMetadata interface to include methods for managing token
// transfers, allowances, and querying balances.
//
// The Teller interface is designed to ensure that any token adhering to this
// standard provides a consistent API for interacting with fungible tokens.
//
// SECURITY: Transfer/Approve/TransferFrom take (_ int, rlm realm, ...), so
// handing a Teller value to untrusted code yields a capability token to
// whatever Transfer/Approve/TransferFrom impl that code dispatches into.
// Any /p/ or /r/ function that accepts a Teller as a parameter from external
// callers MUST type-assert against the canonical concrete type (*fnTeller)
// via IsCanonicalTeller and reject otherwise. An unexported-marker "seal"
// does NOT defend against this — see
// p/test/seal/filetests/z_seal_iface_embedding_filetest.gno
// for the realistic embedding-bypass attack. Reference impl for the
// canonical-allowlist pattern: p/jaekwon/allowancesender.
type Teller interface {
// Returns the name of the token.
GetName() string
// Returns the symbol of the token, usually a shorter version of the
// name.
GetSymbol() string
// Returns the decimals places of the token.
GetDecimals() int
// Returns the amount of tokens in existence.
TotalSupply() int64
// Returns the amount of tokens owned by `account`.
BalanceOf(account address) int64
// Moves `amount` tokens from the caller's account to `to`. rlm must
// be the caller's own captured cur — verified via rlm.IsCurrent().
//
// Returns an error if the operation failed.
Transfer(_ int, rlm realm, to address, amount int64) error
// Returns the remaining number of tokens that `spender` will be
// allowed to spend on behalf of `owner` through {transferFrom}. This is
// zero by default.
//
// This value changes when {approve} or {transferFrom} are called.
Allowance(owner, spender address) int64
// Sets `amount` as the allowance of `spender` over the caller's tokens.
//
// Returns an error if the operation failed.
//
// IMPORTANT: Beware that changing an allowance with this method brings
// the risk that someone may use both the old and the new allowance by
// unfortunate transaction ordering. One possible solution to mitigate
// this race condition is to first reduce the spender's allowance to 0
// and set the desired value afterwards:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
Approve(_ int, rlm realm, spender address, amount int64) error
// Moves `amount` tokens from `from` to `to` using the
// allowance mechanism. `amount` is then deducted from the caller's
// allowance.
//
// Returns an error if the operation failed.
TransferFrom(_ int, rlm realm, from, to address, amount int64) error
}
// Token represents a fungible token with an ID, name, symbol, and a certain
// number of decimal places. It maintains a ledger for tracking balances and
// allowances of addresses.
//
// The Token struct provides methods for retrieving token metadata, such as the
// name, symbol, and decimals, as well as methods for interacting with the
// ledger, including checking balances and allowances.
type Token struct {
// Identifier precomputed in NewToken to make ID() a cheap field read.
id string
// Name of the token (e.g., "Dummy Token").
name string
// Symbol of the token (e.g., "DUMMY").
symbol string
// Number of decimal places used for the token's precision.
decimals int
// Pointer to the PrivateLedger that manages balances and allowances.
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
}
// PrivateLedger is a struct that holds the balances and allowances for the
// token. It provides administrative functions for minting, burning,
// transferring tokens, and managing allowances.
//
// The PrivateLedger is not safe to expose publicly, as it contains sensitive
// information regarding token balances and allowances, and allows direct,
// unrestricted access to all administrative functions.
type PrivateLedger struct {
// Total supply of the token managed by this ledger.
totalSupply int64
// chain.Address -> int64
balances avl.Tree
// owner.(chain.Address)+":"+spender.(chain.Address)) -> int64
allowances avl.Tree
// Pointer to the associated Token struct
token *Token
}
var (
ErrInsufficientBalance = errors.New("insufficient balance")
ErrInsufficientAllowance = errors.New("insufficient allowance")
ErrInvalidAddress = errors.New("invalid address")
ErrCannotTransferToSelf = errors.New("cannot send transfer to self")
ErrReadonly = errors.New("banker is readonly")
ErrRestrictedTokenOwner = errors.New("restricted to bank owner")
ErrMintOverflow = errors.New("mint overflow")
ErrInvalidAmount = errors.New("invalid amount")
ErrSpoofedRealm = errors.New("rlm does not match the current crossing frame")
ErrForeignCallerTeller = errors.New("caller teller is confined to the token's own 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_-])")
ErrInvalidDecimals = errors.New("invalid decimals (must be 0..18)")
)
// Construction limits. Symbol is restricted to the same charset as
// grc20reg.validateSlug because it is included in Token.ID(), which is
// emitted in events and frequently used as a registry slug; banning `.` `/`
// and whitespace here prevents downstream parsers from being fooled by
// ambiguous IDs. Name is for display only and allows any valid UTF-8 except
// control characters.
const (
MaxNameLen = 64
MaxSymbolLen = 11
MaxDecimals = 18
)
const (
NewTokenEvent = "NewToken"
MintEvent = "Mint"
BurnEvent = "Burn"
TransferEvent = "Transfer"
ApprovalEvent = "Approval"
)
type fnTeller struct {
accountFn func(_ int, rlm realm) address
// homeGuard marks a frame-relative teller (PrivateLedger.CallerTeller),
// whose actor is resolved from the invoking frame. Such a teller is only
// meaningful in the token's own realm and is refused anywhere else, so
// exporting the value cannot hand out a spend capability.
homeGuard bool
*Token
}
var _ Teller = (*fnTeller)(nil)
// IsCanonicalTeller reports whether t is the canonical *fnTeller produced by
// Token.CallerTeller / RealmTeller / RealmSubTeller / ReadonlyTeller /
// ImpersonateTeller. Use this at any public entry point that accepts a
// Teller from an external caller before invoking its methods.
//
// Foreign types — including embedding-based wrappers like
// `type Evil struct { grc20.Teller }` — are rejected because type
// assertions are nominal: *Evil is not *fnTeller, regardless of method
// promotion. This is the reliable defense; the unexported-marker "seal"
// pattern is bypassable via embedding (see
// p/test/seal/filetests/z_seal_iface_embedding_filetest.gno).
//
// Mirrors the precedent of chain/banker.IsCanonical and
// p/jaekwon/allowancesender's canonical-impl check.
func IsCanonicalTeller(t Teller) bool {
_, ok := t.(*fnTeller)
return ok
}