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

crew.gno

// Package crew is small-group coordination as a product rather than as a
// framework: three to fifteen people with a shared pot, a way to decide, and a
// way to leave with their share.
//
// # Why not a DAO framework
//
// A framework asks you to pick a governance module, a voting strategy and a
// treasury adapter before anybody has put in a single ugnot. The targets here
// are real and already exist: a validator set, a working group, a hackathon
// team, a five-person company. They want the thing you can create in one
// transaction. [gno.land/p/nym-moultest123/grants] and daokit are the framework layer, and
// this package is deliberately underneath them: one call to open a crew, one to
// join it, one to leave with what your shares are worth.
//
// # The model
//
//	Crews     every crew, plus the credit ledger every payout goes through
//	Crew      a name, a creation height, members with shares, a treasury, proposals
//	Proposal  advisory text with a deadline and a share-weighted tally
//
// Shares are the whole design. They are the vote weight and the claim on the
// treasury at the same time, minted by [Crews.Join] and burned by
// [Crews.Ragequit], so leaving is priced by the same number that decides. There
// is no separate token to issue, distribute or forget to make meaningful.
//
// # Rounding, which is the part that has to be right
//
// Every division here rounds DOWN, and both of them therefore round in the
// crew's favour:
//
//   - joining mints amount * totalShares / treasury, so a late joiner buys
//     exactly what they paid for at the CURRENT per-share value and never a
//     share more. Rounding up would hand them a sliver of value the existing
//     members built, which is the whole reason a flat price is wrong here.
//   - ragequitting credits shares * treasury / totalShares, so a leaver takes
//     no more than their slice and the remainder stays with the people who
//     stayed.
//
// The dust that accrues from both is never stranded: the last member to
// ragequit holds every outstanding share, so their MulDiv is exact and the
// treasury empties to the last ugnot. [Crews.Ragequit] has a test for that.
//
// # What v0 deliberately does not do
//
// A proposal is advisory text. Passing one executes nothing, moves nothing and
// binds nothing; it records that the crew agreed by share weight at a point in
// time. Executing a payout is the obvious next step and the one that turns this
// into a treasury contract rather than a notice board.
//
// A vote is weighed at the moment it is cast. A member who votes and then
// ragequits leaves their weight behind in the tally, because unwinding it would
// mean re-weighing every ballot on every share change.
//
// # Errors, not aborts
//
// This is a p/, so it returns errors and declares no crossing function: the
// caller, the height and the amount all arrive as plain arguments and the realm
// that wires it to the chain decides what to abort on.
package crew

import (
	"chain/markdown"
	"errors"
	"strings"

	"gno.land/p/nym-moultest123/kit/store/v0"
	"gno.land/p/nym-moultest123/xmath/v1"
)

const (
	// MaxMembers is the upper end of "three to fifteen people". It is a
	// product constraint and not a technical one: above it the share math
	// still works and the thing stops being a crew.
	MaxMembers = 15

	// InitialPricePerShare is what a share costs in ugnot before the crew
	// has a treasury to price against: at creation, and again if every
	// member has left. 1000 ugnot makes 1 GNOT worth 1000 shares, which
	// keeps the integer arithmetic far away from both zero and overflow.
	InitialPricePerShare = int64(1000)

	// VoteBlocks is how long a proposal stays open, in blocks.
	VoteBlocks = int64(1000)

	// MaxNameLen and MaxTextLen bound what one call can make the crew's
	// members pay a storage deposit on.
	MaxNameLen = 60
	MaxTextLen = 500

	// ExcerptLen is how much of a proposal a listing shows.
	ExcerptLen = 60
)

// maxInt64 is the largest int64, spelled out because the overflow guards
// compare against it directly.
const maxInt64 = int64(9223372036854775807)

// The errors a caller can get back.
var (
	ErrBadName     = errors.New("crew: name is empty, too long, or has control characters")
	ErrBadText     = errors.New("crew: text is empty, too long, or has control characters")
	ErrBadAmount   = errors.New("crew: amount must be positive")
	ErrNoCrew      = errors.New("crew: no such crew")
	ErrNoProposal  = errors.New("crew: no such proposal")
	ErrNotMember   = errors.New("crew: not a member of this crew")
	ErrIsMember    = errors.New("crew: already a member of this crew")
	ErrFull        = errors.New("crew: the crew is full")
	ErrNoShares    = errors.New("crew: the amount sent buys no whole share")
	ErrVoteClosed  = errors.New("crew: the proposal is no longer open")
	ErrVoteOpen    = errors.New("crew: the proposal is still open")
	ErrNothing     = errors.New("crew: nothing to withdraw")
	ErrWouldExceed = errors.New("crew: the amount would overflow the ledger")
)

// Crew is one group: who is in it, what it holds, and what it is deciding.
type Crew struct {
	Name      string
	CreatedAt int64 // block height
	Treasury  int64 // ugnot, accounted here and held at the realm's address

	// TotalShares is every share outstanding. It is the denominator of both
	// the join price and the ragequit payout, so it is maintained here
	// rather than summed over the members on demand.
	TotalShares int64

	shares    map[string]int64 // address -> shares held
	order     []address        // members in join order, so output never iterates a map
	proposals []store.ID
}

// SharesOf is how many shares who holds, zero when they hold none.
func (c *Crew) SharesOf(who address) int64 {
	if c == nil {
		return 0
	}
	return c.shares[who.String()]
}

// IsMember reports whether who holds any share.
func (c *Crew) IsMember(who address) bool { return c.SharesOf(who) > 0 }

// MemberCount is how many addresses hold shares.
func (c *Crew) MemberCount() int {
	if c == nil {
		return 0
	}
	return len(c.order)
}

// Members returns the members in join order. The slice is a copy, so a caller
// rendering it cannot reorder the crew.
func (c *Crew) Members() []address {
	if c == nil {
		return nil
	}
	out := make([]address, len(c.order))
	copy(out, c.order)
	return out
}

// Proposals returns this crew's proposal ids, oldest first, as a copy.
func (c *Crew) Proposals() []store.ID {
	if c == nil {
		return nil
	}
	out := make([]store.ID, len(c.proposals))
	copy(out, c.proposals)
	return out
}

// ValuePerShare is what one share is worth in ugnot right now, rounded down.
//
// It is a display figure and nothing computes against it: [Crews.Join] and
// [Crews.Ragequit] divide by the real totals, so a crew whose treasury is
// smaller than its share count still prices both correctly while this reads 0.
func (c *Crew) ValuePerShare() int64 {
	if c == nil || c.TotalShares == 0 {
		return 0
	}
	return c.Treasury / c.TotalShares
}

// PricePerShare is what the next share costs a joiner, rounded down, which is
// [Crew.ValuePerShare] except on a crew nobody holds a share in.
func (c *Crew) PricePerShare() int64 {
	if c == nil || c.TotalShares == 0 || c.Treasury == 0 {
		return InitialPricePerShare
	}
	return c.Treasury / c.TotalShares
}

// ballot is one member's vote: which way, and what it weighed when cast.
type ballot struct {
	yes    bool
	weight int64
}

// Proposal is a question put to a crew. v0 proposals are advisory text and
// execute nothing: see the package doc.
type Proposal struct {
	CrewID   store.ID
	Author   address
	Text     string
	OpenedAt int64
	Deadline int64 // OpenedAt + VoteBlocks, exclusive

	// Yes and No are the running share-weighted tally, maintained on every
	// vote so reading it never walks the ballots.
	Yes int64
	No  int64

	Closed bool
	Passed bool

	votes map[string]ballot
}

// Open reports whether the proposal still accepts votes at height now.
func (p *Proposal) Open(now int64) bool {
	return p != nil && !p.Closed && now < p.Deadline
}

// VoteOf reports how who voted and what it weighed, and whether they voted at
// all.
func (p *Proposal) VoteOf(who address) (yes bool, weight int64, voted bool) {
	if p == nil {
		return false, 0, false
	}
	b, ok := p.votes[who.String()]
	return b.yes, b.weight, ok
}

// Voters is how many members have cast a ballot.
func (p *Proposal) Voters() int {
	if p == nil {
		return 0
	}
	return len(p.votes)
}

// Crews holds every crew, every proposal, and the credit ledger each payout
// goes through.
type Crews struct {
	crews *store.Store
	props *store.Store

	credit map[string]int64 // address -> ugnot owed
	owed   int64            // the sum of the above, which the holder must reserve
}

// New returns an empty Crews.
func New() *Crews {
	return &Crews{
		crews:  store.Named("crew"),
		props:  store.Named("proposal"),
		credit: map[string]int64{},
	}
}

// Create opens a crew with founder as its only member, their shares bought out
// of amount at [InitialPricePerShare].
//
// The remainder below one whole share stays in the treasury rather than being
// refunded, which is the same direction every other division here rounds.
func (cs *Crews) Create(name string, founder address, amount, at int64) (store.ID, error) {
	if !ValidName(name) {
		return 0, ErrBadName
	}
	if amount <= 0 {
		return 0, ErrBadAmount
	}
	shares := amount / InitialPricePerShare
	if shares < 1 {
		return 0, ErrNoShares
	}
	c := &Crew{
		Name:        name,
		CreatedAt:   at,
		Treasury:    amount,
		TotalShares: shares,
		shares:      map[string]int64{founder.String(): shares},
		order:       []address{founder},
	}
	return cs.crews.Add(c), nil
}

// Join mints who shares at the crew's CURRENT per-share value and adds amount
// to its treasury.
//
// amount * totalShares / treasury, rounded down. That is the whole anti-dilution
// rule: a crew that turned 10 GNOT into 20 sells the next share for what a share
// is worth now, not for what the founders paid, and the rounding remainder stays
// with the crew rather than with the joiner.
func (cs *Crews) Join(id store.ID, who address, amount int64) (int64, error) {
	c, ok := cs.Get(id)
	if !ok {
		return 0, ErrNoCrew
	}
	if amount <= 0 {
		return 0, ErrBadAmount
	}
	if c.IsMember(who) {
		return 0, ErrIsMember
	}
	if len(c.order) >= MaxMembers {
		return 0, ErrFull
	}
	if c.Treasury > maxInt64-amount {
		return 0, ErrWouldExceed
	}

	var shares int64
	if c.TotalShares == 0 || c.Treasury == 0 {
		// Nobody holds a share, so there is no value to price against and
		// the crew is back at its opening price.
		shares = amount / InitialPricePerShare
	} else {
		shares = xmath.MulDiv(amount, c.TotalShares, c.Treasury)
	}
	if shares < 1 {
		return 0, ErrNoShares
	}
	if c.TotalShares > maxInt64-shares {
		return 0, ErrWouldExceed
	}

	c.shares[who.String()] = shares
	c.order = append(c.order, who)
	c.TotalShares += shares
	c.Treasury += amount
	return shares, nil
}

// Fund adds amount to a crew's treasury and mints nothing.
//
// It is what makes the join price mean anything: a crew whose treasury only
// ever moves with its share count prices every joiner identically forever, and
// the anti-dilution rule in [Crews.Join] would be decorative. Revenue, a grant
// and a member topping the pot up all arrive this way, and every existing share
// is worth more afterwards.
func (cs *Crews) Fund(id store.ID, amount int64) error {
	c, ok := cs.Get(id)
	if !ok {
		return ErrNoCrew
	}
	if amount <= 0 {
		return ErrBadAmount
	}
	if c.Treasury > maxInt64-amount {
		return ErrWouldExceed
	}
	c.Treasury += amount
	return nil
}

// Propose opens an advisory question, open for [VoteBlocks] blocks. Any member
// may propose.
func (cs *Crews) Propose(id store.ID, who address, text string, at int64) (store.ID, error) {
	c, ok := cs.Get(id)
	if !ok {
		return 0, ErrNoCrew
	}
	if !c.IsMember(who) {
		return 0, ErrNotMember
	}
	if !ValidText(text) {
		return 0, ErrBadText
	}
	p := &Proposal{
		CrewID:   id,
		Author:   who,
		Text:     text,
		OpenedAt: at,
		Deadline: at + VoteBlocks,
		votes:    map[string]ballot{},
	}
	pid := cs.props.Add(p)
	c.proposals = append(c.proposals, pid)
	return pid, nil
}

// Vote records who's ballot, weighted by the shares they hold right now.
//
// One ballot per member, changeable while the proposal is open: a second call
// replaces the first, tally and weight both, so changing your mind after buying
// more shares counts the shares you now hold.
func (cs *Crews) Vote(pid store.ID, who address, yes bool, at int64) error {
	p, ok := cs.Proposal(pid)
	if !ok {
		return ErrNoProposal
	}
	if !p.Open(at) {
		return ErrVoteClosed
	}
	c, ok := cs.Get(p.CrewID)
	if !ok {
		return ErrNoCrew
	}
	weight := c.SharesOf(who)
	if weight <= 0 {
		return ErrNotMember
	}

	key := who.String()
	if prev, voted := p.votes[key]; voted {
		if prev.yes {
			p.Yes -= prev.weight
		} else {
			p.No -= prev.weight
		}
	}
	p.votes[key] = ballot{yes: yes, weight: weight}
	if yes {
		p.Yes += weight
	} else {
		p.No += weight
	}
	return nil
}

// Close records a proposal as passed or failed by share weight, once its
// deadline has gone by. Anyone may call it: closing is bookkeeping, not
// authority, and a proposal nobody closes is simply never recorded.
//
// A tie fails. There is no quorum in v0: a crew where one member votes and the
// rest ignore it passes the proposal, which is exactly as advisory as the text
// it carries.
func (cs *Crews) Close(pid store.ID, at int64) (bool, error) {
	p, ok := cs.Proposal(pid)
	if !ok {
		return false, ErrNoProposal
	}
	if p.Closed {
		return p.Passed, ErrVoteClosed
	}
	if at < p.Deadline {
		return false, ErrVoteOpen
	}
	p.Closed = true
	p.Passed = p.Yes > p.No
	return p.Passed, nil
}

// Ragequit burns every share who holds, credits them their pro-rata slice of
// the treasury and removes them from the crew.
//
// shares * treasury / totalShares, rounded down, so the remainder stays with
// the members who stayed. This is what makes a share mean something: the exit
// is priced by the same number that votes, and nobody has to agree to let you
// out.
//
// The payout is credited, never sent. The caller moves the coins after this
// returns, which is the ordering the pull-payment pattern exists for.
func (cs *Crews) Ragequit(id store.ID, who address) (shares, amount int64, err error) {
	c, ok := cs.Get(id)
	if !ok {
		return 0, 0, ErrNoCrew
	}
	shares = c.SharesOf(who)
	if shares <= 0 {
		return 0, 0, ErrNotMember
	}

	amount = xmath.MulDiv(shares, c.Treasury, c.TotalShares)
	c.TotalShares -= shares
	c.Treasury -= amount
	delete(c.shares, who.String())
	c.order = dropAddress(c.order, who)

	if amount > 0 {
		if err := cs.credits(who, amount); err != nil {
			return 0, 0, err
		}
	}
	return shares, amount, nil
}

// credits adds to an address's withdrawable balance.
func (cs *Crews) credits(who address, amount int64) error {
	key := who.String()
	if cs.credit[key] > maxInt64-amount || cs.owed > maxInt64-amount {
		return ErrWouldExceed
	}
	cs.credit[key] += amount
	cs.owed += amount
	return nil
}

// Withdraw zeroes who's credit and returns what they were owed.
//
// The balance is gone from the ledger before this returns, so the caller can
// move the coins afterwards and a reentrant call finds nothing: effects, then
// interactions.
func (cs *Crews) Withdraw(who address) (int64, error) {
	key := who.String()
	amount, ok := cs.credit[key]
	if !ok || amount == 0 {
		return 0, ErrNothing
	}
	delete(cs.credit, key)
	cs.owed -= amount
	return amount, nil
}

// CreditOf is what who can withdraw right now.
func (cs *Crews) CreditOf(who address) int64 { return cs.credit[who.String()] }

// TotalOwed is the sum of every outstanding credit, which is what the holding
// realm must keep in reserve on top of every crew's treasury.
func (cs *Crews) TotalOwed() int64 { return cs.owed }

// Get returns a crew by id.
func (cs *Crews) Get(id store.ID) (*Crew, bool) {
	v, ok := cs.crews.Get(id)
	if !ok {
		return nil, false
	}
	return v.(*Crew), true
}

// Proposal returns a proposal by id.
func (cs *Crews) Proposal(pid store.ID) (*Proposal, bool) {
	v, ok := cs.props.Get(pid)
	if !ok {
		return nil, false
	}
	return v.(*Proposal), true
}

// Len is how many crews exist.
func (cs *Crews) Len() int { return cs.crews.Len() }

// ProposalCount is how many proposals exist, across every crew.
func (cs *Crews) ProposalCount() int { return cs.props.Len() }

// Listing is one row of [Crews.List]: the crew and the id a link needs.
type Listing struct {
	ID   store.ID
	Crew *Crew
}

// List returns up to limit crews, newest first. limit below 1 returns nothing.
func (cs *Crews) List(limit int) []Listing {
	var out []Listing
	for _, e := range cs.crews.PageReverse(1, limit) {
		out = append(out, Listing{ID: e.ID, Crew: e.Value.(*Crew)})
	}
	return out
}

// ValidName reports whether name can be stored: non-empty after the render's
// own stripping and trimming,
// within [MaxNameLen], free of control characters including newlines, and
// free of the pipe character.
//
// The pipe is the one restriction that is not obvious, and it is here because
// a name is rendered as the TITLE of a link inside a table cell. md.Link
// escapes its title with the inline-text escaper, which deliberately leaves
// "|" alone because a pipe is markdown-inert outside a table, and wrapping the
// title in ui.Cell on top of that would double-escape and render the
// backslashes. Refusing the character at write time is the only place left
// where the fix is one rule rather than one exception per call site.
//
// A proposal's text has no such restriction: [ValidText] allows a pipe and the
// render escapes it with ui.Cell, because free prose legitimately contains one
// and a name does not.
func ValidName(name string) bool {
	if len(name) > MaxNameLen || strings.TrimSpace(markdown.StripBidiAndZeroWidth(name)) == "" {
		return false
	}
	for i := 0; i < len(name); i++ {
		c := name[i]
		if c < 0x20 || c == 0x7f || c == '|' {
			return false
		}
	}
	return true
}

// ValidText reports whether a proposal body can be stored: non-empty after
// the render's own stripping and trimming, within [MaxTextLen], and free of control characters other than
// newline and tab.
//
// Control characters are refused rather than stripped because the text is shown
// back to its author, and silently rewriting what somebody wrote is worse than
// telling them it was refused. Everything else is allowed and escaped at render
// time: a validator and an escaper protect against different mistakes.
func ValidText(text string) bool {
	if len(text) > MaxTextLen || strings.TrimSpace(markdown.StripBidiAndZeroWidth(text)) == "" {
		return false
	}
	for i := 0; i < len(text); i++ {
		c := text[i]
		if c < 0x20 && c != '\n' && c != '\t' || c == 0x7f {
			return false
		}
	}
	return true
}

// dropAddress returns addrs without who, in a freshly allocated slice.
//
// It allocates rather than shortening in place: a slice is one persisted object
// and the storage deposit only comes back when that object is dropped, so
// append(s[:i], s[i+1:]...) would keep the peak allocation charged forever.
func dropAddress(addrs []address, who address) []address {
	out := make([]address, 0, len(addrs))
	for _, a := range addrs {
		if a != who {
			out = append(out, a)
		}
	}
	return out
}

crew_test.gno

package crew

import (
	"strconv"
	"strings"
	"testing"

	"gno.land/p/nym-moultest123/kit/store/v0"
	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
	"gno.land/p/nt/urequire/v0"
)

var (
	alice = testutils.TestAddress("alice")
	bob   = testutils.TestAddress("bob")
	carol = testutils.TestAddress("carol")
	dave  = testutils.TestAddress("dave")
)

// join is Join with the minted share count dropped, for the cases that only
// care that it worked.
func join(t *testing.T, cs *Crews, id store.ID, who address, amount int64) {
	t.Helper()
	_, err := cs.Join(id, who, amount)
	urequire.NoError(t, err)
}

// tenGNOT is the amount every founder in these tests puts in, chosen so the
// share count is a round 10,000 and a halved or doubled price is still exact.
const tenGNOT = int64(10000000)

func TestValidName(t *testing.T) {
	tests := []struct {
		name string
		want bool
	}{
		{"validators", true},
		{"The Hackathon Team", true},
		{"a", true},
		{strings.Repeat("x", MaxNameLen), true},
		{"", false},
		{"   ", false},
		{strings.Repeat("x", MaxNameLen+1), false},
		{"two\nlines", false},
		{"a\tb", false},
		{"a\x7fb", false},
		{"a | pipe", false},
	}
	for _, tt := range tests {
		uassert.Equal(t, tt.want, ValidName(tt.name), tt.name)
	}
}

func TestValidText(t *testing.T) {
	tests := []struct {
		name string
		text string
		want bool
	}{
		{"plain", "ship v1 before the conference", true},
		{"newlines and tabs are content", "a\nb\tc", true},
		{"markdown is allowed and escaped later", "[x](y) | z", true},
		{"empty", "", false},
		{"blank", "  \n ", false},
		{"too long", strings.Repeat("x", MaxTextLen+1), false},
		{"control character", "a\x01b", false},
		{"delete character", "a\x7fb", false},
	}
	for _, tt := range tests {
		uassert.Equal(t, tt.want, ValidText(tt.text), tt.name)
	}
}

func TestCreateMintsAtTheOpeningPrice(t *testing.T) {
	cs := New()
	id, err := cs.Create("validators", alice, tenGNOT, 100)
	urequire.NoError(t, err)

	c, ok := cs.Get(id)
	urequire.True(t, ok, "the crew exists")
	uassert.Equal(t, "validators", c.Name)
	uassert.Equal(t, int64(100), c.CreatedAt)
	uassert.Equal(t, tenGNOT/InitialPricePerShare, c.TotalShares)
	uassert.Equal(t, tenGNOT, c.Treasury)
	uassert.Equal(t, c.TotalShares, c.SharesOf(alice))
	uassert.Equal(t, 1, c.MemberCount())
	uassert.Equal(t, InitialPricePerShare, c.ValuePerShare())
	uassert.Equal(t, 1, cs.Len())
}

// The remainder below one whole share stays in the treasury, which is the same
// direction every other division here rounds.
func TestCreateKeepsTheRemainder(t *testing.T) {
	cs := New()
	id, err := cs.Create("crew", alice, 2999, 100)
	urequire.NoError(t, err)

	c, _ := cs.Get(id)
	uassert.Equal(t, int64(2), c.TotalShares, "2999 ugnot buys two whole shares")
	uassert.Equal(t, int64(2999), c.Treasury, "and the 999 left over is the crew's")
}

func TestCreateRefusals(t *testing.T) {
	tests := []struct {
		label  string
		name   string
		amount int64
		want   error
	}{
		{"empty name", "", tenGNOT, ErrBadName},
		{"name with a newline", "two\nlines", tenGNOT, ErrBadName},
		{"name with a pipe", "a | pipe", tenGNOT, ErrBadName},
		{"nothing sent", "crew", 0, ErrBadAmount},
		{"negative", "crew", -1, ErrBadAmount},
		{"under one share", "crew", InitialPricePerShare - 1, ErrNoShares},
	}
	for _, tt := range tests {
		cs := New()
		_, err := cs.Create(tt.name, alice, tt.amount, 100)
		uassert.ErrorIs(t, err, tt.want, tt.label)
		uassert.Equal(t, 0, cs.Len(), tt.label+": nothing was stored")
	}
}

// A second joiner at the same per-share value gets the same shares. This is the
// baseline the anti-dilution rule is measured against.
func TestASecondJoinerAtTheSamePriceGetsTheSameShares(t *testing.T) {
	cs := New()
	id, _ := cs.Create("crew", alice, tenGNOT, 100)

	got, err := cs.Join(id, bob, tenGNOT)
	urequire.NoError(t, err)

	c, _ := cs.Get(id)
	uassert.Equal(t, c.SharesOf(alice), got, "same money, same shares")
	uassert.Equal(t, tenGNOT/InitialPricePerShare, got)
	uassert.Equal(t, 2*tenGNOT, c.Treasury)
	uassert.Equal(t, 2*(tenGNOT/InitialPricePerShare), c.TotalShares)
	uassert.Equal(t, InitialPricePerShare, c.ValuePerShare(), "the value per share did not move")
	uassert.Equal(t, 2, c.MemberCount())
}

// A joiner arriving after the treasury grew gets FEWER shares for the same
// money, because they are buying at what a share is worth now. That is the
// whole point: a late joiner cannot buy into value the existing members built.
func TestAJoinerAfterTheTreasuryGrewGetsFewer(t *testing.T) {
	cs := New()
	id, _ := cs.Create("crew", alice, tenGNOT, 100)
	urequire.NoError(t, cs.Fund(id, tenGNOT)) // the crew doubled its money

	c, _ := cs.Get(id)
	urequire.Equal(t, 2*InitialPricePerShare, c.ValuePerShare())

	got, err := cs.Join(id, bob, tenGNOT)
	urequire.NoError(t, err)
	uassert.Equal(t, c.SharesOf(alice)/2, got, "the same money buys half as much")
	uassert.Equal(t, 2*InitialPricePerShare, c.ValuePerShare(),
		"and joining did not move the value for anybody else")
}

// Rounding down on the way in means a joiner never gets a share they did not
// fully pay for, and the fractional remainder accrues to the crew.
func TestJoinRoundsInTheCrewsFavour(t *testing.T) {
	cs := New()
	id, _ := cs.Create("crew", alice, 1000, 100) // 1 share, treasury 1000
	urequire.NoError(t, cs.Fund(id, 500))        // treasury 1500, still 1 share

	// 1499 ugnot is 0.999 of a share. Rounding up would hand bob a whole
	// one and half of alice's money with it.
	_, err := cs.Join(id, bob, 1499)
	uassert.ErrorIs(t, err, ErrNoShares)

	got, err := cs.Join(id, bob, 2999)
	urequire.NoError(t, err)
	uassert.Equal(t, int64(1), got, "1.999 shares' worth buys one share")

	c, _ := cs.Get(id)
	uassert.Equal(t, int64(4499), c.Treasury, "the 1499 ugnot of remainder stayed")
	uassert.Equal(t, int64(2), c.TotalShares)
}

func TestJoinRefusals(t *testing.T) {
	cs := New()
	id, _ := cs.Create("crew", alice, tenGNOT, 100)

	_, err := cs.Join(999, bob, tenGNOT)
	uassert.ErrorIs(t, err, ErrNoCrew)

	_, err = cs.Join(id, alice, tenGNOT)
	uassert.ErrorIs(t, err, ErrIsMember, "a member cannot buy in twice")

	_, err = cs.Join(id, bob, 0)
	uassert.ErrorIs(t, err, ErrBadAmount)

	c, _ := cs.Get(id)
	uassert.Equal(t, 1, c.MemberCount(), "no refusal changed the roster")
	uassert.Equal(t, tenGNOT, c.Treasury)
}

// Fifteen people is the product constraint, and the sixteenth is refused rather
// than quietly allowed.
func TestACrewIsFullAtMaxMembers(t *testing.T) {
	cs := New()
	id, _ := cs.Create("crew", alice, tenGNOT, 100)
	for i := 1; i < MaxMembers; i++ {
		who := testutils.TestAddress("m" + strconv.Itoa(i))
		_, err := cs.Join(id, who, tenGNOT)
		urequire.NoError(t, err)
	}

	c, _ := cs.Get(id)
	urequire.Equal(t, MaxMembers, c.MemberCount())

	_, err := cs.Join(id, testutils.TestAddress("one too many"), tenGNOT)
	uassert.ErrorIs(t, err, ErrFull)
	uassert.Equal(t, MaxMembers, c.MemberCount())
}

func TestProposeAndTallyByShareWeight(t *testing.T) {
	cs := New()
	id, _ := cs.Create("crew", alice, tenGNOT, 100) // alice: 10000 shares
	cs.Join(id, bob, tenGNOT/2)                     // bob: 5000 shares

	pid, err := cs.Propose(id, bob, "ship v1 before the conference", 200)
	urequire.NoError(t, err)

	p, ok := cs.Proposal(pid)
	urequire.True(t, ok, "the proposal exists")
	uassert.Equal(t, uint64(id), uint64(p.CrewID))
	uassert.Equal(t, int64(200+VoteBlocks), p.Deadline)
	uassert.True(t, p.Open(200))
	uassert.False(t, p.Open(200+VoteBlocks), "the deadline is exclusive")

	urequire.NoError(t, cs.Vote(pid, bob, true, 210))
	urequire.NoError(t, cs.Vote(pid, alice, false, 211))
	uassert.Equal(t, int64(5000), p.Yes)
	uassert.Equal(t, int64(10000), p.No, "a bigger holder outvotes a smaller one")
	uassert.Equal(t, 2, p.Voters())

	c, _ := cs.Get(id)
	uassert.Equal(t, 1, len(c.Proposals()))
}

// One ballot per member, replaced in place while the proposal is open, and
// reweighed from the shares held at the moment it is recast.
func TestAVoteIsChangeableWhileOpen(t *testing.T) {
	cs := New()
	id, _ := cs.Create("crew", alice, tenGNOT, 100)
	pid, _ := cs.Propose(id, alice, "a question", 200)
	p, _ := cs.Proposal(pid)

	urequire.NoError(t, cs.Vote(pid, alice, true, 210))
	uassert.Equal(t, int64(10000), p.Yes)
	uassert.Equal(t, int64(0), p.No)

	urequire.NoError(t, cs.Vote(pid, alice, false, 211))
	uassert.Equal(t, int64(0), p.Yes, "the old ballot is removed, not added to")
	uassert.Equal(t, int64(10000), p.No)
	uassert.Equal(t, 1, p.Voters(), "still one voter")

	yes, weight, voted := p.VoteOf(alice)
	uassert.True(t, voted)
	uassert.False(t, yes)
	uassert.Equal(t, int64(10000), weight)
}

func TestProposeAndVoteRefusals(t *testing.T) {
	cs := New()
	id, _ := cs.Create("crew", alice, tenGNOT, 100)

	_, err := cs.Propose(999, alice, "text", 200)
	uassert.ErrorIs(t, err, ErrNoCrew)
	_, err = cs.Propose(id, bob, "text", 200)
	uassert.ErrorIs(t, err, ErrNotMember, "only a member proposes")
	_, err = cs.Propose(id, alice, "   ", 200)
	uassert.ErrorIs(t, err, ErrBadText)

	pid, _ := cs.Propose(id, alice, "a question", 200)
	uassert.ErrorIs(t, cs.Vote(999, alice, true, 210), ErrNoProposal)
	uassert.ErrorIs(t, cs.Vote(pid, bob, true, 210), ErrNotMember)
	uassert.ErrorIs(t, cs.Vote(pid, alice, true, 200+VoteBlocks), ErrVoteClosed,
		"the deadline is exclusive")
}

func TestCloseRecordsTheResult(t *testing.T) {
	tests := []struct {
		label      string
		aliceVotes bool
		bobVotes   bool
		want       bool
	}{
		{"the bigger holder carries it", true, false, true},
		{"and blocks it", false, true, false},
		{"unanimous yes", true, true, true},
		{"unanimous no", false, false, false},
	}
	for _, tt := range tests {
		cs := New()
		id, _ := cs.Create("crew", alice, tenGNOT, 100) // 10000 shares
		cs.Join(id, bob, tenGNOT/2)                     // 5000 shares
		pid, _ := cs.Propose(id, alice, "a question", 200)

		urequire.NoError(t, cs.Vote(pid, alice, tt.aliceVotes, 210))
		urequire.NoError(t, cs.Vote(pid, bob, tt.bobVotes, 211))

		passed, err := cs.Close(pid, 200+VoteBlocks)
		urequire.NoError(t, err)
		uassert.Equal(t, tt.want, passed, tt.label)

		p, _ := cs.Proposal(pid)
		uassert.True(t, p.Closed, tt.label)
		uassert.Equal(t, tt.want, p.Passed, tt.label)
	}
}

// A tie fails, and a proposal nobody voted on is a tie at zero.
func TestATieFails(t *testing.T) {
	cs := New()
	id, _ := cs.Create("crew", alice, tenGNOT, 100)
	cs.Join(id, bob, tenGNOT)
	pid, _ := cs.Propose(id, alice, "a question", 200)

	urequire.NoError(t, cs.Vote(pid, alice, true, 210))
	urequire.NoError(t, cs.Vote(pid, bob, false, 211))

	passed, err := cs.Close(pid, 200+VoteBlocks)
	urequire.NoError(t, err)
	uassert.False(t, passed, "equal weight on both sides is not agreement")

	silent, _ := cs.Propose(id, alice, "nobody cares", 200)
	passed, err = cs.Close(silent, 200+VoteBlocks)
	urequire.NoError(t, err)
	uassert.False(t, passed, "0 to 0 is not agreement either")
}

func TestCloseRefusals(t *testing.T) {
	cs := New()
	id, _ := cs.Create("crew", alice, tenGNOT, 100)
	pid, _ := cs.Propose(id, alice, "a question", 200)

	_, err := cs.Close(999, 5000)
	uassert.ErrorIs(t, err, ErrNoProposal)

	_, err = cs.Close(pid, 200+VoteBlocks-1)
	uassert.ErrorIs(t, err, ErrVoteOpen, "one block early is early")

	_, err = cs.Close(pid, 200+VoteBlocks)
	urequire.NoError(t, err)
	_, err = cs.Close(pid, 200+VoteBlocks)
	uassert.ErrorIs(t, err, ErrVoteClosed, "closing twice does not re-tally")
}

// A vote keeps the weight it was cast with. Ragequitting afterwards does not
// unwind it, which is a v0 caveat stated in the package doc rather than a bug.
func TestAVoteKeepsTheWeightItWasCastWith(t *testing.T) {
	cs := New()
	id, _ := cs.Create("crew", alice, tenGNOT, 100)
	cs.Join(id, bob, tenGNOT)
	pid, _ := cs.Propose(id, alice, "a question", 200)

	urequire.NoError(t, cs.Vote(pid, bob, true, 210))
	_, _, err := cs.Ragequit(id, bob)
	urequire.NoError(t, err)

	p, _ := cs.Proposal(pid)
	uassert.Equal(t, int64(10000), p.Yes, "bob's ballot stayed behind")
	uassert.ErrorIs(t, cs.Vote(pid, bob, false, 220), ErrNotMember,
		"but he cannot touch it again")
}

func TestRagequitTakesAProRataSlice(t *testing.T) {
	cs := New()
	id, _ := cs.Create("crew", alice, tenGNOT, 100)
	cs.Join(id, bob, tenGNOT)
	urequire.NoError(t, cs.Fund(id, 2*tenGNOT)) // the crew doubled its money

	shares, amount, err := cs.Ragequit(id, bob)
	urequire.NoError(t, err)
	uassert.Equal(t, tenGNOT/InitialPricePerShare, shares, "every share is burned")
	uassert.Equal(t, 2*tenGNOT, amount, "half of a treasury worth four, for half the shares")

	c, _ := cs.Get(id)
	uassert.Equal(t, 1, c.MemberCount())
	uassert.Equal(t, int64(0), c.SharesOf(bob))
	uassert.False(t, c.IsMember(bob))
	uassert.Equal(t, 2*tenGNOT, c.Treasury)
	uassert.Equal(t, tenGNOT/InitialPricePerShare, c.TotalShares)

	uassert.Equal(t, 2*tenGNOT, cs.CreditOf(bob), "credited, never sent")
	uassert.Equal(t, 2*tenGNOT, cs.TotalOwed())

	_, _, err = cs.Ragequit(id, bob)
	uassert.ErrorIs(t, err, ErrNotMember, "there is nothing left to burn")
	_, _, err = cs.Ragequit(999, alice)
	uassert.ErrorIs(t, err, ErrNoCrew)
}

// A one-member crew ragequitting takes everything: their shares ARE the total,
// so the division is exact whatever the numbers are.
func TestAOneMemberCrewTakesEverything(t *testing.T) {
	cs := New()
	id, _ := cs.Create("crew", alice, 5001, 100) // 5 shares, a treasury of 5001

	shares, amount, err := cs.Ragequit(id, alice)
	urequire.NoError(t, err)
	uassert.Equal(t, int64(5), shares)
	uassert.Equal(t, int64(5001), amount, "including the ugnot that bought no share")

	c, _ := cs.Get(id)
	uassert.Equal(t, int64(0), c.Treasury)
	uassert.Equal(t, int64(0), c.TotalShares)
	uassert.Equal(t, 0, c.MemberCount())
}

// Everyone ragequitting empties the treasury to the last ugnot, even when no
// single division is exact: the dust each leaver rounds away belongs to whoever
// is still in, and the last one out holds every share.
func TestEveryoneRagequittingEmptiesTheTreasury(t *testing.T) {
	cs := New()
	id, _ := cs.Create("crew", alice, 1000, 100)
	join(t, cs, id, bob, 1000)
	join(t, cs, id, carol, 1000)
	urequire.NoError(t, cs.Fund(id, 2)) // 3002 ugnot over 3 shares, divides by nothing

	c, _ := cs.Get(id)
	urequire.Equal(t, int64(3002), c.Treasury)
	urequire.Equal(t, int64(3), c.TotalShares)

	var paid int64
	for _, who := range []address{alice, bob, carol} {
		_, amount, err := cs.Ragequit(id, who)
		urequire.NoError(t, err)
		paid += amount
	}

	uassert.Equal(t, int64(3002), paid, "every ugnot left with somebody")
	uassert.Equal(t, int64(0), c.Treasury, "to the last one")
	uassert.Equal(t, int64(0), c.TotalShares)
	uassert.Equal(t, 0, c.MemberCount())
	uassert.Equal(t, int64(3002), cs.TotalOwed())

	// The dust did not land evenly, which is the point: the people who
	// stayed longest absorbed it.
	uassert.Equal(t, int64(1000), cs.CreditOf(alice), "first out, rounded down hardest")
	uassert.Equal(t, int64(1001), cs.CreditOf(bob))
	uassert.Equal(t, int64(1001), cs.CreditOf(carol))
}

// An emptied crew is not a dead one. With no shares outstanding there is no
// value to price against, so it reopens at the price it opened at.
func TestRejoiningAnEmptiedCrewIsBackAtTheOpeningPrice(t *testing.T) {
	cs := New()
	id, _ := cs.Create("crew", alice, tenGNOT, 100)
	_, _, err := cs.Ragequit(id, alice)
	urequire.NoError(t, err)

	c, _ := cs.Get(id)
	urequire.Equal(t, int64(0), c.TotalShares)
	uassert.Equal(t, int64(0), c.ValuePerShare(), "nothing is worth anything yet")
	uassert.Equal(t, InitialPricePerShare, c.PricePerShare(), "but a share still has a price")

	got, err := cs.Join(id, dave, tenGNOT)
	urequire.NoError(t, err)
	uassert.Equal(t, tenGNOT/InitialPricePerShare, got)
	uassert.Equal(t, tenGNOT, c.Treasury)
}

func TestWithdrawZeroesTheCreditBeforeItReturns(t *testing.T) {
	cs := New()
	id, _ := cs.Create("crew", alice, tenGNOT, 100)
	cs.Join(id, bob, tenGNOT)
	_, owed, _ := cs.Ragequit(id, bob)
	urequire.True(t, owed > 0, "bob is owed something")

	got, err := cs.Withdraw(bob)
	urequire.NoError(t, err)
	uassert.Equal(t, owed, got)
	uassert.Equal(t, int64(0), cs.CreditOf(bob), "zeroed, so a reentrant call finds nothing")
	uassert.Equal(t, int64(0), cs.TotalOwed())

	_, err = cs.Withdraw(bob)
	uassert.ErrorIs(t, err, ErrNothing)
	_, err = cs.Withdraw(carol)
	uassert.ErrorIs(t, err, ErrNothing)
}

// Credits accumulate across crews, because one ledger serves all of them.
func TestCreditsAccumulateAcrossCrews(t *testing.T) {
	cs := New()
	first, _ := cs.Create("first", alice, tenGNOT, 100)
	second, _ := cs.Create("second", bob, tenGNOT, 100)
	join(t, cs, second, alice, tenGNOT)

	_, a, _ := cs.Ragequit(first, alice)
	_, b, _ := cs.Ragequit(second, alice)
	uassert.Equal(t, a+b, cs.CreditOf(alice), "one withdrawal collects both")
	uassert.Equal(t, 2, cs.Len())
}

func TestListIsNewestFirst(t *testing.T) {
	cs := New()
	first, _ := cs.Create("first", alice, tenGNOT, 100)
	second, _ := cs.Create("second", bob, tenGNOT, 101)
	third, _ := cs.Create("third", carol, tenGNOT, 102)

	got := cs.List(10)
	urequire.Equal(t, 3, len(got))
	uassert.Equal(t, uint64(third), uint64(got[0].ID))
	uassert.Equal(t, uint64(second), uint64(got[1].ID))
	uassert.Equal(t, uint64(first), uint64(got[2].ID))
	uassert.Equal(t, "third", got[0].Crew.Name)

	uassert.Equal(t, 1, len(cs.List(1)))
	uassert.Equal(t, 0, len(cs.List(0)))
}

// Members comes back in join order and as a copy, so a Render can never
// reshuffle the roster it is reading.
func TestMembersAreAnOrderedCopy(t *testing.T) {
	cs := New()
	id, _ := cs.Create("crew", alice, tenGNOT, 100)
	cs.Join(id, bob, tenGNOT)
	cs.Join(id, carol, tenGNOT)

	c, _ := cs.Get(id)
	got := c.Members()
	urequire.Equal(t, 3, len(got))
	uassert.Equal(t, alice.String(), got[0].String())
	uassert.Equal(t, bob.String(), got[1].String())
	uassert.Equal(t, carol.String(), got[2].String())

	got[0] = dave
	uassert.Equal(t, alice.String(), c.Members()[0].String(), "the caller got a copy")

	// Ragequitting removes the leaver and keeps the rest in order.
	cs.Ragequit(id, bob)
	got = c.Members()
	urequire.Equal(t, 2, len(got))
	uassert.Equal(t, alice.String(), got[0].String())
	uassert.Equal(t, carol.String(), got[1].String())
}

func TestFundRefusals(t *testing.T) {
	cs := New()
	id, _ := cs.Create("crew", alice, tenGNOT, 100)

	uassert.ErrorIs(t, cs.Fund(999, 100), ErrNoCrew)
	uassert.ErrorIs(t, cs.Fund(id, 0), ErrBadAmount)
	uassert.ErrorIs(t, cs.Fund(id, -1), ErrBadAmount)

	c, _ := cs.Get(id)
	uassert.Equal(t, tenGNOT, c.Treasury, "no refusal moved the treasury")
	uassert.Equal(t, 0, cs.ProposalCount())
}

gnomod.toml

module = "gno.land/p/nym-moultest123/x/social/crew/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 392081
  max_deposit = "19000000ugnot"

zerowidth_test.gno

package crew

import "testing"

// Finding 325-input-validation-1 (review run 001-cd0b6a9).
//
// A validator that calls a field required must agree with the escaper its own
// render runs. strings.TrimSpace uses unicode.IsSpace, which does NOT include
// U+200B and the rest of the bidi and zero-width set, while every escaper on
// the output side runs chain/markdown.StripBidiAndZeroWidth, which does. So a
// value made only of those characters passes validation and renders as
// nothing: a required field that is blank on the page.
//
// The cases below are the invariant, not the implementation. A value the
// validator accepts must still be non-empty after the stripper.
func TestValidatorsAgreeWithTheEscaper(t *testing.T) {
	// One per class the stripper removes, so a fix that handles only
	// U+200B does not pass.
	blank := []string{
		"\u200b\u200b\u200b",   // ZWSP
		"\u200d",                // ZWJ
		"\u200e",                // LRM
		"\u202e",                // RLO
		"\u2066\u2069",          // LRI PDI
		"\ufeff",                // BOM
		" \u200b \u200b ",        // mixed with real spaces
	}
	// These must stay valid: the stripper removes the marks and leaves text.
	ok := []string{
		"a",
		"a\u200bb",
		"  padded  ",
	}

	for _, s := range blank {
		if ValidName(s) {
			t.Errorf("ValidName(%q) is true, but the render strips it to empty", s)
		}
	}
	for _, s := range ok {
		if !ValidName(s) {
			t.Errorf("ValidName(%q) is false, but it renders as real text", s)
		}
	}

	for _, s := range blank {
		if ValidText(s) {
			t.Errorf("ValidText(%q) is true, but the render strips it to empty", s)
		}
	}
	for _, s := range ok {
		if !ValidText(s) {
			t.Errorf("ValidText(%q) is false, but it renders as real text", s)
		}
	}

}