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

gnomod.toml

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

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186411
  max_deposit = "13000000ugnot"

render.gno

package grc20wrapdemo

import (
	"gno.land/p/nt/ufmt/v0"
)

func Render(path string) string {
	if path == "" {
		return renderIndex()
	}
	return renderOne(path)
}

func renderIndex() string {
	s := "# GRC20 wrapper factory\n\n"
	s += "Wrap any token registered in [grc20reg](/r/nt/grc20reg/v0) into a new one "
	s += "with a different personality, or fuse two into one. Permissionless: "
	s += "no allowlist, no owner, no authority over anybody's balance.\n\n"
	s += ufmt.Sprintf("Escrow account to approve: `%s`\n\n", home.String())

	s += "## Modes\n\n"
	s += "| mode | what the wrapped token does |\n"
	s += "|---|---|\n"
	s += "| `plain` | 1:1 custody receipt |\n"
	s += "| `kilo` | 1 underlying unit becomes 1000 wrapped, +3 decimals |\n"
	s += "| `soulbound` | wrap and unwrap freely, never transferable |\n"
	s += "| `pool` | shares in the escrow; `Donate` pays every holder at once |\n"
	s += "| `sticky` | `pool` plus a 1% exit fee, left behind for whoever stays |\n"
	s += "| `fusion` | one meta-token backed by a fixed bundle of two others |\n"

	s += "\n## Issued here\n\n"
	if len(created) == 0 {
		s += "Nothing yet. Be the first.\n"
	} else {
		s += "| symbol | mode | backing | supply | registry key |\n"
		s += "|---|---|---|---|---|\n"
		for _, sym := range created {
			e := must(sym)
			s += ufmt.Sprintf("| [%s](/r/nym-moultest123/x/grc20wrapdemo/v0:%s) | %s | %s | %d | `%s` |\n",
				e.symbol, e.symbol, e.mode, e.backing(), e.token().TotalSupply(), e.key)
		}
	}

	s += "\n## Try it\n\n"
	s += "Claim play money from [the faucet](/r/nym-moultest123/x/grc20faucet/v0), let this realm\n"
	s += "spend it, then wrap:\n\n"
	s += "```\n"
	s += "# 1. get RED and BLUE\n"
	s += "maketx call -pkgpath gno.land/r/nym-moultest123/x/grc20faucet/v0 -func Claim\n\n"
	s += "# 2. let this realm pull your RED\n"
	s += "maketx call -pkgpath gno.land/r/nym-moultest123/x/grc20faucet/v0 -func Approve \\\n"
	s += ufmt.Sprintf("  -args RED -args %s -args 1000000\n\n", home.String())
	s += "# 3. create a pool wrapper over RED, then deposit into it\n"
	s += "maketx call -pkgpath gno.land/r/nym-moultest123/x/grc20wrapdemo/v0 -func NewWrapper \\\n"
	s += "  -args gno.land/r/nym-moultest123/x/grc20faucet/v0.RED -args pool -args pRED\n"
	s += "maketx call -pkgpath gno.land/r/nym-moultest123/x/grc20wrapdemo/v0 -func Deposit \\\n"
	s += "  -args pRED -args 500000\n"
	s += "```\n\n"
	s += "Built on [p/moul/x/grc20wrap](/p/nym-moultest123/x/grc20wrap/v0).\n"
	return s
}

func renderOne(symbol string) string {
	e := byName.Get(symbol)
	if e == nil {
		return "# 404\n\nThis realm has not issued `" + symbol + "`.\n"
	}
	en := e.(*entry)

	s := ufmt.Sprintf("# %s\n\n", en.symbol)
	if en.vault != nil {
		s += en.vault.Summary()
	} else {
		s += en.basket.Summary()
	}
	s += ufmt.Sprintf("\n- mode: `%s`\n", en.mode)
	s += ufmt.Sprintf("- registry key: `%s`\n", en.key)
	s += ufmt.Sprintf("- created by: `%s` at block %d\n", en.creator.String(), en.height)
	s += "\n[back to the index](/r/nym-moultest123/x/grc20wrapdemo/v0)\n"
	return s
}

// backing names what an entry is redeemable for, for the index table.
func (e *entry) backing() string {
	if e.vault != nil {
		return e.vault.Underlying().GetSymbol()
	}
	out := ""
	for i := 0; i < e.basket.Legs(); i++ {
		tok, per, _ := e.basket.Leg(i)
		if i > 0 {
			out += " + "
		}
		out += ufmt.Sprintf("%dx%s", per, tok.GetSymbol())
	}
	return out
}

wrapdemo.gno

// Package grc20wrapdemo is a permissionless wrapper factory for GRC20 tokens.
//
// Point it at any token registered in gno.land/r/nt/grc20reg/v0 and it issues a
// new one backed by it, with a personality you pick from a list. Point it at two
// and it issues a meta-token backed by both. Nothing is whitelisted, nothing is
// owned, and the realm never gains authority over anybody's balance: every
// deposit is pulled with an allowance the holder granted to this realm's address.
//
// The five wrapper modes, all from gno.land/p/nym-moultest123/x/grc20wrap/v0:
//
//	plain      1:1 custody. A receipt. The boring one that proves the rest works.
//	kilo       1 underlying unit becomes 1000 wrapped ones, +3 decimals.
//	soulbound  wrap and unwrap freely, but the wrapped token never changes hands.
//	pool       shares in the escrow: Donate raises what every share redeems for.
//	sticky     pool, plus a 1% exit fee that stays behind for whoever holds on.
//
// And one fusion mode: NewFusion bundles two registered tokens at a fixed
// proportion into a single meta-token, redeemable back into both.
//
// # Wrapping a wrapper
//
// Every token this realm issues is itself registered in grc20reg, so its key can
// be fed straight back into NewWrapper or NewFusion. A pool over a kilo over a
// plain wrap of RED is legal, works, and is a good way to see how thin the
// abstraction really is.
//
// # The one thing a caller must do first
//
// Approve this realm's address on the underlying token, through THAT token's own
// realm. Home() prints the address. Without it every Deposit fails with
// "insufficient allowance", which is the system working.
//
// Play money to try it on: gno.land/r/nym-moultest123/x/grc20faucet/v0.
package grc20wrapdemo

import (
	"chain/runtime"

	"gno.land/p/nym-moultest123/x/grc20wrap/v0"
	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/grc20/v0"
	"gno.land/p/nt/seqid/v0"
	"gno.land/p/nt/ufmt/v0"
	"gno.land/r/nt/grc20reg/v0"
)

// entry is one issued token: either a wrapper over a single underlying, or a
// fusion over several. Exactly one of vault/basket is set.
type entry struct {
	symbol  string
	mode    string
	key     string // grc20reg key of the issued token
	vault   *grc20wrap.Vault
	basket  *grc20wrap.Basket
	creator address
	height  int64
}

var (
	ids     seqid.ID
	byName  = avl.NewTree() // symbol -> *entry
	created []string        // symbols, in creation order, for a stable Render
	home    address         // this realm's address: the escrow account
)

func init(cur realm) {
	home = cur.Address()
}

// Home is the address to approve on an underlying token before depositing. It
// is where every escrow this realm holds actually sits.
func Home() address { return home }

// NewWrapper issues a token wrapping `tokenKey`, a key in grc20reg, under the
// given mode, and registers it. It returns the new token's own registry key.
//
// `symbol` is yours to choose, must be unique in this realm, and follows the
// GRC20 rules: 1 to 11 characters of [A-Za-z0-9_-].
func NewWrapper(cur realm, tokenKey, mode, symbol string) string {
	who := caller(cur)
	under := grc20reg.MustGet(tokenKey)
	requireFree(symbol)

	pol, extraDecimals := modePolicy(mode)
	decimals := under.GetDecimals() + extraDecimals
	if decimals > 18 {
		panic(ufmt.Sprintf("%s already has %d decimals; mode %q would need %d, over the GRC20 limit of 18",
			under.GetSymbol(), under.GetDecimals(), mode, decimals))
	}
	name := ufmt.Sprintf("%s (%s wrap of %s)", symbol, mode, under.GetSymbol())

	v := grc20wrap.NewVault(under, pol, name, symbol, decimals, ids.Next(), cur)
	key := grc20reg.Register(cross(cur), v.Token(), "")
	record(&entry{
		symbol:  symbol,
		mode:    mode,
		key:     key,
		vault:   v,
		creator: who,
		height:  runtime.ChainHeight(),
	})
	return key
}

// NewFusion issues a meta-token backed by two registered tokens at a fixed
// proportion: one smallest unit of the meta-token is always worth `perA`
// smallest units of A plus `perB` of B. It returns the new token's registry key.
//
// The proportion never changes, and the meta-token is minted and burned only
// against the real thing, so it cannot drift from its backing or be arbitraged.
// What it can do is make the pair one transferable object.
func NewFusion(cur realm, keyA string, perA int64, keyB string, perB int64, symbol string) string {
	who := caller(cur)
	a := grc20reg.MustGet(keyA)
	b := grc20reg.MustGet(keyB)
	requireFree(symbol)

	decimals := a.GetDecimals()
	if b.GetDecimals() > decimals {
		decimals = b.GetDecimals()
	}
	name := ufmt.Sprintf("%s (%s+%s fusion)", symbol, a.GetSymbol(), b.GetSymbol())

	bk := grc20wrap.NewBasket(
		[]*grc20.Token{a, b},
		[]int64{perA, perB},
		name, symbol, decimals, ids.Next(), cur,
	)
	key := grc20reg.Register(cross(cur), bk.Token(), "")
	record(&entry{
		symbol:  symbol,
		mode:    "fusion",
		key:     key,
		basket:  bk,
		creator: who,
		height:  runtime.ChainHeight(),
	})
	return key
}

// Deposit escrows `amount` of the underlying and mints `symbol` to the caller.
// It returns how much was minted, which is not `amount` unless the mode is
// plain. Approve Home() on the underlying first.
func Deposit(cur realm, symbol string, amount int64) int64 {
	who := caller(cur)
	out, err := mustVault(symbol).Wrap(0, cur, who, amount)
	checkErr(err)
	return out
}

// Withdraw burns `amount` of `symbol` and returns the underlying to the caller.
// It returns how much came back.
func Withdraw(cur realm, symbol string, amount int64) int64 {
	who := caller(cur)
	out, err := mustVault(symbol).Unwrap(0, cur, who, amount)
	checkErr(err)
	return out
}

// Donate escrows `amount` of the underlying for `symbol` and mints nothing.
//
// Under a pool or sticky mode this is a gift to every current holder at once,
// and it is irreversible: there is no share to redeem it with. Under any other
// mode it is a gift to nobody, since the rate ignores the escrow.
func Donate(cur realm, symbol string, amount int64) {
	who := caller(cur)
	checkErr(mustVault(symbol).Donate(0, cur, who, amount))
}

// Fuse escrows every leg of `symbol` and mints `units` of it to the caller.
// Approve Home() on BOTH legs first.
func Fuse(cur realm, symbol string, units int64) {
	who := caller(cur)
	checkErr(mustBasket(symbol).Fuse(0, cur, who, units))
}

// Defuse burns `units` of `symbol` and returns every leg to the caller.
func Defuse(cur realm, symbol string, units int64) {
	who := caller(cur)
	checkErr(mustBasket(symbol).Defuse(0, cur, who, units))
}

// Transfer moves the caller's own units of `symbol`. A soulbound wrapper
// refuses here, and nowhere else.
func Transfer(cur realm, symbol string, to address, amount int64) {
	who := caller(cur)
	e := must(symbol)
	if e.vault != nil {
		checkErr(e.vault.Move(who, to, amount))
		return
	}
	checkErr(e.basket.Move(who, to, amount))
}

// Approve lets `spender` draw `amount` of `symbol` from the caller's balance.
func Approve(cur realm, symbol string, spender address, amount int64) {
	who := caller(cur)
	e := must(symbol)
	if e.vault != nil {
		checkErr(e.vault.Allow(who, spender, amount))
		return
	}
	checkErr(e.basket.Allow(who, spender, amount))
}

// TransferFrom spends an allowance the caller was granted on `symbol`.
func TransferFrom(cur realm, symbol string, from, to address, amount int64) {
	who := caller(cur)
	e := must(symbol)
	if e.vault != nil {
		checkErr(e.vault.MoveFrom(who, from, to, amount))
		return
	}
	checkErr(e.basket.MoveFrom(who, from, to, amount))
}

// Key returns the grc20reg key of the token this realm issued as `symbol`.
func Key(symbol string) string { return must(symbol).key }

// TotalSupply returns how much of `symbol` is outstanding.
func TotalSupply(symbol string) int64 { return must(symbol).token().TotalSupply() }

// BalanceOf returns `owner`'s balance of `symbol`.
func BalanceOf(symbol string, owner address) int64 {
	return must(symbol).token().BalanceOf(owner)
}

// Allowance returns what `owner` let `spender` draw of `symbol`.
func Allowance(symbol string, owner, spender address) int64 {
	return must(symbol).token().Allowance(owner, spender)
}

// Escrow returns the underlying escrowed behind a wrapper.
func Escrow(symbol string) int64 { return mustVault(symbol).Held() }

// Legs returns how many components a fusion has.
func Legs(symbol string) int { return mustBasket(symbol).Legs() }

// Leg describes the i-th component of a fusion: its symbol, the units escrowed
// per meta unit, and the units escrowed so far.
func Leg(symbol string, i int) (string, int64, int64) {
	tok, per, held := mustBasket(symbol).Leg(i)
	return tok.GetSymbol(), per, held
}

// Count is how many tokens this realm has issued.
func Count() int { return len(created) }

// internals
//

// modePolicy maps a mode name to its policy and to the extra decimals the
// wrapped token needs to represent the same value.
func modePolicy(mode string) (grc20wrap.Policy, int) {
	switch mode {
	case "plain":
		return grc20wrap.OneToOne{}, 0
	case "kilo":
		return grc20wrap.Ratio{Num: 1_000, Den: 1}, 3
	case "soulbound":
		return grc20wrap.Soulbound{}, 0
	case "pool":
		return grc20wrap.Pool{}, 0
	case "sticky":
		return grc20wrap.Fee{Base: grc20wrap.Pool{}, UnwrapBPS: 100}, 0
	}
	panic("unknown mode " + mode + " (plain, kilo, soulbound, pool, sticky)")
}

func (e *entry) token() *grc20.Token {
	if e.vault != nil {
		return e.vault.Token()
	}
	return e.basket.Token()
}

func record(e *entry) {
	byName.Set(e.symbol, e)
	created = append(created, e.symbol)
}

func requireFree(symbol string) {
	if byName.Has(symbol) {
		panic("symbol " + symbol + " is already issued by this realm")
	}
}

func must(symbol string) *entry {
	e := byName.Get(symbol)
	if e == nil {
		panic("this realm has not issued " + symbol)
	}
	return e.(*entry)
}

func mustVault(symbol string) *grc20wrap.Vault {
	e := must(symbol)
	if e.vault == nil {
		panic(symbol + " is a fusion; use Fuse and Defuse")
	}
	return e.vault
}

func mustBasket(symbol string) *grc20wrap.Basket {
	e := must(symbol)
	if e.basket == nil {
		panic(symbol + " is a wrapper; use Deposit and Withdraw")
	}
	return e.basket
}

// caller is the account or realm that crossed into this one. Every deposit is
// escrowed from, and every mint credited to, exactly this address.
func caller(cur realm) address {
	if !cur.IsCurrent() {
		panic("grc20wrapdemo: stale realm token")
	}
	return cur.Previous().Address()
}

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

wrapdemo_test.gno

package grc20wrapdemo

import (
	"strings"
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
	faucet "gno.land/r/nym-moultest123/x/grc20faucet/v0"
)

// Realm state carries over between test functions, but the block height does
// not: every test starts from the same height. The faucet's per-account
// cooldown would therefore fire on the second test to reuse an account, so each
// test claims with its own. TestFaucetCooldown covers the cooldown itself.
func fund(cur realm, t *testing.T, name string) address {
	t.Helper()
	who := testutils.TestAddress(name)
	testing.SetRealm(testing.NewUserRealm(who))
	faucet.Claim(cross(cur))
	faucet.Approve(cross(cur), "RED", Home(), faucet.ClaimAmount)
	faucet.Approve(cross(cur), "BLUE", Home(), faucet.ClaimAmount)
	return who
}

// testing.SetRealm only governs crossing calls made from the frame that called
// it: put it in a helper with no crossing call of its own and it is silently
// ignored, and the caller stays whoever it was. fund() gets away with it
// because it crosses into the faucet right after; switching accounts mid-test
// has to be written inline, which is why there is no act() helper here.

// The plain mode is the baseline: it proves custody actually crosses a realm
// boundary. The RED never belonged to this realm, and it can only ever take
// what the faucet's Approve handed over.
func TestPlainWrapperRoundTrip(cur realm, t *testing.T) {
	alice := fund(cur, t, "w-alice")
	before := faucet.BalanceOf("RED", alice)

	key := NewWrapper(cross(cur), faucet.RedKey, "plain", "wRED")
	uassert.True(t, strings.HasSuffix(key, ".wRED"), "registered under its own symbol: "+key)

	minted := Deposit(cross(cur), "wRED", 400_000)
	uassert.Equal(t, int64(400_000), minted)
	uassert.Equal(t, int64(400_000), BalanceOf("wRED", alice))
	uassert.Equal(t, int64(400_000), Escrow("wRED"))
	uassert.Equal(t, before-400_000, faucet.BalanceOf("RED", alice))
	// The escrow really sits at this realm's address, in the faucet's ledger.
	uassert.Equal(t, int64(400_000), faucet.BalanceOf("RED", Home()))

	back := Withdraw(cross(cur), "wRED", 150_000)
	uassert.Equal(t, int64(150_000), back)
	uassert.Equal(t, int64(250_000), TotalSupply("wRED"))
	uassert.Equal(t, before-250_000, faucet.BalanceOf("RED", alice))
}

// Depositing without an allowance is the default state of the world, and it
// fails. This realm holds no standing authority over anybody's balance.
func TestDepositNeedsAnAllowance(cur realm, t *testing.T) {
	fund(cur, t, "noallow")
	NewWrapper(cross(cur), faucet.RedKey, "plain", "noallow")

	// Revoke what fund() granted.
	faucet.Approve(cross(cur), "RED", Home(), 0)
	uassert.AbortsContains(t, cur, "insufficient allowance", func() {
		Deposit(cross(cur), "noallow", 1)
	})
	uassert.Equal(t, int64(0), TotalSupply("noallow"))
}

// kilo re-denominates a token whose own realm will never redeploy for it.
func TestKiloWrapperAddsThreeDecimals(cur realm, t *testing.T) {
	fund(cur, t, "kilo")
	NewWrapper(cross(cur), faucet.RedKey, "kilo", "kRED")

	minted := Deposit(cross(cur), "kRED", 1_000)
	uassert.Equal(t, int64(1_000_000), minted)
	uassert.Equal(t, int64(1_000), Escrow("kRED"))

	back := Withdraw(cross(cur), "kRED", 999_000)
	uassert.Equal(t, int64(999), back)
	// 999 wrapped units cannot buy back a whole underlying one, so the
	// redemption is refused rather than burning them for nothing.
	uassert.AbortsContains(t, cur, "rounds to zero", func() {
		Withdraw(cross(cur), "kRED", 999)
	})
}

func TestSoulboundWrapperRefusesTransfer(cur realm, t *testing.T) {
	fund(cur, t, "soul")
	bob := testutils.TestAddress("soul-bob")
	NewWrapper(cross(cur), faucet.RedKey, "soulbound", "sRED")
	Deposit(cross(cur), "sRED", 300_000)

	uassert.AbortsContains(t, cur, "soulbound", func() {
		Transfer(cross(cur), "sRED", bob, 1)
	})
	uassert.Equal(t, int64(0), BalanceOf("sRED", bob))

	// The exit stays open: unwrap, and the RED moves as freely as ever.
	back := Withdraw(cross(cur), "sRED", 300_000)
	uassert.Equal(t, int64(300_000), back)
	uassert.Equal(t, int64(0), TotalSupply("sRED"))
}

// Pool: a donation is shared by whoever is holding, and the donor can never
// take it back out.
func TestPoolWrapperSharesDonations(cur realm, t *testing.T) {
	alice := fund(cur, t, "pool-a")
	NewWrapper(cross(cur), faucet.RedKey, "pool", "pRED")
	uassert.Equal(t, int64(100_000), Deposit(cross(cur), "pRED", 100_000))

	bob := fund(cur, t, "pool-b")
	Donate(cross(cur), "pRED", 100_000)
	uassert.Equal(t, int64(200_000), Escrow("pRED"))
	uassert.Equal(t, int64(100_000), TotalSupply("pRED"))
	uassert.Equal(t, int64(0), BalanceOf("pRED", bob)) // a donation mints nothing

	// Buying in afterwards costs twice as much per share.
	uassert.Equal(t, int64(50_000), Deposit(cross(cur), "pRED", 100_000))

	// alice walks away with double what she put in.
	testing.SetRealm(testing.NewUserRealm(alice))
	redBefore := faucet.BalanceOf("RED", alice)
	uassert.Equal(t, int64(200_000), Withdraw(cross(cur), "pRED", 100_000))
	uassert.Equal(t, redBefore+200_000, faucet.BalanceOf("RED", alice))

	// And bob gets back exactly the 100_000 he deposited: his own donation
	// was to the holders, and by then that was alice.
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.Equal(t, int64(100_000), Withdraw(cross(cur), "pRED", 50_000))
	uassert.Equal(t, int64(0), Escrow("pRED"))
}

// Sticky: the 1% exit fee is collected by nobody, it is left in the pool, so
// whoever stays longest ends up with it.
func TestStickyWrapperChargesOnTheWayOut(cur realm, t *testing.T) {
	alice := fund(cur, t, "stick-a")
	NewWrapper(cross(cur), faucet.RedKey, "sticky", "fRED")
	Deposit(cross(cur), "fRED", 500_000)

	bob := fund(cur, t, "stick-b")
	Deposit(cross(cur), "fRED", 500_000)
	uassert.Equal(t, int64(1_000_000), TotalSupply("fRED"))

	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.Equal(t, int64(495_000), Withdraw(cross(cur), "fRED", 500_000))

	// The 5_000 alice paid on the way out now backs bob's shares.
	uassert.Equal(t, int64(505_000), Escrow("fRED"))
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.Equal(t, int64(499_950), Withdraw(cross(cur), "fRED", 500_000))
}

// Fusion: one token backed by a fixed bundle of two, and nothing else.
func TestFusionOfRedAndBlue(cur realm, t *testing.T) {
	alice := fund(cur, t, "fuse-a")
	bob := testutils.TestAddress("fuse-b")

	key := NewFusion(cross(cur), faucet.RedKey, 1, faucet.BlueKey, 2, "PURPLE")
	uassert.True(t, strings.HasSuffix(key, ".PURPLE"), key)
	uassert.Equal(t, 2, Legs("PURPLE"))

	redBefore := faucet.BalanceOf("RED", alice)
	blueBefore := faucet.BalanceOf("BLUE", alice)
	Fuse(cross(cur), "PURPLE", 100_000)

	uassert.Equal(t, int64(100_000), BalanceOf("PURPLE", alice))
	uassert.Equal(t, redBefore-100_000, faucet.BalanceOf("RED", alice))
	uassert.Equal(t, blueBefore-200_000, faucet.BalanceOf("BLUE", alice))

	sym, per, held := Leg("PURPLE", 1)
	uassert.Equal(t, "BLUE", sym)
	uassert.Equal(t, int64(2), per)
	uassert.Equal(t, int64(200_000), held)

	// PURPLE moves as one object, and whoever ends up with it can split it
	// back into both legs without ever having touched the faucet.
	Transfer(cross(cur), "PURPLE", bob, 40_000)
	testing.SetRealm(testing.NewUserRealm(bob))
	Defuse(cross(cur), "PURPLE", 40_000)
	uassert.Equal(t, int64(40_000), faucet.BalanceOf("RED", bob))
	uassert.Equal(t, int64(80_000), faucet.BalanceOf("BLUE", bob))
	uassert.Equal(t, int64(60_000), TotalSupply("PURPLE"))
}

// Every token issued here is registered too, so it can be wrapped again.
func TestWrappingAWrapper(cur realm, t *testing.T) {
	fund(cur, t, "nest")
	NewWrapper(cross(cur), faucet.RedKey, "plain", "nRED")
	Deposit(cross(cur), "nRED", 800_000)

	// nRED lives in THIS realm, so the allowance is granted through this
	// realm's own Approve. Same shape, one level up.
	NewWrapper(cross(cur), Key("nRED"), "pool", "nnRED")
	Approve(cross(cur), "nRED", Home(), 800_000)
	uassert.Equal(t, int64(600_000), Deposit(cross(cur), "nnRED", 600_000))

	// The outer wrapper escrows the inner token, not the RED.
	uassert.Equal(t, int64(600_000), Escrow("nnRED"))
	uassert.Equal(t, int64(800_000), Escrow("nRED"))
	uassert.Equal(t, int64(600_000), BalanceOf("nRED", Home()))

	// And it unwinds the whole way back down.
	uassert.Equal(t, int64(600_000), Withdraw(cross(cur), "nnRED", 600_000))
	uassert.Equal(t, int64(800_000), Withdraw(cross(cur), "nRED", 800_000))
	uassert.Equal(t, int64(0), TotalSupply("nRED"))
}

func TestAllowanceOnAWrappedToken(cur realm, t *testing.T) {
	alice := fund(cur, t, "allow-a")
	bob := testutils.TestAddress("allow-b")

	NewWrapper(cross(cur), faucet.RedKey, "plain", "aRED")
	Deposit(cross(cur), "aRED", 500_000)
	Approve(cross(cur), "aRED", bob, 120_000)
	uassert.Equal(t, int64(120_000), Allowance("aRED", alice, bob))

	testing.SetRealm(testing.NewUserRealm(bob))
	TransferFrom(cross(cur), "aRED", alice, bob, 120_000)
	uassert.Equal(t, int64(120_000), BalanceOf("aRED", bob))
	uassert.AbortsContains(t, cur, "insufficient allowance", func() {
		TransferFrom(cross(cur), "aRED", alice, bob, 1)
	})
}

func TestFaucetCooldown(cur realm, t *testing.T) {
	who := fund(cur, t, "cooldown")
	uassert.AbortsContains(t, cur, "too soon", func() {
		faucet.Claim(cross(cur))
	})

	next, ok := faucet.NextClaim(who)
	uassert.True(t, ok, "the account has claimed once")
	testing.SkipHeights(faucet.ClaimEvery + 1)
	faucet.Claim(cross(cur))
	uassert.Equal(t, 2*faucet.ClaimAmount, faucet.BalanceOf("RED", who))
	uassert.True(t, next > 0, "a cooldown was recorded")

	_, ok = faucet.NextClaim(testutils.TestAddress("never"))
	uassert.False(t, ok, "an account that never claimed has no cooldown")
}

func TestRejectsBadInput(cur realm, t *testing.T) {
	fund(cur, t, "bad")
	NewWrapper(cross(cur), faucet.RedKey, "plain", "xRED")
	NewFusion(cross(cur), faucet.RedKey, 1, faucet.BlueKey, 1, "xMIX")

	uassert.AbortsContains(t, cur, "unknown mode", func() {
		NewWrapper(cross(cur), faucet.RedKey, "moon", "xMOON")
	})
	uassert.AbortsContains(t, cur, "already issued by this realm", func() {
		NewWrapper(cross(cur), faucet.RedKey, "plain", "xRED")
	})
	uassert.AbortsContains(t, cur, "unknown token", func() {
		NewWrapper(cross(cur), "gno.land/r/nope/nope.NOPE", "plain", "xNOPE")
	})
	uassert.AbortsContains(t, cur, "is a fusion", func() {
		Deposit(cross(cur), "xMIX", 1)
	})
	uassert.AbortsContains(t, cur, "is a wrapper", func() {
		Fuse(cross(cur), "xRED", 1)
	})
	uassert.AbortsContains(t, cur, "has not issued", func() {
		Deposit(cross(cur), "GHOST", 1)
	})
	uassert.AbortsContains(t, cur, "unknown symbol", func() {
		faucet.Transfer(cross(cur), "GREEN", Home(), 1)
	})
}

func TestRender(cur realm, t *testing.T) {
	fund(cur, t, "render")
	NewWrapper(cross(cur), faucet.RedKey, "pool", "rRED")
	Deposit(cross(cur), "rRED", 250_000)

	index := Render("")
	uassert.True(t, strings.Contains(index, "# GRC20 wrapper factory"), "index heading")
	uassert.True(t, strings.Contains(index, Home().String()), "index shows the escrow address")
	uassert.True(t, strings.Contains(index, "| [rRED](/r/nym-moultest123/x/grc20wrapdemo/v0:rRED) | pool | RED |"),
		"index lists the wrapper:\n"+index)

	detail := Render("rRED")
	uassert.True(t, strings.Contains(detail, "escrowed underlying: 250000"), detail)
	uassert.True(t, strings.Contains(detail, "- mode: `pool`"), detail)
	uassert.True(t, strings.Contains(detail, "solvent: yes"), detail)

	uassert.True(t, strings.Contains(Render("NOPE"), "404"), "unknown symbol renders a 404")
}