Playground
basket.gno
package grc20wrap
import (
"math/overflow"
"gno.land/p/nt/grc20/v0"
"gno.land/p/nt/seqid/v0"
"gno.land/p/nt/ufmt/v0"
)
// leg is one component of a Basket.
type leg struct {
tok *grc20.Token
teller grc20.Teller
per int64 // units escrowed per meta unit
held int64 // units escrowed so far
}
// Basket issues ONE meta-token over several underlying GRC20s at fixed
// proportions. Minting a meta unit escrows every leg's `per` amount; redeeming
// hands all of them back.
//
// A two-leg basket is the interesting one: it makes a pair tradable, quotable
// and transferable as a single object, without a price oracle, an AMM or any
// notion of what the legs are worth. The basket never values anything - it only
// ever swaps a fixed bundle for a receipt and back, so it cannot be arbitraged
// or drained. What it CAN do is let the market price the bundle, which is
// exactly how an index token works.
//
// Proportions are fixed at creation. Rebalancing would mean revaluing the legs,
// which needs a price, which is a different contract.
type Basket struct {
legs []*leg
home address
tok *grc20.Token
led *grc20.PrivateLedger
}
// NewBasket issues a meta-token over tokens[i], escrowing parts[i] units of
// each per meta unit.
//
// Both slices must be the same length, hold at least two entries, name no token
// twice, and every part must be positive. As with NewVault, pass the owning
// realm's own cur: escrow lands at that realm's address.
func NewBasket(tokens []*grc20.Token, parts []int64, name, symbol string, decimals int, id seqid.ID, rlm realm) *Basket {
if len(tokens) < 2 || len(tokens) != len(parts) {
panic(ErrBadLegs)
}
legs := make([]*leg, 0, len(tokens))
for i, t := range tokens {
if t == nil {
panic(ErrNilToken)
}
if parts[i] <= 0 {
panic(ErrBadLegs)
}
for _, seen := range legs {
if seen.tok.ID() == t.ID() {
panic(ErrBadLegs)
}
}
legs = append(legs, &leg{
tok: t,
teller: t.RealmTeller(0, rlm),
per: parts[i],
})
}
tok, led := grc20.NewToken(name, symbol, decimals, id, rlm)
return &Basket{
legs: legs,
home: rlm.Address(),
tok: tok,
led: led,
}
}
// Token is the meta-token this basket issues.
func (b *Basket) Token() *grc20.Token { return b.tok }
// Home is the escrow account: the host realm's address.
func (b *Basket) Home() address { return b.home }
// Legs is the number of components.
func (b *Basket) Legs() int { return len(b.legs) }
// Leg returns the i-th component: its token, the units escrowed per meta unit,
// and the units escrowed so far.
func (b *Basket) Leg(i int) (*grc20.Token, int64, int64) {
l := b.legs[i]
return l.tok, l.per, l.held
}
// Solvent reports whether every leg's escrow account still covers what the
// basket recorded taking in.
func (b *Basket) Solvent() bool {
for _, l := range b.legs {
if l.tok.BalanceOf(b.home) < l.held {
return false
}
}
return true
}
// Fuse escrows per*units of every leg from `from` and mints `units` of the meta
// token to it.
//
// `from` must have approved b.Home() on EVERY leg first. The whole basket is
// priced and checked before the first transfer, so a caller short on leg two
// gets an error with leg one untouched.
func (b *Basket) Fuse(_ int, rlm realm, from address, units int64) error {
if units <= 0 {
return ErrInvalidAmount
}
need := make([]int64, len(b.legs))
for i, l := range b.legs {
n, ok := overflow.Mul64(l.per, units)
if !ok {
return ErrOverflow
}
if l.tok.BalanceOf(from) < n {
return ErrShortBalance
}
if l.tok.Allowance(from, b.home) < n {
return ErrShortAllowance
}
need[i] = n
}
// Past here every leg was checked, so a failure is an invariant
// violation and the transaction must not stand.
for i, l := range b.legs {
if err := l.teller.TransferFrom(0, rlm, from, b.home, need[i]); err != nil {
panic(err)
}
l.held += need[i]
}
if err := b.led.Mint(from, units); err != nil {
panic(err)
}
return nil
}
// Defuse burns `units` of the meta token held by `to` and returns every leg's
// share of the escrow to it.
func (b *Basket) Defuse(_ int, rlm realm, to address, units int64) error {
if units <= 0 {
return ErrInvalidAmount
}
give := make([]int64, len(b.legs))
for i, l := range b.legs {
n, ok := overflow.Mul64(l.per, units)
if !ok {
return ErrOverflow
}
if n > l.held {
return ErrUnbacked
}
give[i] = n
}
if err := b.led.Burn(to, units); err != nil {
return err
}
for i, l := range b.legs {
l.held -= give[i]
if err := l.teller.Transfer(0, rlm, to, give[i]); err != nil {
panic(err)
}
}
return nil
}
// Move transfers meta units between two accounts.
func (b *Basket) Move(from, to address, amount int64) error {
if amount <= 0 {
return ErrInvalidAmount
}
return b.led.Transfer(from, to, amount)
}
// Allow sets `spender`'s allowance over `owner`'s meta balance.
func (b *Basket) Allow(owner, spender address, amount int64) error {
return b.led.Approve(owner, spender, amount)
}
// MoveFrom spends `spender`'s allowance over `owner`'s meta balance.
func (b *Basket) MoveFrom(spender, owner, to address, amount int64) error {
if amount <= 0 {
return ErrInvalidAmount
}
return b.led.TransferFrom(owner, spender, to, amount)
}
// Summary renders the basket as a markdown block.
func (b *Basket) Summary() string {
s := ufmt.Sprintf("**%s** (%s) - meta-token over %d legs\n\n",
b.tok.GetName(), b.tok.GetSymbol(), len(b.legs))
s += ufmt.Sprintf("- meta supply: %d\n", b.tok.TotalSupply())
for _, l := range b.legs {
s += ufmt.Sprintf("- leg %s: %d per unit, %d escrowed\n",
l.tok.GetSymbol(), l.per, l.held)
}
if b.Solvent() {
s += "- solvent: yes\n"
} else {
s += "- solvent: **NO**\n"
}
return s
}
basket_test.gno
package grc20wrap
import (
"testing"
"gno.land/p/nt/grc20/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/urequire/v0"
)
const (
pairPath = "gno.land/r/test/pair"
basketPath = "gno.land/r/test/basket"
)
// mintPair issues two independent tokens from one foreign realm and funds the
// holders with both.
func mintPair(cur realm, t *testing.T, red, blue int64, funded ...address) (*grc20.Token, *grc20.PrivateLedger, *grc20.Token, *grc20.PrivateLedger) {
t.Helper()
testing.SetRealm(testing.NewCodeRealm(pairPath))
rt, rl := grc20.NewToken("Red", "RED", 4, 0, cur)
bt, bl := grc20.NewToken("Blue", "BLUE", 4, 1, cur)
for _, a := range funded {
urequire.NoError(t, rl.Mint(a, red))
urequire.NoError(t, bl.Mint(a, blue))
}
return rt, rl, bt, bl
}
func TestFuseAndDefuse(cur realm, t *testing.T) {
red, redLed, blue, blueLed := mintPair(cur, t, 1_000, 1_000, alice)
testing.SetRealm(testing.NewCodeRealm(basketPath))
b := NewBasket(
[]*grc20.Token{red, blue},
[]int64{1, 2},
"Purple", "PURPLE", 4, 0, cur,
)
approve(cur, t, redLed, alice, b.Home(), 1_000)
approve(cur, t, blueLed, alice, b.Home(), 1_000)
urequire.NoError(t, b.Fuse(0, cur, alice, 10))
uassert.Equal(t, int64(10), b.Token().BalanceOf(alice))
uassert.Equal(t, int64(990), red.BalanceOf(alice))
uassert.Equal(t, int64(980), blue.BalanceOf(alice))
_, per, held := b.Leg(0)
uassert.Equal(t, int64(1), per)
uassert.Equal(t, int64(10), held)
_, per, held = b.Leg(1)
uassert.Equal(t, int64(2), per)
uassert.Equal(t, int64(20), held)
uassert.True(t, b.Solvent())
urequire.NoError(t, b.Defuse(0, cur, alice, 4))
uassert.Equal(t, int64(6), b.Token().TotalSupply())
uassert.Equal(t, int64(994), red.BalanceOf(alice))
uassert.Equal(t, int64(988), blue.BalanceOf(alice))
// Out entirely: the basket closes empty on both legs.
urequire.NoError(t, b.Defuse(0, cur, alice, 6))
uassert.Equal(t, int64(0), b.Token().TotalSupply())
_, _, held = b.Leg(0)
uassert.Equal(t, int64(0), held)
_, _, held = b.Leg(1)
uassert.Equal(t, int64(0), held)
uassert.Equal(t, int64(1_000), red.BalanceOf(alice))
uassert.Equal(t, int64(1_000), blue.BalanceOf(alice))
}
// The whole basket is priced before the first transfer, so being short on the
// SECOND leg leaves the first one untouched. Without the pre-pass this is where
// a partially-applied mint would come from.
func TestFuseChecksEveryLegBeforeMovingAny(cur realm, t *testing.T) {
red, redLed, blue, blueLed := mintPair(cur, t, 1_000, 10, alice)
testing.SetRealm(testing.NewCodeRealm(basketPath))
b := NewBasket(
[]*grc20.Token{red, blue},
[]int64{1, 2},
"Purple", "PURPLE", 4, 0, cur,
)
approve(cur, t, redLed, alice, b.Home(), 1_000)
approve(cur, t, blueLed, alice, b.Home(), 1_000)
// 100 units needs 100 RED (fine) and 200 BLUE (alice has 10).
uassert.ErrorIs(t, b.Fuse(0, cur, alice, 100), ErrShortBalance)
uassert.Equal(t, int64(1_000), red.BalanceOf(alice))
uassert.Equal(t, int64(0), b.Token().TotalSupply())
// Same for a missing allowance on the second leg only.
approve(cur, t, blueLed, alice, b.Home(), 0)
urequire.NoError(t, blueLed.Mint(alice, 1_000))
uassert.ErrorIs(t, b.Fuse(0, cur, alice, 5), ErrShortAllowance)
uassert.Equal(t, int64(1_000), red.BalanceOf(alice))
uassert.Equal(t, int64(0), b.Token().TotalSupply())
}
func TestDefuseStopsAtTheBalance(cur realm, t *testing.T) {
red, redLed, blue, blueLed := mintPair(cur, t, 1_000, 1_000, alice, bob)
testing.SetRealm(testing.NewCodeRealm(basketPath))
b := NewBasket(
[]*grc20.Token{red, blue},
[]int64{1, 1},
"Purple", "PURPLE", 4, 0, cur,
)
for _, a := range []address{alice, bob} {
approve(cur, t, redLed, a, b.Home(), 1_000)
approve(cur, t, blueLed, a, b.Home(), 1_000)
}
urequire.NoError(t, b.Fuse(0, cur, alice, 50))
uassert.ErrorContains(t, b.Defuse(0, cur, bob, 1), "insufficient balance")
uassert.ErrorIs(t, b.Defuse(0, cur, alice, 0), ErrInvalidAmount)
_, _, held := b.Leg(0)
uassert.Equal(t, int64(50), held)
}
func TestNewBasketRejectsBadLegs(cur realm, t *testing.T) {
red, _, blue, _ := mintPair(cur, t, 1_000, 1_000)
testing.SetRealm(testing.NewCodeRealm(basketPath))
// A one-leg basket is a Vault; say so instead of pretending.
uassert.PanicsContains(t, cur, "at least two legs", func() {
NewBasket([]*grc20.Token{red}, []int64{1}, "X", "X", 4, 0, cur)
})
// Mismatched slices.
uassert.PanicsContains(t, cur, "at least two legs", func() {
NewBasket([]*grc20.Token{red, blue}, []int64{1}, "X", "X", 4, 0, cur)
})
// A zero part would let a leg be minted for free.
uassert.PanicsContains(t, cur, "at least two legs", func() {
NewBasket([]*grc20.Token{red, blue}, []int64{1, 0}, "X", "X", 4, 0, cur)
})
// The same token twice is two accountings of one balance.
uassert.PanicsContains(t, cur, "at least two legs", func() {
NewBasket([]*grc20.Token{red, red}, []int64{1, 1}, "X", "X", 4, 0, cur)
})
uassert.PanicsContains(t, cur, "nil underlying token", func() {
NewBasket([]*grc20.Token{red, nil}, []int64{1, 1}, "X", "X", 4, 0, cur)
})
}
func TestBasketMoveAndAllowance(cur realm, t *testing.T) {
red, redLed, blue, blueLed := mintPair(cur, t, 1_000, 1_000, alice)
testing.SetRealm(testing.NewCodeRealm(basketPath))
b := NewBasket(
[]*grc20.Token{red, blue},
[]int64{1, 1},
"Purple", "PURPLE", 4, 0, cur,
)
approve(cur, t, redLed, alice, b.Home(), 1_000)
approve(cur, t, blueLed, alice, b.Home(), 1_000)
urequire.NoError(t, b.Fuse(0, cur, alice, 100))
urequire.NoError(t, b.Move(alice, bob, 40))
uassert.Equal(t, int64(40), b.Token().BalanceOf(bob))
urequire.NoError(t, b.Allow(alice, bob, 30))
urequire.NoError(t, b.MoveFrom(bob, alice, carl, 30))
uassert.Equal(t, int64(30), b.Token().BalanceOf(carl))
uassert.ErrorIs(t, b.MoveFrom(bob, alice, carl, 0), ErrInvalidAmount)
// bob holds meta units he never minted, and can still split them.
urequire.NoError(t, b.Defuse(0, cur, bob, 40))
uassert.Equal(t, int64(40), red.BalanceOf(bob))
uassert.Equal(t, int64(40), blue.BalanceOf(bob))
}
func TestBasketSummary(cur realm, t *testing.T) {
red, redLed, blue, blueLed := mintPair(cur, t, 1_000, 1_000, alice)
testing.SetRealm(testing.NewCodeRealm(basketPath))
b := NewBasket(
[]*grc20.Token{red, blue},
[]int64{1, 2},
"Purple", "PURPLE", 4, 0, cur,
)
approve(cur, t, redLed, alice, b.Home(), 1_000)
approve(cur, t, blueLed, alice, b.Home(), 1_000)
urequire.NoError(t, b.Fuse(0, cur, alice, 7))
want := "**Purple** (PURPLE) - meta-token over 2 legs\n\n" +
"- meta supply: 7\n" +
"- leg RED: 1 per unit, 7 escrowed\n" +
"- leg BLUE: 2 per unit, 14 escrowed\n" +
"- solvent: yes\n"
uassert.Equal(t, want, b.Summary())
}
gnomod.toml
module = "gno.land/p/nym-moultest123/x/grc20wrap/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186406 max_deposit = "20000000ugnot"
policy.gno
package grc20wrap
import "gno.land/p/nt/ufmt/v0"
// Policy is a wrapper's personality. It sets the exchange rate in both
// directions and can veto a move of the wrapped token.
//
// Every method receives the vault, so a policy can price against live state -
// escrow, supply, custody - instead of a frozen constant. Embed OneToOne to
// write a policy that only overrides what it cares about.
type Policy interface {
// WrapRate returns how many wrapped units `in` underlying units mint.
// It is called BEFORE the escrow moves, so v.Held() excludes `in`.
WrapRate(v *Vault, in int64) (int64, error)
// UnwrapRate returns how many underlying units `in` wrapped units
// release. It is called before the burn, so v.Supply() includes `in`.
UnwrapRate(v *Vault, in int64) (int64, error)
// CanMove vetoes a transfer of the wrapped token between two accounts.
CanMove(v *Vault, from, to address, amount int64) error
// Name labels the policy in a catalogue. Short, lowercase.
Name() string
}
// OneToOne is the boring wrapper: one underlying unit in, one wrapped unit
// out, and no restriction on who may hold the result. Useful on its own as a
// pure custody receipt, and as the embedded base of every policy below.
type OneToOne struct{}
func (OneToOne) WrapRate(v *Vault, in int64) (int64, error) { return in, nil }
func (OneToOne) UnwrapRate(v *Vault, in int64) (int64, error) { return in, nil }
func (OneToOne) CanMove(v *Vault, from, to address, amount int64) error { return nil }
func (OneToOne) Name() string { return "1:1" }
// Ratio re-denominates: Num wrapped units per Den underlying units. Both terms
// must be positive.
//
// Ratio{Num: 1000, Den: 1} turns one underlying unit into a thousand wrapped
// ones, which is how you give a token three more decimals without touching the
// realm that issued it. The reverse direction divides, so a redemption that
// rounds to zero is refused (ErrDust) rather than silently burning value: with
// Num=1000, unwrapping 999 wrapped units returns nothing and is rejected.
type Ratio struct {
OneToOne
Num int64
Den int64
}
func (r Ratio) WrapRate(v *Vault, in int64) (int64, error) {
if r.Num <= 0 || r.Den <= 0 {
return 0, ErrBadRatio
}
return mulDiv(in, r.Num, r.Den)
}
func (r Ratio) UnwrapRate(v *Vault, in int64) (int64, error) {
if r.Num <= 0 || r.Den <= 0 {
return 0, ErrBadRatio
}
return mulDiv(in, r.Den, r.Num)
}
func (r Ratio) Name() string { return ufmt.Sprintf("%d:%d", r.Num, r.Den) }
// Soulbound wraps another policy and refuses every transfer of the wrapped
// token. Rates are whatever Base says; a nil Base means OneToOne.
//
// The result is an account-bound receipt: anyone can wrap into it and anyone
// can unwrap back out, but the wrapped unit itself never changes hands. That
// makes it a membership badge, a proof of deposit, or a vote weight that
// cannot be rented - while the underlying stays fully liquid one step away.
//
// The veto binds signing users only; see the package doc.
type Soulbound struct {
Base Policy
}
func (s Soulbound) base() Policy {
if s.Base == nil {
return OneToOne{}
}
return s.Base
}
func (s Soulbound) WrapRate(v *Vault, in int64) (int64, error) {
return s.base().WrapRate(v, in)
}
func (s Soulbound) UnwrapRate(v *Vault, in int64) (int64, error) {
return s.base().UnwrapRate(v, in)
}
func (s Soulbound) CanMove(v *Vault, from, to address, amount int64) error {
return ErrSoulbound
}
func (s Soulbound) Name() string { return "soulbound/" + s.base().Name() }
// Pool prices in shares instead of units: the wrapped token is a claim on a
// fraction of the escrow rather than on a fixed amount.
//
// wrap: shares = in * supply / held (1:1 while the pool is empty)
// unwrap: units = in * held / supply
//
// Nothing changes until someone calls Vault.Donate, which adds escrow without
// minting shares. Every outstanding share is then worth more, permanently and
// for everyone at once. That is the whole yield-bearing-token pattern in two
// lines of arithmetic: a fee sink, a staking reward, an airdrop to holders, all
// the same operation.
//
// Two honest caveats:
//
// - Division truncates, so a share is always worth marginally less than its
// exact fraction. The remainder stays in the pool, which is the safe
// direction: a vault can never promise more than it holds.
// - A first depositor can wrap one unit, donate a large amount, and make
// every later deposit smaller than one share round to zero in their favour
// (the ERC-4626 inflation attack). Seed the pool at creation, or keep the
// wrapped token's decimals well above the underlying's, before using this
// anywhere real.
type Pool struct {
OneToOne
}
func (Pool) WrapRate(v *Vault, in int64) (int64, error) {
supply, held := v.Supply(), v.Held()
if supply == 0 || held == 0 {
return in, nil
}
return mulDiv(in, supply, held)
}
func (Pool) UnwrapRate(v *Vault, in int64) (int64, error) {
supply := v.Supply()
if supply == 0 {
return 0, ErrDust
}
return mulDiv(in, v.Held(), supply)
}
func (Pool) Name() string { return "pool" }
// Fee takes a basis-point haircut in both directions on top of Base (nil means
// OneToOne). 100 BPS is 1%.
//
// The haircut is not paid to anyone: it stays escrowed. Over a plain base that
// only strands value, so Fee is meant to sit over Pool, where the stranded
// units raise what every remaining share redeems for. The wrapper then pays its
// holders out of its own turnover, and paying twice - in and out - costs more
// than holding.
type Fee struct {
Base Policy
WrapBPS int64
UnwrapBPS int64
}
func (f Fee) base() Policy {
if f.Base == nil {
return OneToOne{}
}
return f.Base
}
// cut removes bps basis points from amount.
func cut(amount, bps int64) (int64, error) {
if bps < 0 || bps > 10000 {
return 0, ErrBadBPS
}
taken, err := mulDiv(amount, bps, 10000)
if err != nil {
return 0, err
}
return amount - taken, nil
}
func (f Fee) WrapRate(v *Vault, in int64) (int64, error) {
out, err := f.base().WrapRate(v, in)
if err != nil {
return 0, err
}
return cut(out, f.WrapBPS)
}
func (f Fee) UnwrapRate(v *Vault, in int64) (int64, error) {
out, err := f.base().UnwrapRate(v, in)
if err != nil {
return 0, err
}
return cut(out, f.UnwrapBPS)
}
func (f Fee) CanMove(v *Vault, from, to address, amount int64) error {
return f.base().CanMove(v, from, to, amount)
}
func (f Fee) Name() string {
return ufmt.Sprintf("fee(%d/%dbps)/%s", f.WrapBPS, f.UnwrapBPS, f.base().Name())
}
policy_test.gno
package grc20wrap
import (
"math"
"testing"
"gno.land/p/nt/uassert/v0"
)
// Every policy here is stateless, so it prices correctly against a nil vault.
// Pool is the one that reads the vault, and it is covered end to end in
// TestPoolSharesAppreciate.
func TestStatelessRates(t *testing.T) {
cases := []struct {
name string
pol Policy
wrapIn int64
wrapOut int64
unwrapIn int64
unwrapOut int64
}{
{"one to one", OneToOne{}, 7, 7, 7, 7},
{"kilo", Ratio{Num: 1_000, Den: 1}, 7, 7_000, 7_000, 7},
{"kilo truncates on the way out", Ratio{Num: 1_000, Den: 1}, 1, 1_000, 2_500, 2},
{"milli", Ratio{Num: 1, Den: 1_000}, 7_000, 7, 7, 7_000},
{"two for three", Ratio{Num: 2, Den: 3}, 9, 6, 6, 9},
{"soulbound keeps its base rate", Soulbound{Base: Ratio{Num: 2, Den: 1}}, 5, 10, 10, 5},
{"soulbound with no base is 1:1", Soulbound{}, 5, 5, 5, 5},
{"one percent both ways", Fee{WrapBPS: 100, UnwrapBPS: 100}, 1_000, 990, 1_000, 990},
{"a haircut under one unit rounds to nothing", Fee{WrapBPS: 100}, 55, 55, 55, 55},
}
for _, tc := range cases {
got, err := tc.pol.WrapRate(nil, tc.wrapIn)
uassert.NoError(t, err, tc.name)
uassert.Equal(t, tc.wrapOut, got, tc.name+" (wrap)")
got, err = tc.pol.UnwrapRate(nil, tc.unwrapIn)
uassert.NoError(t, err, tc.name)
uassert.Equal(t, tc.unwrapOut, got, tc.name+" (unwrap)")
}
}
func TestRateErrors(t *testing.T) {
cases := []struct {
name string
pol Policy
in int64
wrapErr error
unwrapErr error
}{
{"zero numerator", Ratio{Num: 0, Den: 1}, 5, ErrBadRatio, ErrBadRatio},
{"negative denominator", Ratio{Num: 2, Den: -1}, 5, ErrBadRatio, ErrBadRatio},
// Only the multiplying direction can overflow; the dividing one
// just returns a very small number.
{"overflowing numerator", Ratio{Num: math.MaxInt64, Den: 1}, 3, ErrOverflow, nil},
{"basis points above 100%", Fee{WrapBPS: 10_001, UnwrapBPS: 10_001}, 100, ErrBadBPS, ErrBadBPS},
{"negative basis points", Fee{WrapBPS: -1, UnwrapBPS: -1}, 100, ErrBadBPS, ErrBadBPS},
}
for _, tc := range cases {
_, err := tc.pol.WrapRate(nil, tc.in)
if tc.wrapErr == nil {
uassert.NoError(t, err, tc.name+" (wrap)")
} else {
uassert.ErrorIs(t, err, tc.wrapErr, tc.name+" (wrap)")
}
_, err = tc.pol.UnwrapRate(nil, tc.in)
if tc.unwrapErr == nil {
uassert.NoError(t, err, tc.name+" (unwrap)")
} else {
uassert.ErrorIs(t, err, tc.unwrapErr, tc.name+" (unwrap)")
}
}
}
func TestPolicyNames(t *testing.T) {
uassert.Equal(t, "1:1", OneToOne{}.Name())
uassert.Equal(t, "1000:1", Ratio{Num: 1_000, Den: 1}.Name())
uassert.Equal(t, "pool", Pool{}.Name())
uassert.Equal(t, "soulbound/1:1", Soulbound{}.Name())
uassert.Equal(t, "soulbound/pool", Soulbound{Base: Pool{}}.Name())
uassert.Equal(t, "fee(0/100bps)/pool", Fee{Base: Pool{}, UnwrapBPS: 100}.Name())
}
func TestOnlySoulboundVetoes(t *testing.T) {
uassert.NoError(t, OneToOne{}.CanMove(nil, alice, bob, 1))
uassert.NoError(t, Ratio{Num: 1, Den: 1}.CanMove(nil, alice, bob, 1))
uassert.NoError(t, Pool{}.CanMove(nil, alice, bob, 1))
uassert.NoError(t, Fee{Base: Pool{}}.CanMove(nil, alice, bob, 1))
uassert.ErrorIs(t, Soulbound{}.CanMove(nil, alice, bob, 1), ErrSoulbound)
// A fee over a soulbound base inherits the veto.
uassert.ErrorIs(t, Fee{Base: Soulbound{}}.CanMove(nil, alice, bob, 1), ErrSoulbound)
}
wrap.gno
// Package grc20wrap builds derived GRC20 tokens on top of existing ones.
//
// Two shapes:
//
// - Vault wraps ONE underlying token. It escrows underlying units at the
// host realm's address and issues its own GRC20 against that escrow. A
// Policy sets the exchange rate in both directions and may veto a move of
// the wrapped token, which is where a wrapper stops being plumbing and
// becomes a pattern: 1:1 custody, a denomination change, a
// non-transferable receipt, a share in a growing pool.
// - Basket wraps SEVERAL. One meta-token is minted against fixed parts of
// every leg and splits back into them on redemption.
//
// Neither type holds chain state of its own beyond the GRC20 ledger it
// creates, so a realm keeps them wherever it likes.
//
// # How custody works
//
// Escrow lands at the HOST REALM's address. A vault moves it through
// grc20.RealmTeller, which binds eagerly to that address, so a vault can only
// ever spend what its own realm holds. Pulling a user's tokens in therefore
// takes the ordinary allowance route: the user approves the host realm's
// address on the underlying token, through that token realm's own entry
// point, and the vault draws on the allowance as itself.
//
// # Reverting, not returning
//
// Wrapping is two ledger writes on two different tokens, and gno has no
// rollback short of a panic: a returned error does not undo what already ran.
// Every method here therefore validates while nothing has moved and returns an
// error, then panics if a write fails after the point of no return. Aborting
// the transaction is the only atomicity available.
//
// # What a Policy can and cannot enforce
//
// A Policy veto binds end users, not realms. Moving the wrapped token through
// Vault.Move is the only path a signing account has, because MsgCall cannot
// build the realm argument grc20's tellers require. Another realm holding the
// wrapped token can always call grc20.RealmTeller on it and move its OWN
// balance. Soulbound means "no user can pass it on", not "it can never move".
//
// Live demo: gno.land/r/nym-moultest123/x/grc20wrapdemo/v0.
package grc20wrap
import (
"errors"
"math/overflow"
"gno.land/p/nt/grc20/v0"
"gno.land/p/nt/seqid/v0"
"gno.land/p/nt/ufmt/v0"
)
var (
ErrNilToken = errors.New("grc20wrap: nil underlying token")
ErrInvalidAmount = errors.New("grc20wrap: amount must be positive")
ErrDust = errors.New("grc20wrap: amount rounds to zero")
ErrUnbacked = errors.New("grc20wrap: payout exceeds this vault's escrow")
ErrSoulbound = errors.New("grc20wrap: soulbound, the wrapped token cannot change hands")
ErrOverflow = errors.New("grc20wrap: arithmetic overflow")
ErrBadRatio = errors.New("grc20wrap: ratio terms must be positive")
ErrBadBPS = errors.New("grc20wrap: basis points must be within 0..10000")
ErrBadLegs = errors.New("grc20wrap: a basket needs at least two legs, each with a positive part")
ErrShortBalance = errors.New("grc20wrap: insufficient balance on a leg")
ErrShortAllowance = errors.New("grc20wrap: insufficient allowance on a leg")
)
// Vault escrows one underlying GRC20 and issues another against it.
//
// The escrow account is the host realm's own address, shared with every other
// vault that realm creates. Separation between them is the per-vault Held()
// counter, not separate accounts: a vault only ever releases what it recorded
// taking in, so the realm-wide invariant is sum(Held) <= Custody().
type Vault struct {
under *grc20.Token
teller grc20.Teller // bound to home, eagerly, at construction
home address
tok *grc20.Token
led *grc20.PrivateLedger
pol Policy
held int64
}
// NewVault issues a new GRC20 backed by units of under.
//
// Call it from the realm that will own the vault, forwarding that realm's own
// cur: both the teller binding and the new token's origRealm are taken from it
// and cannot be forged afterwards. id disambiguates several tokens minted by
// the same realm - allocate it from one persistent seqid.ID.
//
// A nil pol means OneToOne.
func NewVault(under *grc20.Token, pol Policy, name, symbol string, decimals int, id seqid.ID, rlm realm) *Vault {
if under == nil {
panic(ErrNilToken)
}
if pol == nil {
pol = OneToOne{}
}
tok, led := grc20.NewToken(name, symbol, decimals, id, rlm)
return &Vault{
under: under,
teller: under.RealmTeller(0, rlm),
home: rlm.Address(),
tok: tok,
led: led,
pol: pol,
}
}
// Token is the wrapped token this vault issues. It is safe to hand out: a
// *grc20.Token carries metadata and read access, never the authority to debit
// anybody.
func (v *Vault) Token() *grc20.Token { return v.tok }
// Underlying is the token held in escrow.
func (v *Vault) Underlying() *grc20.Token { return v.under }
// Policy is this vault's personality.
func (v *Vault) Policy() Policy { return v.pol }
// Home is the escrow account: the host realm's address.
func (v *Vault) Home() address { return v.home }
// Held is the underlying escrowed for THIS vault, by its own accounting.
func (v *Vault) Held() int64 { return v.held }
// Supply is the wrapped token in circulation.
func (v *Vault) Supply() int64 { return v.tok.TotalSupply() }
// Custody is the underlying actually sitting at the escrow account. It covers
// every vault the host realm created over the same underlying, plus anything
// sent there by mistake, so Custody >= Held is necessary for solvency and
// sufficient only when this is the realm's single vault over that token.
func (v *Vault) Custody() int64 { return v.under.BalanceOf(v.home) }
// Solvent reports whether the escrow account still covers what this vault
// recorded taking in. False means the host realm moved the underlying behind
// the vault's back.
func (v *Vault) Solvent() bool { return v.Custody() >= v.held }
// Wrap escrows amount units of the underlying from `from` and mints the
// wrapped token to `from`, returning how much was minted.
//
// `from` must already have granted v.Home() an allowance of at least amount on
// the underlying token, set through that token realm's own entry point.
func (v *Vault) Wrap(_ int, rlm realm, from address, amount int64) (int64, error) {
if amount <= 0 {
return 0, ErrInvalidAmount
}
out, err := v.pol.WrapRate(v, amount)
if err != nil {
return 0, err
}
if out <= 0 {
return 0, ErrDust
}
// Last point at which nothing has moved.
if err := v.teller.TransferFrom(0, rlm, from, v.home, amount); err != nil {
return 0, err
}
held, ok := overflow.Add64(v.held, amount)
if !ok {
panic(ErrOverflow)
}
v.held = held
if err := v.led.Mint(from, out); err != nil {
// The escrow already moved; only aborting the tx can undo it.
panic(err)
}
return out, nil
}
// Unwrap burns amount wrapped units held by `from` and releases the underlying
// back to it, returning how much was released.
func (v *Vault) Unwrap(_ int, rlm realm, from address, amount int64) (int64, error) {
if amount <= 0 {
return 0, ErrInvalidAmount
}
out, err := v.pol.UnwrapRate(v, amount)
if err != nil {
return 0, err
}
if out <= 0 {
return 0, ErrDust
}
if out > v.held {
return 0, ErrUnbacked
}
// Burn first: it is the step that can legitimately fail on a short
// balance, and it fails before anything has moved.
if err := v.led.Burn(from, amount); err != nil {
return 0, err
}
v.held -= out
if err := v.teller.Transfer(0, rlm, from, out); err != nil {
// The burn already happened; only aborting the tx can undo it.
panic(err)
}
return out, nil
}
// Donate escrows amount units of the underlying without minting anything.
//
// Under a pool policy this is how the wrapper gets interesting: the donation
// raises what every outstanding wrapped unit redeems for, so anyone can make
// every holder richer and nobody can take it back out except by holding.
// `from` must have approved v.Home() on the underlying, as for Wrap.
func (v *Vault) Donate(_ int, rlm realm, from address, amount int64) error {
if amount <= 0 {
return ErrInvalidAmount
}
if err := v.teller.TransferFrom(0, rlm, from, v.home, amount); err != nil {
return err
}
held, ok := overflow.Add64(v.held, amount)
if !ok {
panic(ErrOverflow)
}
v.held = held
return nil
}
// Move transfers wrapped units after the policy has had its say. It is the
// only path a signing user has to move the wrapped token; see the package doc
// for what that does and does not guarantee.
func (v *Vault) Move(from, to address, amount int64) error {
if amount <= 0 {
return ErrInvalidAmount
}
if err := v.pol.CanMove(v, from, to, amount); err != nil {
return err
}
return v.led.Transfer(from, to, amount)
}
// Allow sets `spender`'s allowance over `owner`'s wrapped balance.
//
// The policy is deliberately not consulted: an allowance moves nothing. It is
// checked when the allowance is spent, in MoveFrom, so a policy that starts
// vetoing later still binds allowances granted before.
func (v *Vault) Allow(owner, spender address, amount int64) error {
return v.led.Approve(owner, spender, amount)
}
// MoveFrom spends `spender`'s allowance over `owner`'s wrapped balance, after
// the policy has had its say.
func (v *Vault) MoveFrom(spender, owner, to address, amount int64) error {
if amount <= 0 {
return ErrInvalidAmount
}
if err := v.pol.CanMove(v, owner, to, amount); err != nil {
return err
}
return v.led.TransferFrom(owner, spender, to, amount)
}
// Summary renders the vault as a markdown block.
func (v *Vault) Summary() string {
s := ufmt.Sprintf("**%s** (%s) - %s wrapper over %s\n\n",
v.tok.GetName(), v.tok.GetSymbol(), v.pol.Name(), v.under.GetSymbol())
s += ufmt.Sprintf("- wrapped supply: %d\n", v.Supply())
s += ufmt.Sprintf("- escrowed underlying: %d\n", v.held)
s += ufmt.Sprintf("- realm custody: %d\n", v.Custody())
if v.Solvent() {
s += "- solvent: yes\n"
} else {
s += "- solvent: **NO**\n"
}
return s
}
// mulDiv returns a*b/c, rejecting an overflowing product and a zero divisor.
// The division truncates toward zero, which always rounds in the vault's
// favour rather than the holder's.
func mulDiv(a, b, c int64) (int64, error) {
if c <= 0 {
return 0, ErrBadRatio
}
p, ok := overflow.Mul64(a, b)
if !ok {
return 0, ErrOverflow
}
return p / c, nil
}
wrap_test.gno
package grc20wrap
import (
"testing"
"gno.land/p/nt/grc20/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/urequire/v0"
)
// The two realms every test needs: one that issues the underlying token, one
// that wraps it. They MUST be distinct, because wrapping a token issued by your
// own realm exercises none of the interesting machinery: the allowance, the
// eagerly-bound teller, the foreign escrow.
const (
underPath = "gno.land/r/test/under"
wrapPath = "gno.land/r/test/wrapper"
)
var (
alice = testutils.TestAddress("alice")
bob = testutils.TestAddress("bob")
carl = testutils.TestAddress("carl")
)
// mintUnder issues the underlying token from underPath and funds holders.
func mintUnder(cur realm, t *testing.T, funded ...address) (*grc20.Token, *grc20.PrivateLedger) {
t.Helper()
testing.SetRealm(testing.NewCodeRealm(underPath))
tok, led := grc20.NewToken("Under", "UND", 4, 0, cur)
for _, a := range funded {
urequire.NoError(t, led.Mint(a, 1_000))
}
return tok, led
}
// approve stands in for the underlying realm's own Approve entry point: on
// chain the holder calls it, here the ledger does it on their behalf.
func approve(cur realm, t *testing.T, led *grc20.PrivateLedger, owner, spender address, amount int64) {
t.Helper()
urequire.NoError(t, led.ImpersonateTeller(owner).Approve(0, cur, spender, amount))
}
func TestOneToOneRoundTrip(cur realm, t *testing.T) {
under, led := mintUnder(cur, t, alice)
testing.SetRealm(testing.NewCodeRealm(wrapPath))
v := NewVault(under, OneToOne{}, "Wrapped Under", "wUND", 4, 0, cur)
approve(cur, t, led, alice, v.Home(), 1_000)
out, err := v.Wrap(0, cur, alice, 400)
urequire.NoError(t, err)
uassert.Equal(t, int64(400), out)
uassert.Equal(t, int64(400), v.Token().BalanceOf(alice))
uassert.Equal(t, int64(600), under.BalanceOf(alice))
uassert.Equal(t, int64(400), v.Held())
uassert.Equal(t, int64(400), v.Custody())
uassert.True(t, v.Solvent())
back, err := v.Unwrap(0, cur, alice, 150)
urequire.NoError(t, err)
uassert.Equal(t, int64(150), back)
uassert.Equal(t, int64(250), v.Token().BalanceOf(alice))
uassert.Equal(t, int64(250), v.Supply())
uassert.Equal(t, int64(750), under.BalanceOf(alice))
uassert.Equal(t, int64(250), v.Held())
uassert.True(t, v.Solvent())
}
// Escrow is pulled with an allowance, so a wrapper can never take more than a
// holder granted it. This is the property that makes a wrapper safe to publish
// as a permissionless factory: it has no authority nobody handed it.
func TestWrapStopsAtTheAllowance(cur realm, t *testing.T) {
under, led := mintUnder(cur, t, alice)
testing.SetRealm(testing.NewCodeRealm(wrapPath))
v := NewVault(under, OneToOne{}, "Wrapped Under", "wUND", 4, 0, cur)
approve(cur, t, led, alice, v.Home(), 100)
_, err := v.Wrap(0, cur, alice, 101)
uassert.ErrorContains(t, err, "insufficient allowance")
uassert.Equal(t, int64(0), v.Supply())
uassert.Equal(t, int64(1_000), under.BalanceOf(alice))
_, err = v.Wrap(0, cur, alice, 0)
uassert.ErrorIs(t, err, ErrInvalidAmount)
}
// Unwrapping is bounded by the wrapped balance, not by the escrow: a holder
// cannot redeem somebody else's deposit.
func TestUnwrapStopsAtTheBalance(cur realm, t *testing.T) {
under, led := mintUnder(cur, t, alice, bob)
testing.SetRealm(testing.NewCodeRealm(wrapPath))
v := NewVault(under, OneToOne{}, "Wrapped Under", "wUND", 4, 0, cur)
approve(cur, t, led, alice, v.Home(), 1_000)
approve(cur, t, led, bob, v.Home(), 1_000)
_, err := v.Wrap(0, cur, alice, 500)
urequire.NoError(t, err)
_, err = v.Wrap(0, cur, bob, 500)
urequire.NoError(t, err)
uassert.Equal(t, int64(1_000), v.Held())
_, err = v.Unwrap(0, cur, bob, 501)
uassert.ErrorContains(t, err, "insufficient balance")
uassert.Equal(t, int64(1_000), v.Held())
}
// Ratio gives a token more decimals than the realm that issued it ever offered.
func TestRatioRedenominates(cur realm, t *testing.T) {
under, led := mintUnder(cur, t, alice)
testing.SetRealm(testing.NewCodeRealm(wrapPath))
v := NewVault(under, Ratio{Num: 1_000, Den: 1}, "Kilo Under", "kUND", 7, 0, cur)
approve(cur, t, led, alice, v.Home(), 1_000)
out, err := v.Wrap(0, cur, alice, 5)
urequire.NoError(t, err)
uassert.Equal(t, int64(5_000), out)
uassert.Equal(t, int64(5), v.Held())
back, err := v.Unwrap(0, cur, alice, 3_000)
urequire.NoError(t, err)
uassert.Equal(t, int64(3), back)
uassert.Equal(t, int64(2), v.Held())
// A redemption too small to buy one underlying unit is refused rather
// than silently burning the wrapped units for nothing.
_, err = v.Unwrap(0, cur, alice, 999)
uassert.ErrorIs(t, err, ErrDust)
uassert.Equal(t, int64(2_000), v.Supply())
}
// Soulbound: wrap in, unwrap out, but never hand the receipt to anybody.
func TestSoulboundReceipt(cur realm, t *testing.T) {
under, led := mintUnder(cur, t, alice)
testing.SetRealm(testing.NewCodeRealm(wrapPath))
v := NewVault(under, Soulbound{}, "Bound Under", "sUND", 4, 0, cur)
approve(cur, t, led, alice, v.Home(), 1_000)
_, err := v.Wrap(0, cur, alice, 300)
urequire.NoError(t, err)
uassert.ErrorIs(t, v.Move(alice, bob, 1), ErrSoulbound)
uassert.Equal(t, int64(0), v.Token().BalanceOf(bob))
// An allowance may be granted, and is still worthless when spent.
urequire.NoError(t, v.Allow(alice, bob, 100))
uassert.ErrorIs(t, v.MoveFrom(bob, alice, carl, 100), ErrSoulbound)
// The exit is always open: unwrap, then move the underlying.
back, err := v.Unwrap(0, cur, alice, 300)
urequire.NoError(t, err)
uassert.Equal(t, int64(300), back)
uassert.Equal(t, int64(0), v.Supply())
}
// Pool is the yield-bearing pattern: a donation nobody can withdraw raises what
// every share redeems for, and later depositors buy in at the new price.
func TestPoolSharesAppreciate(cur realm, t *testing.T) {
under, led := mintUnder(cur, t, alice, bob, carl)
testing.SetRealm(testing.NewCodeRealm(wrapPath))
v := NewVault(under, Pool{}, "Pooled Under", "pUND", 4, 0, cur)
for _, a := range []address{alice, bob, carl} {
approve(cur, t, led, a, v.Home(), 1_000)
}
// First in, priced 1:1 because the pool is empty.
out, err := v.Wrap(0, cur, alice, 100)
urequire.NoError(t, err)
uassert.Equal(t, int64(100), out)
// bob donates: escrow doubles, share count does not move.
urequire.NoError(t, v.Donate(0, cur, bob, 100))
uassert.Equal(t, int64(200), v.Held())
uassert.Equal(t, int64(100), v.Supply())
// carl now pays twice as much per share.
out, err = v.Wrap(0, cur, carl, 100)
urequire.NoError(t, err)
uassert.Equal(t, int64(50), out)
uassert.Equal(t, int64(300), v.Held())
uassert.Equal(t, int64(150), v.Supply())
// alice redeems 100 shares of 150 against 300 escrowed: 200 back, on a
// 100 deposit. bob's donation went to whoever was holding.
back, err := v.Unwrap(0, cur, alice, 100)
urequire.NoError(t, err)
uassert.Equal(t, int64(200), back)
uassert.Equal(t, int64(1_100), under.BalanceOf(alice))
// carl is made whole, and the pool closes empty.
back, err = v.Unwrap(0, cur, carl, 50)
urequire.NoError(t, err)
uassert.Equal(t, int64(100), back)
uassert.Equal(t, int64(0), v.Held())
uassert.Equal(t, int64(0), v.Supply())
uassert.True(t, v.Solvent())
}
// Fee over Pool: the haircut is not paid out, it is left behind, so the people
// still holding are the ones who collect it.
func TestFeeOverPoolPaysTheHolders(cur realm, t *testing.T) {
under, led := mintUnder(cur, t, alice, bob)
testing.SetRealm(testing.NewCodeRealm(wrapPath))
v := NewVault(under, Fee{Base: Pool{}, WrapBPS: 0, UnwrapBPS: 1_000}, "Sticky Under", "fUND", 4, 0, cur)
approve(cur, t, led, alice, v.Home(), 1_000)
approve(cur, t, led, bob, v.Home(), 1_000)
_, err := v.Wrap(0, cur, alice, 500)
urequire.NoError(t, err)
_, err = v.Wrap(0, cur, bob, 500)
urequire.NoError(t, err)
uassert.Equal(t, int64(1_000), v.Supply())
// alice leaves and pays 10% on the way out: 500 - 50.
back, err := v.Unwrap(0, cur, alice, 500)
urequire.NoError(t, err)
uassert.Equal(t, int64(450), back)
// bob stayed, and the 50 alice left behind is now his.
uassert.Equal(t, int64(550), v.Held())
uassert.Equal(t, int64(500), v.Supply())
back, err = v.Unwrap(0, cur, bob, 500)
urequire.NoError(t, err)
uassert.Equal(t, int64(495), back) // 550 pro rata, minus the same 10%
uassert.Equal(t, int64(55), v.Held())
}
// Two vaults over the same underlying share one escrow account, so Held() is
// the only thing that keeps them apart. Pin that they do.
func TestTwoVaultsShareOneEscrowAccount(cur realm, t *testing.T) {
under, led := mintUnder(cur, t, alice)
testing.SetRealm(testing.NewCodeRealm(wrapPath))
a := NewVault(under, OneToOne{}, "Vault A", "vA", 4, 0, cur)
b := NewVault(under, OneToOne{}, "Vault B", "vB", 4, 1, cur)
uassert.Equal(t, a.Home().String(), b.Home().String())
approve(cur, t, led, alice, a.Home(), 1_000)
_, err := a.Wrap(0, cur, alice, 300)
urequire.NoError(t, err)
_, err = b.Wrap(0, cur, alice, 200)
urequire.NoError(t, err)
uassert.Equal(t, int64(300), a.Held())
uassert.Equal(t, int64(200), b.Held())
// Custody is realm-wide: it sees both.
uassert.Equal(t, int64(500), a.Custody())
uassert.Equal(t, int64(500), b.Custody())
// Vault B refuses to release more than it took in, even though the
// account it draws on holds A's escrow too. Without the per-vault
// counter this is exactly where one vault would eat the other's.
_, err = b.Unwrap(0, cur, alice, 201)
uassert.ErrorIs(t, err, ErrUnbacked)
uassert.Equal(t, int64(200), b.Held())
uassert.Equal(t, int64(500), b.Custody())
// Both still unwind cleanly and independently.
_, err = b.Unwrap(0, cur, alice, 200)
urequire.NoError(t, err)
_, err = a.Unwrap(0, cur, alice, 300)
urequire.NoError(t, err)
uassert.Equal(t, int64(0), a.Custody())
uassert.Equal(t, int64(1_000), under.BalanceOf(alice))
}
func TestMoveAndAllowance(cur realm, t *testing.T) {
under, led := mintUnder(cur, t, alice)
testing.SetRealm(testing.NewCodeRealm(wrapPath))
v := NewVault(under, OneToOne{}, "Wrapped Under", "wUND", 4, 0, cur)
approve(cur, t, led, alice, v.Home(), 1_000)
_, err := v.Wrap(0, cur, alice, 600)
urequire.NoError(t, err)
urequire.NoError(t, v.Move(alice, bob, 100))
uassert.Equal(t, int64(100), v.Token().BalanceOf(bob))
uassert.ErrorIs(t, v.Move(alice, bob, 0), ErrInvalidAmount)
urequire.NoError(t, v.Allow(alice, bob, 250))
uassert.Equal(t, int64(250), v.Token().Allowance(alice, bob))
urequire.NoError(t, v.MoveFrom(bob, alice, carl, 250))
uassert.Equal(t, int64(250), v.Token().BalanceOf(carl))
uassert.ErrorContains(t, v.MoveFrom(bob, alice, carl, 1), "insufficient allowance")
}
func TestNewVaultRejectsNilUnderlying(cur realm, t *testing.T) {
testing.SetRealm(testing.NewCodeRealm(wrapPath))
uassert.PanicsContains(t, cur, "nil underlying token", func() {
NewVault(nil, OneToOne{}, "Broken", "BRK", 4, 0, cur)
})
}
func TestNilPolicyMeansOneToOne(cur realm, t *testing.T) {
under, _ := mintUnder(cur, t)
testing.SetRealm(testing.NewCodeRealm(wrapPath))
v := NewVault(under, nil, "Wrapped Under", "wUND", 4, 0, cur)
uassert.Equal(t, "1:1", v.Policy().Name())
}
func TestSummaryReportsSolvency(cur realm, t *testing.T) {
under, led := mintUnder(cur, t, alice)
testing.SetRealm(testing.NewCodeRealm(wrapPath))
v := NewVault(under, OneToOne{}, "Wrapped Under", "wUND", 4, 0, cur)
approve(cur, t, led, alice, v.Home(), 1_000)
_, err := v.Wrap(0, cur, alice, 250)
urequire.NoError(t, err)
want := "**Wrapped Under** (wUND) - 1:1 wrapper over UND\n\n" +
"- wrapped supply: 250\n" +
"- escrowed underlying: 250\n" +
"- realm custody: 250\n" +
"- solvent: yes\n"
uassert.Equal(t, want, v.Summary())
}