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

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

erc20.gno

// Package erc20 implements MiniToken, a minimal fungible token modeled on the
// Solidity ERC-20 idea, ported to gno.land (gno 0.9 / sapphire).
//
// State is package-level and persistent. All state-mutating exported functions
// are crossing functions (they take `cur realm` as the first parameter) per the
// gno 0.9 interrealm convention, and identify the caller via
// cur.Previous().Address() after checking cur.IsCurrent().
package erc20

import (
	"errors"
	"sort"
	"strconv"
	"strings"
)

const (
	name   = "MiniToken"
	symbol = "MINI"
)

var (
	// balances maps holder address -> token balance.
	balances = map[address]uint64{}
	// allowances[owner][spender] = amount the spender may pull from owner.
	allowances = map[address]map[address]uint64{}
	// totalSupply is the sum of all balances.
	totalSupply uint64
)

var (
	errZeroAddress  = errors.New("erc20: zero address")
	errInsufficient = errors.New("erc20: insufficient balance")
	errAllowanceLow = errors.New("erc20: insufficient allowance")
	errOverflow     = errors.New("erc20: supply overflow")
	errSpoofedRealm = errors.New("erc20: spoofed realm")
	errNotUser      = errors.New("erc20: caller is not a user account")
)

// caller returns the immediate caller's address for a crossing function.
// It enforces the gno 0.9 authentication primitive: cur must be the live
// crossing frame before its Previous() is trusted.
func caller(cur realm) address {
	if !cur.IsCurrent() {
		panic(errSpoofedRealm)
	}
	prev := cur.Previous()
	if !prev.IsUser() {
		panic(errNotUser)
	}
	return prev.Address()
}

// Mint creates `amount` new tokens and credits them to `to`, increasing the
// total supply. Crossing function.
func Mint(cur realm, to address, amount uint64) {
	_ = caller(cur) // authenticate the crossing frame; anyone may mint in this demo
	if !to.IsValid() {
		panic(errZeroAddress)
	}
	if amount == 0 {
		return
	}
	if totalSupply+amount < totalSupply {
		panic(errOverflow)
	}
	totalSupply += amount
	balances[to] += amount
}

// Transfer moves `amount` tokens from the caller to `to`. Crossing function.
func Transfer(cur realm, to address, amount uint64) {
	from := caller(cur)
	if !to.IsValid() {
		panic(errZeroAddress)
	}
	if err := transfer(from, to, amount); err != nil {
		panic(err)
	}
}

// Approve authorizes `spender` to pull up to `amount` tokens from the caller.
// Crossing function.
func Approve(cur realm, spender address, amount uint64) {
	owner := caller(cur)
	if !spender.IsValid() {
		panic(errZeroAddress)
	}
	m := allowances[owner]
	if m == nil {
		m = map[address]uint64{}
		allowances[owner] = m
	}
	m[spender] = amount
}

// TransferFrom moves `amount` tokens from `from` to `to`, spending the caller's
// allowance granted by `from`. Crossing function.
func TransferFrom(cur realm, from, to address, amount uint64) {
	spender := caller(cur)
	if !from.IsValid() || !to.IsValid() {
		panic(errZeroAddress)
	}
	allowed := allowances[from][spender]
	if allowed < amount {
		panic(errAllowanceLow)
	}
	if err := transfer(from, to, amount); err != nil {
		panic(err)
	}
	allowances[from][spender] = allowed - amount
}

// transfer is the internal, non-crossing balance mover. Pure logic on package
// state; returns an error rather than panicking so callers control reverts.
func transfer(from, to address, amount uint64) error {
	if amount == 0 {
		return nil
	}
	if balances[from] < amount {
		return errInsufficient
	}
	balances[from] -= amount
	balances[to] += amount
	return nil
}

// BalanceOf returns the token balance of `holder`. Read-only, non-crossing.
func BalanceOf(holder address) uint64 {
	return balances[holder]
}

// Allowance returns how much `spender` may still pull from `owner`.
func Allowance(owner, spender address) uint64 {
	return allowances[owner][spender]
}

// TotalSupply returns the total number of tokens in existence.
func TotalSupply() uint64 {
	return totalSupply
}

// Name returns the token name.
func Name() string { return name }

// Symbol returns the token symbol.
func Symbol() string { return symbol }

// Render produces the gnoweb Markdown view of the token: metadata plus a
// deterministically-ordered table of non-zero balances. Render is NOT a
// crossing function (no `cur realm` parameter).
func Render(path string) string {
	var b strings.Builder

	b.WriteString("# " + name + " (" + symbol + ")\n\n")
	b.WriteString("A minimal ERC-20-style fungible token on gno.land.\n\n")
	b.WriteString("- **Name:** " + name + "\n")
	b.WriteString("- **Symbol:** " + symbol + "\n")
	b.WriteString("- **Total supply:** " + strconv.FormatUint(totalSupply, 10) + "\n\n")

	// Collect and sort holder addresses for deterministic output. Map iteration
	// order is not a stable contract, so we sort the string keys (gno's sort
	// package has no generic Slice; Strings is the deterministic primitive).
	keys := make([]string, 0, len(balances))
	byKey := make(map[string]uint64, len(balances))
	for addr, bal := range balances {
		if bal == 0 {
			continue
		}
		s := addr.String()
		keys = append(keys, s)
		byKey[s] = bal
	}
	sort.Strings(keys)

	b.WriteString("## Balances\n\n")
	if len(keys) == 0 {
		b.WriteString("_No holders yet — call `Mint` to create tokens._\n")
		return b.String()
	}

	b.WriteString("| Address | Amount |\n")
	b.WriteString("| --- | ---: |\n")
	for _, k := range keys {
		b.WriteString("| `" + k + "` | " +
			strconv.FormatUint(byKey[k], 10) + " |\n")
	}

	return b.String()
}

erc20_test.gno

package erc20

import (
	"strings"
	"testing"

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

// Fixed test addresses. testutils.TestAddress derives real, valid-length
// addresses; literal strings would fail address.IsValid() and trip the realm's
// zero-address guard.
var (
	alice   = testutils.TestAddress("alice")
	bob     = testutils.TestAddress("bob")
	spender = testutils.TestAddress("spender")
	dest    = testutils.TestAddress("dest")
)

// reset clears package state between tests so cases stay independent.
func reset() {
	balances = map[address]uint64{}
	allowances = map[address]map[address]uint64{}
	totalSupply = 0
}

// TestMintAndTransfer mints to alice, then transfers alice -> bob.
func TestMintAndTransfer(cur realm, t *testing.T) {
	reset()

	testing.SetRealm(testing.NewUserRealm(alice))
	Mint(cross(cur), alice, 1000)

	if got := TotalSupply(); got != 1000 {
		t.Fatalf("total supply = %d, want 1000", got)
	}
	if got := BalanceOf(alice); got != 1000 {
		t.Fatalf("alice balance = %d, want 1000", got)
	}

	testing.SetRealm(testing.NewUserRealm(alice))
	Transfer(cross(cur), bob, 400)

	if got := BalanceOf(alice); got != 600 {
		t.Errorf("alice balance = %d, want 600", got)
	}
	if got := BalanceOf(bob); got != 400 {
		t.Errorf("bob balance = %d, want 400", got)
	}
	if got := TotalSupply(); got != 1000 {
		t.Errorf("total supply changed on transfer: %d, want 1000", got)
	}
}

// TestApproveAndTransferFrom exercises the allowance path.
func TestApproveAndTransferFrom(cur realm, t *testing.T) {
	reset()

	testing.SetRealm(testing.NewUserRealm(alice))
	Mint(cross(cur), alice, 500)

	testing.SetRealm(testing.NewUserRealm(alice))
	Approve(cross(cur), spender, 300)
	if got := Allowance(alice, spender); got != 300 {
		t.Fatalf("allowance = %d, want 300", got)
	}

	testing.SetRealm(testing.NewUserRealm(spender))
	TransferFrom(cross(cur), alice, dest, 200)

	if got := BalanceOf(alice); got != 300 {
		t.Errorf("owner balance = %d, want 300", got)
	}
	if got := BalanceOf(dest); got != 200 {
		t.Errorf("dest balance = %d, want 200", got)
	}
	if got := Allowance(alice, spender); got != 100 {
		t.Errorf("remaining allowance = %d, want 100", got)
	}
}

// TestTransferInsufficientPanics asserts an over-transfer reverts.
func TestTransferInsufficientPanics(cur realm, t *testing.T) {
	reset()

	testing.SetRealm(testing.NewUserRealm(alice))
	Mint(cross(cur), alice, 10)

	// Aborts from a cross(cur) call cannot be caught by a plain recover();
	// assert on the abort message instead.
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsWithMessage(t, cur, "erc20: insufficient balance", func() {
		Transfer(cross(cur), bob, 100) // more than balance -> panic
	})
}

// TestRenderContainsMetadata checks the Markdown view exposes name/symbol/supply.
func TestRenderContainsMetadata(cur realm, t *testing.T) {
	reset()

	testing.SetRealm(testing.NewUserRealm(alice))
	Mint(cross(cur), alice, 42)

	out := Render("")
	for _, want := range []string{"MiniToken", "MINI", "Total supply", "42"} {
		if !strings.Contains(out, want) {
			t.Errorf("render output missing %q\n%s", want, out)
		}
	}
}

gnomod.toml

module = "gno.land/r/nym-moultest123/x/daily/erc20/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186407
  max_deposit = "5000000ugnot"