Transaction
B3DE99584D731F…CE4B58E653C2
Block 923,223 · index 0 · indexed
Summary
- Hash
- B3DE99584D731F8F2C6DB28350B26CD8A88D72CA3C215E531EE4CE4B58E653C2
- Block
- 923,223
- Size
- 48787 bytes
- Gas used
- 62,084,359 / 137,876,400
- Fee
- 413629 ugnot
- Status
- success
Messages
- Attached funds
- 20000000 ugnot
Arguments · 15
- #1crews
- #2README.md
- #3# crews A crew is three to fifteen people with a shared pot, a way to decide, and a way to leave with their share. One transaction to start one. The chain wiring for [`p/moul/x/social/crew`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/social/crew), which holds the share math and the proposal state. This realm reads the caller, reads the coins attached to the call, asks the engine, and renders the result. ## The API | call | | |---|---| | `Create(name)` | payable. You become the crew's first member, your shares bought out of what you sent at `InitialPricePerShare`. | | `Join(crewID)` | payable. Mints shares at what a share is worth **now**: `amount * totalShares / treasury`, rounded down. Send at least the crew page's *to join* figure, `treasury / totalShares` rounded up, or no whole share is minted. | | `Fund(crewID)` | payable. Adds to the treasury and mints nothing, so every existing share is worth more. | | `Propose(crewID, text)` | any member. Open for `VoteBlocks` blocks. | | `Vote(proposalID, yes)` | weighted by the shares you hold right now, changeable while it is open. | | `Close(proposalID)` | anyone, after the deadline. Records passed or failed by share weight. | | `Ragequit(crewID)` | burn every share you hold, be credited your pro-rata of the treasury, leave. | | `Withdraw()` | collect what you were credited. | Reads: `Get`, `Count`, `SharesOf`, `MemberCount`, `Treasury`, `ValuePerShare`, `ProposalOf`, `Tally`, `CreditOf`, `TotalOwed`. `Render` serves three views: the index, `:crew/<id>`, and `:proposal/<id>`. ## Shares are the token, and that is the answer The shares **are** the token. They are the vote weight and the claim on the treasury at once, minted by joining and burned by leaving, so nothing about them is decorative and nobody has to be persuaded they are worth something. v0 keeps them as an internal ledger rather than one GRC20 per crew, because a GRC20 per crew means a realm per crew. A transferable share belongs in [`p/moul/x/social/coin`](https://github.com/moul/gno-contracts/tree/main/p/moul/x/social/coin), the sibling that refuses to exist until its mint rule, sink and buyer are declared. This realm does not import it. ## The custody caveat, which is real **One realm address holds every crew's treasury**, with per-crew accounting inside it. The chain sees one balance; which crew owns which part of it is a number in this realm's state. So a bug in that accounting is a bug **across** crews, not inside one. An arithmetic error that over-credits one crew's ragequit pays it out of another crew's money, and nothing at the bank layer would refuse that transfer: as far as the chain is concerned it is all the same address paying itself out. The fix is the instance-per-realm pattern (`EFFECTIVE_GNO.md` section 1.4, in this repository): one realm per crew, each holding its own coins at its own address, with `p/moul/x/social/crew` as the shared engine. That is v1. It is not v0 because deploying a realm per crew is a publish per crew, which is the opposite of "create it in one transaction", and the one transaction is the whole product claim. ## Payouts are pulled, never pushed A ragequit credits an internal ledger and the leaver calls `Withdraw` themselves. One address that cannot be paid cannot wedge anybody else, and the credit is zeroed before the coins move, so a reentrant call finds nothing left to take. ## What a proposal does not do Nothing. A v0 proposal is advisory text: passing one records that the crew agreed by share weight at a point in time, and moves no coins, changes no membership and binds no code. Executing a payout is the next step, and it is what would turn this into a treasury contract rather than a notice board. ## Why this realm is private `private = true`, so it can be redeployed at this path by its creator, and no other realm may import it. The trade is the usual one: a redeploy wipes every package-level variable, so every crew, every share and every credit would go with it while the coins stayed at the address. Nothing imports this realm and nothing is meant to, so the redeploy door is worth more than the import one while the design is still moving. The v1 above is the move that closes it. <!-- BEGIN GNOCONTRACTS FOOTER (generated by `make readmes`; do not edit below) --> --- Part of **[moul/gno-contracts](https://github.com/moul/gno-contracts)** — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage. **On mainnet:** [](https://gnoscope.com/realm/r/moul/x/social/crews/v0) [](https://gnoscope.com/realm/r/moul/x/social/crews/v0) [](https://gnoscope.com/realm/r/moul/x/social/crews/v0) [](https://gnoscope.com/realm/r/moul/x/social/crews/v0) **Dependency graph:**  > 🧪 **Highly experimental — potentially vibe-coded.** Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: [DISCLAIMER](https://github.com/moul/gno-contracts/blob/main/DISCLAIMER.md). <!-- END GNOCONTRACTS FOOTER -->
- #4bounded_test.gno
- #5package crews import ( "strconv" "strings" "testing" ) // Finding 325-cost-at-caps-1. A crew's page rendered every proposal the crew // had ever had. Proposing is open to every member and nothing deletes one, so // the cost every reader of that page paid grew without a bound anybody // controls. // // Both comparison points are above the cap on purpose: comparing a count below // it with one above measures the cap arriving, not the page being bounded. func TestACrewPageIsBoundedByWhatItShows(cur realm, t *testing.T) { reset() id := create(cur, alice, 1000000, "the crew") for i := 0; i < 40; i++ { testing.SetRealm(testing.NewUserRealm(alice)) Propose(cross(cur), id, "proposal number "+strconv.Itoa(i)) } small := Render("crew/" + strconv.FormatInt(id, 10)) for i := 40; i < 200; i++ { testing.SetRealm(testing.NewUserRealm(alice)) Propose(cross(cur), id, "proposal number "+strconv.Itoa(i)) } big := Render("crew/" + strconv.FormatInt(id, 10)) rowsSmall := strings.Count(small, "\n|") rowsBig := strings.Count(big, "\n|") if rowsSmall == 0 { t.Fatal("no table rows rendered at all, so this test is measuring nothing") } if rowsBig > rowsSmall { t.Errorf("the crew page grew from %d rows to %d when the proposals went from 40 to 200: "+ "every reader pays for every proposal the crew has ever had", rowsSmall, rowsBig) } }
- #6crews.gno
- #7// Package crews is small-group coordination you can create in one // transaction: three to fifteen people with a shared pot, a way to decide, and // a way to leave with their share. // // It is the chain wiring for [gno.land/p/moul/x/social/crew], which holds the // share math and the proposal state. This realm reads the caller, reads the // coins attached to the call, asks the engine, and renders the result. // // Create pay in, and you are the crew's first member // Join pay in at what a share is worth NOW, not at what it cost them // Fund pay in and mint nothing, so every existing share is worth more // Propose any member opens an advisory question // Vote weighted by the shares you hold, changeable while it is open // Close anyone, once the deadline has gone by // Ragequit burn your shares, be credited your slice, leave // Withdraw collect what you were credited // // # The shares are the token // // There is no second asset to issue. A share is the vote weight and the claim // on the treasury at the same moment, minted by paying in and burned by // leaving, so nothing about it is decorative and nobody has to be persuaded it // is worth something. v0 keeps the shares as an internal ledger rather than one // GRC20 per crew, because a GRC20 per crew means a realm per crew. A // transferable share belongs in [gno.land/p/moul/x/social/coin], the sibling // that refuses to exist until its mint rule, sink and buyer are declared; this // realm does not import it. // // # The custody caveat, which is real // // ONE realm address holds EVERY crew's treasury, with per-crew accounting // inside it. The chain sees one balance; which crew owns which part of it is a // number in this realm's state. So a bug in the accounting is a bug across // crews, not inside one: an arithmetic error that over-credits one crew's // ragequit pays it out of another crew's money, and nothing at the bank layer // would refuse that transfer. // // The fix is the instance-per-realm pattern (EFFECTIVE_GNO.md section 1.4): one // realm per crew, each holding its own coins at its own address, with this // package as the shared engine. That is v1. It is not v0 because deploying a // realm per crew is a publish per crew, which is the opposite of "create it in // one transaction", and the whole product claim here is the one transaction. // // # Payouts are pulled // // Nothing is ever pushed. A ragequit credits an internal ledger and the leaver // calls [Withdraw] themselves, so one address that cannot be paid cannot wedge // anybody else, and the credit is zeroed before the coins move. package crews import ( "strconv" "chain" "chain/banker" "chain/runtime" "gno.land/p/moul/kit/store/v0" "gno.land/p/moul/x/envelope/v0" "gno.land/p/moul/x/social/crew/v0" "gno.land/p/moul/xmath/v1" ) // realmPath is this realm's own path, the one its gnomod.toml module line // declares. It is written out rather than read from the runtime, because every // plain read this realm exports reports its CALLER and would build every link // against the wrong realm. const realmPath = "gno.land/r/moul/x/social/crews/v0" // denom is the only coin a crew holds. ugnot and nothing else: a treasury that // can hold several denominations needs a per-denomination share price, which is // a different product. const denom = "ugnot" // IndexCrews is how many crews the index page lists. const IndexCrews = 20 // IndexProposals is how many of a crew's proposals its page lists. // // Finding 325-cost-at-caps-1: the page rendered every proposal a crew had ever // had. Proposing is open to every member and nothing deletes one, so the cost // every reader pays grew without a bound anybody controls. const IndexProposals = 20 // crews holds every crew, every proposal and the credit ledger. A redeploy // wipes it, which is the trade gnomod.toml's private = true makes: see the // comment there. var crews = crew.New() // Create opens a crew and makes the caller its first member. // // Send ugnot with the call: the founder's shares are bought out of it at // crew.InitialPricePerShare, and the whole amount, remainder included, becomes // the treasury. Returns the new crew's id. func Create(cur realm, name string) int64 { // Both checks have to be here and not behind a helper. cur.IsCurrent() // before cur.Previous() is the realm-token rule; IsUserCall before the // envelope read is the payment one, because the envelope reports what // the SIGNER attached to the transaction and not what reached this // realm. Without it a realm the user called keeps the coins and calls // in here as many times as it likes, every call reading the same send. if !cur.IsCurrent() { panic("spoofed realm: cur is not the live crossing frame") } if !cur.Previous().IsUserCall() { panic("crews: paying in must be a direct user transaction") } who := cur.Previous().Address() amount := envelope.RequireAtLeast(denom, crew.InitialPricePerShare) id, err := crews.Create(name, who, amount, runtime.ChainHeight()) if err != nil { panic(err.Error()) } chain.Emit("Create", "crew", id.String(), "founder", who.String(), "amount", strconv.FormatInt(amount, 10), ) return int64(id) } // Join mints the caller shares at what a share is worth right now and adds what // they sent to the treasury. Returns the shares minted. // // The price is amount * totalShares / treasury, rounded down, so somebody // joining a crew that has tripled its money pays three times what the founders // did. Send at least the crew page's join price, treasury / totalShares rounded // up, or there is no whole share to mint. func Join(cur realm, crewID int64) int64 { // The two guards every payable call needs; see Create. if !cur.IsCurrent() { panic("spoofed realm: cur is not the live crossing frame") } if !cur.Previous().IsUserCall() { panic("crews: paying in must be a direct user transaction") } who := cur.Previous().Address() id := store.ID(crewID) c, ok := crews.Get(id) if !ok { panic(crew.ErrNoCrew.Error()) } amount := envelope.RequireAtLeast(denom, joinPrice(c)) shares, err := crews.Join(id, who, amount) if err != nil { panic(err.Error()) } chain.Emit("Join", "crew", id.String(), "member", who.String(), "amount", strconv.FormatInt(amount, 10), "shares", strconv.FormatInt(shares, 10), ) return shares } // joinPrice is the least a joiner can send and still be minted a share: the // floor Join's envelope guard enforces, and the price a crew page quotes. // // The engine mints amount * totalShares / treasury, rounded down, so one whole // share needs treasury / totalShares rounded UP. crew.Crew.PricePerShare rounds // down, which is one ugnot short whenever the treasury is not an exact multiple // of the share count, the ordinary state after any Fund: a joiner paying the // quoted price passed the guard and then reverted on "buys no whole share". // That method lives in a published package and cannot change in place, so the // rule is here, next to the only guard that uses it. A crew nobody holds a // share in is back at the opening price, the same branch Join takes. func joinPrice(c *crew.Crew) int64 { if c.TotalShares == 0 || c.Treasury == 0 { return crew.InitialPricePerShare } return xmath.MulDivUp(1, c.Treasury, c.TotalShares) } // Fund adds what the caller sent to a crew's treasury and mints nothing, so // every existing share is worth more afterwards. // // It is how revenue, a grant or a member topping the pot up arrives. Anyone may // fund any crew, member or not: there is no way to refuse a transfer on this // chain anyway, and pretending otherwise would only move the donation to a bank // send the realm cannot account for. func Fund(cur realm, crewID int64) int64 { // The two guards every payable call needs; see Create. if !cur.IsCurrent() { panic("spoofed realm: cur is not the live crossing frame") } if !cur.Previous().IsUserCall() { panic("crews: paying in must be a direct user transaction") } who := cur.Previous().Address() amount := envelope.RequireAtLeast(denom, 1) if err := crews.Fund(store.ID(crewID), amount); err != nil { panic(err.Error()) } chain.Emit("Fund", "crew", store.ID(crewID).String(), "from", who.String(), "amount", strconv.FormatInt(amount, 10), ) return amount } // Propose opens an advisory question on a crew. Any member may propose, and it // stays open for crew.VoteBlocks blocks. Returns the proposal's id. // // A proposal EXECUTES NOTHING. Passing one records that the crew agreed by // share weight, and moves no coins, changes no membership and binds no code. // Executing a payout is the next step and it is not in v0. func Propose(cur realm, crewID int64, text string) int64 { who := caller(cur) pid, err := crews.Propose(store.ID(crewID), who, text, runtime.ChainHeight()) if err != nil { panic(err.Error()) } chain.Emit("Propose", "crew", store.ID(crewID).String(), "proposal", pid.String(), "author", who.String(), ) return int64(pid) } // Vote records the caller's ballot, weighted by the shares they hold at this // moment. One ballot per member, changeable while the proposal is open. func Vote(cur realm, proposalID int64, yes bool) { who := caller(cur) pid := store.ID(proposalID) if err := crews.Vote(pid, who, yes, runtime.ChainHeight()); err != nil { panic(err.Error()) } chain.Emit("Vote", "proposal", pid.String(), "voter", who.String(), "yes", strconv.FormatBool(yes), ) } // Close records a proposal as passed or failed once its deadline has gone by, // and returns which. Anyone may call it: closing is bookkeeping, not authority. func Close(cur realm, proposalID int64) bool { pid := store.ID(proposalID) passed, err := crews.Close(pid, runtime.ChainHeight()) if err != nil { panic(err.Error()) } chain.Emit("Close", "proposal", pid.String(), "passed", strconv.FormatBool(passed)) return passed } // Ragequit burns every share the caller holds, credits them their pro-rata // slice of the treasury and removes them from the crew. Returns the amount // credited, which [Withdraw] collects. // // Nobody has to agree. That is what makes a share mean something: the exit is // priced by the same number that votes, and a member outvoted on everything can // still leave with what they put in plus their part of what the crew built. func Ragequit(cur realm, crewID int64) int64 { who := caller(cur) id := store.ID(crewID) shares, amount, err := crews.Ragequit(id, who) if err != nil { panic(err.Error()) } chain.Emit("Ragequit", "crew", id.String(), "member", who.String(), "shares", strconv.FormatInt(shares, 10), "amount", strconv.FormatInt(amount, 10), ) return amount } // Withdraw sends the caller everything they have been credited, and returns it. // // The credit is zeroed before the coins move, so a reentrant call finds nothing // left to take. Nothing in this realm ever pushes value: one address that // cannot be paid must not be able to wedge everybody else. func Withdraw(cur realm) int64 { who := caller(cur) amount, err := crews.Withdraw(who) if err != nil { panic(err.Error()) } bnk := banker.NewBanker(banker.BankerTypeRealmSend, cur) bnk.SendCoins(cur.Address(), who, chain.NewCoins(chain.NewCoin(denom, amount))) chain.Emit("Withdraw", "payee", who.String(), "amount", strconv.FormatInt(amount, 10)) return amount } // Get returns a crew's name, the height it was created at, how many members it // has, its total shares and its treasury in ugnot. // // Flat values rather than the crew itself: handing out a pointer to live state // is a mutation handle nothing checks, and a struct is not something a wallet // can decode anyway. func Get(crewID int64) (string, int64, int, int64, int64) { c, ok := crews.Get(store.ID(crewID)) if !ok { return "", 0, 0, 0, 0 } return c.Name, c.CreatedAt, c.MemberCount(), c.TotalShares, c.Treasury } // Count is how many crews exist. func Count() int { return crews.Len() } // SharesOf is how many shares who holds in a crew. func SharesOf(crewID int64, who address) int64 { c, _ := crews.Get(store.ID(crewID)) return c.SharesOf(who) } // MemberCount is how many people are in a crew. func MemberCount(crewID int64) int { c, _ := crews.Get(store.ID(crewID)) return c.MemberCount() } // Treasury is what a crew holds, in ugnot. The coins themselves sit at this // realm's single address: see the package doc on custody. func Treasury(crewID int64) int64 { c, _ := crews.Get(store.ID(crewID)) if c == nil { return 0 } return c.Treasury } // ValuePerShare is what one of a crew's shares is worth in ugnot, rounded down. func ValuePerShare(crewID int64) int64 { c, _ := crews.Get(store.ID(crewID)) return c.ValuePerShare() } // ProposalOf returns a proposal's crew, author, text, deadline and whether it // has been closed and passed. func ProposalOf(proposalID int64) (int64, address, string, int64, bool, bool) { p, ok := crews.Proposal(store.ID(proposalID)) if !ok { return 0, "", "", 0, false, false } return int64(p.CrewID), p.Author, p.Text, p.Deadline, p.Closed, p.Passed } // Tally is a proposal's share-weighted yes and no. func Tally(proposalID int64) (int64, int64) { p, ok := crews.Proposal(store.ID(proposalID)) if !ok { return 0, 0 } return p.Yes, p.No } // CreditOf is what an address can withdraw right now, in ugnot. func CreditOf(who address) int64 { return crews.CreditOf(who) } // TotalOwed is every outstanding credit, which is the part of this realm's // balance that belongs to people who have already left. func TotalOwed() int64 { return crews.TotalOwed() } // caller is the address that called us, checked the one way that is safe. func caller(cur realm) address { if !cur.IsCurrent() { panic("spoofed realm: cur is not the live crossing frame") } return cur.Previous().Address() }
- #8crews_test.gno
- #9package crews import ( "strconv" "strings" "testing" "chain" "chain/banker" "gno.land/p/moul/x/social/crew/v0" "gno.land/p/nt/testutils/v0" "gno.land/p/nt/uassert/v0" "gno.land/p/nt/urequire/v0" ) var realmAddr = chain.PackageAddress(realmPath) var ( alice = testutils.TestAddress("alice") bob = testutils.TestAddress("bob") carol = testutils.TestAddress("carol") ) // tenGNOT is what every founder here puts in: 10,000 shares at the opening // price, so halving and doubling stay exact and the rounding tests can use // deliberately awkward numbers instead. const tenGNOT = int64(10000000) // reset clears realm state. Realm globals live for the whole test binary, so // everything a later test reads starts here. func reset() { crews = crew.New() } // create calls Create the way a real transaction would: the runtime credits // the realm's address, then the envelope reports the send to the crossing // function. The account switch and the cross are in the same frame on purpose, // since testing.SetRealm governs nothing else. func create(cur realm, who address, amount int64, name string) int64 { testing.IssueCoins(realmAddr, chain.Coins{{denom, amount}}) testing.SetOriginSend(chain.Coins{{denom, amount}}) testing.SetRealm(testing.NewUserRealm(who)) return Create(cross(cur), name) } // join is [create] for Join. func join(cur realm, who address, amount, crewID int64) int64 { testing.IssueCoins(realmAddr, chain.Coins{{denom, amount}}) testing.SetOriginSend(chain.Coins{{denom, amount}}) testing.SetRealm(testing.NewUserRealm(who)) return Join(cross(cur), crewID) } // fund is [create] for Fund. func fund(cur realm, who address, amount, crewID int64) int64 { testing.IssueCoins(realmAddr, chain.Coins{{denom, amount}}) testing.SetOriginSend(chain.Coins{{denom, amount}}) testing.SetRealm(testing.NewUserRealm(who)) return Fund(cross(cur), crewID) } func TestCreateMakesTheFounderTheOnlyMember(cur realm, t *testing.T) { reset() id := create(cur, alice, tenGNOT, "validators") name, at, members, shares, treasury := Get(id) uassert.Equal(t, "validators", name) uassert.Equal(t, int64(123), at, "tests start at height 123") uassert.Equal(t, 1, members) uassert.Equal(t, tenGNOT/crew.InitialPricePerShare, shares) uassert.Equal(t, tenGNOT, treasury) uassert.Equal(t, shares, SharesOf(id, alice)) uassert.Equal(t, int64(0), SharesOf(id, bob)) uassert.Equal(t, crew.InitialPricePerShare, ValuePerShare(id)) uassert.Equal(t, 1, Count()) uassert.Equal(t, tenGNOT, Treasury(id)) } // A second joiner at the same per-share value gets the same shares, which is // the baseline the anti-dilution rule is measured against. func TestASecondJoinerAtTheSamePriceGetsTheSameShares(cur realm, t *testing.T) { reset() id := create(cur, alice, tenGNOT, "crew") got := join(cur, bob, tenGNOT, id) uassert.Equal(t, SharesOf(id, alice), got, "same money, same shares") uassert.Equal(t, crew.InitialPricePerShare, ValuePerShare(id), "the price did not move") uassert.Equal(t, 2, MemberCount(id)) uassert.Equal(t, 2*tenGNOT, Treasury(id)) } // A joiner arriving after the treasury grew gets FEWER shares for the same // money: they buy at what a share is worth now, not at what the founders paid. func TestAJoinerAfterTheTreasuryGrewGetsFewer(cur realm, t *testing.T) { reset() id := create(cur, alice, tenGNOT, "crew") fund(cur, carol, tenGNOT, id) // the crew doubled its money urequire.Equal(t, 2*crew.InitialPricePerShare, ValuePerShare(id)) got := join(cur, bob, tenGNOT, id) uassert.Equal(t, SharesOf(id, alice)/2, got, "the same money buys half as much") uassert.Equal(t, 2*crew.InitialPricePerShare, ValuePerShare(id), "and joining moved the value for nobody") uassert.Equal(t, int64(0), SharesOf(id, carol), "funding mints nothing") } // Ragequit credits, Withdraw pays, and the coins actually move. func TestRagequitCreditsAndWithdrawPays(cur realm, t *testing.T) { reset() id := create(cur, alice, tenGNOT, "crew") join(cur, bob, tenGNOT, id) fund(cur, carol, 2*tenGNOT, id) // treasury 4x, still 2x the shares testing.SetRealm(testing.NewUserRealm(bob)) owed := Ragequit(cross(cur), id) uassert.Equal(t, 2*tenGNOT, owed, "half the shares of a treasury worth four") uassert.Equal(t, owed, CreditOf(bob), "credited, never sent") uassert.Equal(t, owed, TotalOwed()) uassert.Equal(t, 1, MemberCount(id)) uassert.Equal(t, int64(0), SharesOf(id, bob)) uassert.Equal(t, 2*tenGNOT, Treasury(id)) before := banker.NewReadonlyBanker().GetCoins(bob).AmountOf(denom) testing.SetRealm(testing.NewUserRealm(bob)) got := Withdraw(cross(cur)) uassert.Equal(t, owed, got) uassert.Equal(t, int64(0), CreditOf(bob), "zeroed before the coins moved") uassert.Equal(t, int64(0), TotalOwed()) after := banker.NewReadonlyBanker().GetCoins(bob).AmountOf(denom) uassert.Equal(t, before+owed, after, "the coins actually arrived") testing.SetRealm(testing.NewUserRealm(bob)) uassert.AbortsContains(t, cur, "nothing to withdraw", func() { Withdraw(cross(cur)) }) } // Everyone ragequitting empties the treasury to the last ugnot, even when no // single division is exact: the dust a leaver rounds away belongs to whoever is // still in, and the last one out holds every share. func TestEveryoneRagequittingEmptiesTheTreasury(cur realm, t *testing.T) { reset() id := create(cur, alice, 1000, "crew") join(cur, bob, 1000, id) join(cur, carol, 1000, id) fund(cur, alice, 2, id) // 3002 ugnot over 3 shares, divides by nothing urequire.Equal(t, int64(3002), Treasury(id)) var paid int64 testing.SetRealm(testing.NewUserRealm(alice)) paid += Ragequit(cross(cur), id) testing.SetRealm(testing.NewUserRealm(bob)) paid += Ragequit(cross(cur), id) testing.SetRealm(testing.NewUserRealm(carol)) paid += Ragequit(cross(cur), id) uassert.Equal(t, int64(3002), paid, "every ugnot left with somebody") uassert.Equal(t, int64(0), Treasury(id), "to the last one") uassert.Equal(t, 0, MemberCount(id)) uassert.Equal(t, int64(3002), TotalOwed()) uassert.Equal(t, int64(1000), CreditOf(alice), "first out, rounded down hardest") uassert.Equal(t, int64(1001), CreditOf(carol), "last out takes the dust") } // A one-member crew ragequitting takes everything, including the ugnot that // bought no whole share: their shares ARE the total, so the division is exact. func TestAOneMemberCrewTakesEverything(cur realm, t *testing.T) { reset() id := create(cur, alice, 5001, "solo") testing.SetRealm(testing.NewUserRealm(alice)) got := Ragequit(cross(cur), id) uassert.Equal(t, int64(5001), got) uassert.Equal(t, int64(0), Treasury(id)) uassert.Equal(t, 0, MemberCount(id)) // An emptied crew is not a dead one: with nothing outstanding there is // no value to price against, so it reopens at the opening price. uassert.Equal(t, int64(0), ValuePerShare(id)) got = join(cur, bob, tenGNOT, id) uassert.Equal(t, tenGNOT/crew.InitialPricePerShare, got) } func TestProposalsAreAdvisoryAndShareWeighted(cur realm, t *testing.T) { reset() id := create(cur, alice, tenGNOT, "crew") // alice: 10000 shares join(cur, bob, tenGNOT/2, id) // bob: 5000 shares testing.SetRealm(testing.NewUserRealm(bob)) pid := Propose(cross(cur), id, "ship v1 before the conference") _, author, text, deadline, closed, passed := ProposalOf(pid) uassert.Equal(t, bob.String(), author.String()) uassert.Equal(t, "ship v1 before the conference", text) uassert.Equal(t, int64(123+crew.VoteBlocks), deadline) uassert.False(t, closed) uassert.False(t, passed) testing.SetRealm(testing.NewUserRealm(bob)) Vote(cross(cur), pid, true) testing.SetRealm(testing.NewUserRealm(alice)) Vote(cross(cur), pid, false) yes, no := Tally(pid) uassert.Equal(t, int64(5000), yes) uassert.Equal(t, int64(10000), no, "a bigger holder outvotes a smaller one") // Changing your mind while it is open replaces the ballot. testing.SetRealm(testing.NewUserRealm(alice)) Vote(cross(cur), pid, true) yes, no = Tally(pid) uassert.Equal(t, int64(15000), yes) uassert.Equal(t, int64(0), no, "the old ballot is removed, not added to") testing.SkipHeights(crew.VoteBlocks) testing.SetRealm(testing.NewUserRealm(carol)) uassert.True(t, Close(cross(cur), pid), "anyone may close it") _, _, _, _, closed, passed = ProposalOf(pid) uassert.True(t, closed) uassert.True(t, passed) // Passing it moved nothing. That is the whole v0 claim. uassert.Equal(t, tenGNOT+tenGNOT/2, Treasury(id)) uassert.Equal(t, int64(0), TotalOwed()) } func TestRefusals(cur realm, t *testing.T) { reset() id := create(cur, alice, tenGNOT, "crew") testing.IssueCoins(realmAddr, chain.Coins{{denom, tenGNOT}}) testing.SetOriginSend(chain.Coins{{denom, tenGNOT}}) testing.SetRealm(testing.NewUserRealm(alice)) uassert.AbortsContains(t, cur, "already a member", func() { Join(cross(cur), id) }) testing.IssueCoins(realmAddr, chain.Coins{{denom, tenGNOT}}) testing.SetOriginSend(chain.Coins{{denom, tenGNOT}}) testing.SetRealm(testing.NewUserRealm(bob)) uassert.AbortsContains(t, cur, "no such crew", func() { Join(cross(cur), 4242) }) // Create with nothing attached is refused by the envelope, which names // the flag the caller has to fix. testing.SetOriginSend(chain.Coins{}) testing.SetRealm(testing.NewUserRealm(bob)) uassert.AbortsContains(t, cur, "send", func() { Create(cross(cur), "broke") }) testing.SetRealm(testing.NewUserRealm(bob)) uassert.AbortsContains(t, cur, "not a member", func() { Propose(cross(cur), id, "let me in") }) testing.SetRealm(testing.NewUserRealm(bob)) uassert.AbortsContains(t, cur, "not a member", func() { Ragequit(cross(cur), id) }) testing.SetRealm(testing.NewUserRealm(alice)) pid := Propose(cross(cur), id, "a question") testing.SetRealm(testing.NewUserRealm(bob)) uassert.AbortsContains(t, cur, "not a member", func() { Vote(cross(cur), pid, true) }) testing.SetRealm(testing.NewUserRealm(alice)) uassert.AbortsContains(t, cur, "still open", func() { Close(cross(cur), pid) }) testing.SetRealm(testing.NewUserRealm(alice)) uassert.AbortsContains(t, cur, "name is empty", func() { create(cur, alice, tenGNOT, " ") }) // A pipe in a name would open a column where the name is a link title // in a table cell, which md.Link's escaper does not cover. testing.SetRealm(testing.NewUserRealm(alice)) uassert.AbortsContains(t, cur, "name is empty", func() { create(cur, alice, tenGNOT, "a | pipe") }) uassert.Equal(t, 1, Count(), "no refusal created anything") uassert.Equal(t, 1, MemberCount(id)) } // TestRender uses uassert rather than an Example because every view contains // consecutive blank lines, which gno collapses inside an // Output: block. func TestRender(cur realm, t *testing.T) { reset() id := create(cur, alice, tenGNOT, "a crew [with](markdown)") join(cur, bob, tenGNOT, id) testing.SetRealm(testing.NewUserRealm(alice)) pid := Propose(cross(cur), id, "ship v1 | before the conference") testing.SetRealm(testing.NewUserRealm(alice)) Vote(cross(cur), pid, true) index := Render("") uassert.True(t, strings.Contains(index, "# Crews"), index) uassert.True(t, strings.Contains(index, "| 1 | 1 | 0 GNOT |"), "crews, proposals, owed") uassert.True(t, strings.Contains(index, "func=Create"), index) uassert.True(t, strings.Contains(index, "One realm address holds every crew's treasury"), "the index states the custody caveat") uassert.True(t, strings.Contains(index, "[a crew \\[with\\]\\(markdown\\)](/r/moul/x/social/crews/v0:crew/1)"), "md.Link escapes the title exactly once: "+index) sid := strconv.FormatInt(id, 10) page := Render("crew/" + sid) uassert.True(t, strings.Contains(page, "# a crew \\[with\\]\\(markdown\\)"), "the name is escaped where it is shown as prose: "+page) uassert.True(t, strings.Contains(page, "| 2 of 15 | 20000 | 20 GNOT | 0.001 GNOT |"), page) uassert.True(t, strings.Contains(page, "| 10000 | 50% | 10 GNOT |"), "each member holds half the shares and half the money") uassert.True(t, strings.Contains(page, "func=Ragequit"), page) uassert.True(t, strings.Contains(page, "executes nothing"), page) // A pipe in a proposal's text must not open a column in the crew's // proposal table. It goes through ui.Cell for exactly this. uassert.True(t, strings.Contains(page, "ship v1 \\| before the conference"), "the cell is escaped: "+page) uassert.False(t, strings.Contains(page, "| ship v1 | before"), "a raw pipe would open a column: "+page) spid := strconv.FormatInt(pid, 10) prop := Render("proposal/" + spid) uassert.True(t, strings.Contains(prop, "# Proposal #"+spid), prop) uassert.True(t, strings.Contains(prop, "> ship v1 | before the conference"), "a blockquote is prose, where a pipe is inert and must not grow a backslash") uassert.True(t, strings.Contains(prop, "| open until 1123 | 10000 | 0 | 1 |"), prop) uassert.True(t, strings.Contains(prop, "func=Vote"), prop) // Past the deadline the page offers the close instead of the vote. testing.SkipHeights(crew.VoteBlocks) prop = Render("proposal/" + spid) uassert.True(t, strings.Contains(prop, "awaiting a close"), prop) uassert.True(t, strings.Contains(prop, "func=Close"), prop) uassert.False(t, strings.Contains(prop, "func=Vote"), prop) uassert.Equal(t, "# Crews\nNo crew #4242", Render("crew/4242")) uassert.Equal(t, "# Crews\nNot a crew id: nope", Render("crew/nope")) uassert.Equal(t, "# Crews\nNo proposal #4242", Render("proposal/4242")) uassert.Equal(t, "# Crews\nNot a proposal id: nope", Render("proposal/nope")) uassert.True(t, strings.HasPrefix(Render("elsewhere"), "# Not found")) } // An empty realm still renders something a reader can act on. func TestRenderWithNothingInIt(cur realm, t *testing.T) { reset() index := Render("") uassert.True(t, strings.Contains(index, "No crews yet."), index) uassert.True(t, strings.Contains(index, "func=Create"), index) } // Links are rooted at the realm's own path, so they resolve from any page // gnoweb serves them on. func TestLinksAreRootRelative(t *testing.T) { uassert.Equal(t, "/r/moul/x/social/crews/v0", realmURL()) uassert.Equal(t, "/r/moul/x/social/crews/v0:crew/7", crewURL(7)) uassert.Equal(t, "/r/moul/x/social/crews/v0:proposal/7", proposalURL(7)) }
- #10gnomod.toml
- #11module = "gno.land/r/moul/x/social/crews/v0" gno = "0.9" private = true # private: nothing imports this realm and nothing is meant to. The trade is the # usual one, a redeploy wipes every crew, share and credit while the coins stay # at the address, and it is worth taking while the design is still moving. The # v1 in README.md, one realm per crew, is the move that closes the door. [source] repository = "https://github.com/moul/gno-contracts" path = "r/moul/x/social/crews" revision = "507056d812b505ad16a009f0d60786644ceeb19d"
- #12joinprice_test.gno
- #13package crews import ( "strconv" "strings" "testing" "chain" "gno.land/p/moul/x/social/crew/v0" "gno.land/p/nt/uassert/v0" "gno.land/p/nt/urequire/v0" ) // The price a crew page shows a joiner, and the floor Join's envelope guard // enforces, must both be exactly the least amount that mints a whole share. // // Join mints amount * totalShares / treasury, rounded down, so that amount is // treasury / totalShares rounded UP. Rounded down instead, it is one ugnot // short whenever the treasury is not an exact multiple of the share count, // which is the ordinary state after any Fund: the page quotes a price, the // guard accepts it, and the join reverts on "buys no whole share". // // The table is over that rule, not over one input: awkward remainders where // floor and ceiling differ, exact multiples where they must not, and a crew // everybody left, where the opening price applies. func TestTheShownPriceBuysAShareAndOneLessIsRefusedByTheGuard(cur realm, t *testing.T) { cases := []struct { name string create int64 // what the founder pays in, at the opening price fund int64 // then funded with this, which mints nothing leave bool // then the founder ragequits, leaving an empty crew want int64 // the least amount that mints one share }{ {"treasury 3001 over 2 shares", 2000, 1001, false, 1501}, {"treasury 3001 over 3 shares", 3000, 1, false, 1001}, {"ten GNOT and seven ugnot over 10000 shares", tenGNOT, 7, false, 1001}, {"ten GNOT and 999 ugnot over 10000 shares", tenGNOT, 999, false, 1001}, {"exact multiple at the opening price", tenGNOT, 0, false, 1000}, {"exact multiple after doubling", tenGNOT, tenGNOT, false, 2000}, {"a single share", 1000, 0, false, 1000}, {"everybody left", 1000, 0, true, crew.InitialPricePerShare}, } for _, tc := range cases { reset() id := create(cur, alice, tc.create, "crew") if tc.fund > 0 { fund(cur, carol, tc.fund, id) } if tc.leave { testing.SetRealm(testing.NewUserRealm(alice)) Ragequit(cross(cur), id) } // The oracle, independent of the code under test: the least a with // a * shares >= treasury, or the opening price when nobody holds one. _, _, _, shares, treasury := Get(id) oracle := crew.InitialPricePerShare if shares > 0 && treasury > 0 { oracle = treasury / shares if treasury%shares != 0 { oracle++ } } urequire.Equal(t, tc.want, oracle, tc.name+": the table agrees with the rule") page := Render("crew/" + strconv.FormatInt(id, 10)) uassert.Equal(t, tc.want, shownPrice(t, page), tc.name+": the page quotes what buys a share: "+page) // One ugnot under it is refused by the envelope guard, which names the // real price, rather than by Join after the guard let it through. testing.IssueCoins(realmAddr, chain.Coins{{denom, tc.want - 1}}) testing.SetOriginSend(chain.Coins{{denom, tc.want - 1}}) testing.SetRealm(testing.NewUserRealm(bob)) uassert.AbortsContains(t, cur, "costs at least "+strconv.FormatInt(tc.want, 10)+denom, func() { Join(cross(cur), id) }, tc.name+": the guard refuses one ugnot short") // Exactly the quoted price buys exactly one share. got := join(cur, bob, tc.want, id) uassert.Equal(t, int64(1), got, tc.name+": the quoted price mints one share") } } // shownPrice reads the price cell of a crew page's summary table, the first // row after the header that starts with "| members", in ugnot. It is keyed on // the row's position, not the column's title, so it reads the same cell // whatever that column is called. func shownPrice(t *testing.T, page string) int64 { lines := strings.Split(page, "\n") for i, l := range lines { if !strings.HasPrefix(l, "| members") { continue } urequire.True(t, i+2 < len(lines), "the summary table has a row: "+page) cells := strings.Split(lines[i+2], "|") urequire.Equal(t, 6, len(cells), "four cells: "+lines[i+2]) return parseGNOT(t, strings.TrimSpace(cells[4])) } t.Fatalf("no summary table on the crew page: %s", page) return 0 } // parseGNOT turns num.GNOTf's "1.0015 GNOT" back into ugnot. func parseGNOT(t *testing.T, s string) int64 { urequire.True(t, strings.HasSuffix(s, " GNOT"), "a GNOT amount: "+s) s = strings.TrimSuffix(s, " GNOT") whole, frac := s, "" if i := strings.Index(s, "."); i >= 0 { whole, frac = s[:i], s[i+1:] } urequire.True(t, len(frac) <= 6, "at most six decimals: "+s) frac += strings.Repeat("0", 6-len(frac)) w, err := strconv.ParseInt(whole, 10, 64) urequire.NoError(t, err, s) f, err := strconv.ParseInt(frac, 10, 64) urequire.NoError(t, err, s) return w*1000000 + f }
- #14render.gno
- #15package crews import ( "strconv" "chain/runtime" "gno.land/p/moul/kit/num/v0" "gno.land/p/moul/kit/store/v0" "gno.land/p/moul/kit/ui/v0" "gno.land/p/moul/md/v0" "gno.land/p/moul/realmpath/v0" "gno.land/p/moul/x/social/crew/v0" "gno.land/p/moul/xmath/v1" ) // Render routes three views: the index, one crew, and one proposal. func Render(path string) string { req := realmpath.Parse(path) switch req.PathPart(0) { case "": return renderIndex() case "crew": return renderCrew(req.PathPart(1)) case "proposal": return renderProposal(req.PathPart(1)) default: return md.H1("Not found") + "No such view: " + ui.Inline(req.Path) } } func renderIndex() string { out := md.H1("Crews") out += "Three to fifteen people with a shared pot, a way to decide, and a way to " + "leave with their share. One transaction to start one.\n\n" t := ui.NewTable("crews", "proposals", "owed to people who left") t.Row( strconv.Itoa(crews.Len()), strconv.Itoa(crews.ProposalCount()), num.GNOTf(crews.TotalOwed()), ) out += t.String() out += md.H2("The crews") out += crewTable(crews.List(IndexCrews)) out += "\n" + ui.Action("Start a crew", "Create", "name", "") + "\n" out += md.H2("How a share works") out += md.BulletList([]string{ "A share is the vote weight and the claim on the treasury at once. There is no second token.", "Joining mints shares at what a share is worth NOW: " + md.InlineCode("amount * totalShares / treasury") + ", rounded down, so a late joiner cannot buy into value the others built.", "Ragequitting burns every share you hold and credits you " + md.InlineCode("shares * treasury / totalShares") + ", rounded down. Nobody has to agree.", "Both round in the crew's favour. The last member out holds every share, " + "so the treasury still empties to the last ugnot.", "A proposal is advisory text. Passing one records agreement and executes nothing.", }) out += md.H2("Custody") out += "One realm address holds every crew's treasury, with per-crew accounting " + "inside. A bug in that accounting is a bug across crews, not inside one. " + "The fix is one realm per crew, and it is v1.\n" return out } func renderCrew(raw string) string { id, ok := store.ParseID(raw) if !ok { return md.H1("Crews") + "Not a crew id: " + ui.Inline(raw) } c, found := crews.Get(id) if !found { return md.H1("Crews") + "No crew #" + id.String() } out := md.H1(ui.Inline(c.Name)) out += md.Italic("crew #"+id.String()+" · opened at block "+ strconv.FormatInt(c.CreatedAt, 10)) + "\n\n" t := ui.NewTable("members", "shares", "treasury", "to join") t.Row( strconv.Itoa(c.MemberCount())+" of "+strconv.Itoa(crew.MaxMembers), strconv.FormatInt(c.TotalShares, 10), num.GNOTf(c.Treasury), num.GNOTf(joinPrice(c)), ) out += t.String() out += md.H2("Members") if c.MemberCount() == 0 { out += ui.Empty("Everybody has left. The next member in pays the opening price again.") } else { m := ui.NewTable("member", "shares", "weight", "worth") for _, who := range c.Members() { shares := c.SharesOf(who) m.Row( ui.Addr(who), strconv.FormatInt(shares, 10), num.Pct(xmath.MulDiv(shares, 10000, c.TotalShares)), num.GNOTf(xmath.MulDiv(shares, c.Treasury, c.TotalShares)), ) } out += m.String() } out += md.H2("Proposals") out += proposalTable(c.Proposals()) out += "\nA proposal is advisory text. Passing one records that the crew agreed " + "by share weight, and executes nothing.\n" out += "\n" + ui.Join(" · ", ui.Action("Join", "Join", "crewID", id.String()), ui.Action("Fund", "Fund", "crewID", id.String()), ui.Action("Propose", "Propose", "crewID", id.String(), "text", ""), ui.Action("Ragequit", "Ragequit", "crewID", id.String()), ) + "\n" return out } func renderProposal(raw string) string { pid, ok := store.ParseID(raw) if !ok { return md.H1("Crews") + "Not a proposal id: " + ui.Inline(raw) } p, found := crews.Proposal(pid) if !found { return md.H1("Crews") + "No proposal #" + pid.String() } out := md.H1("Proposal #" + pid.String()) out += md.Blockquote(ui.Inline(p.Text)) + "\n" crewName := "crew #" + p.CrewID.String() if c, ok := crews.Get(p.CrewID); ok { crewName = c.Name } out += md.Italic("by "+ui.Addr(p.Author)+" · in "+ md.Link(ui.ShortN(crewName, crew.ExcerptLen, 0), crewURL(p.CrewID))) + "\n\n" now := runtime.ChainHeight() t := ui.NewTable("state", "yes", "no", "voters") t.Row( state(p, now), strconv.FormatInt(p.Yes, 10), strconv.FormatInt(p.No, 10), strconv.Itoa(p.Voters()), ) out += t.String() if p.Open(now) { out += "\n" + ui.Join(" · ", ui.Action("Vote yes", "Vote", "proposalID", pid.String(), "yes", "true"), ui.Action("Vote no", "Vote", "proposalID", pid.String(), "yes", "false"), ) + "\n" } else if !p.Closed { out += "\n" + ui.Action("Close it", "Close", "proposalID", pid.String()) + "\n" } return out } // crewTable lists crews, newest first. func crewTable(items []crew.Listing) string { t := ui.NewTable("crew", "members", "shares", "treasury") for _, it := range items { t.Row( // ShortN truncates without escaping and md.Link escapes what it // is given: ui.Inline here would escape twice and render the // backslashes. A pipe is what md.Link's escaper does NOT cover, // which is why crew.ValidName refuses one at write time. md.Link(ui.ShortN(it.Crew.Name, crew.ExcerptLen, 0), crewURL(it.ID)), strconv.Itoa(it.Crew.MemberCount()), strconv.FormatInt(it.Crew.TotalShares, 10), num.GNOTf(it.Crew.Treasury), ) } return t.OrEmpty("No crews yet.") } // proposalTable lists a crew's proposals, newest first. // // The link title is the id and not the text, which is the opposite of // crewTable and deliberate: a proposal's text is free prose and may contain a // pipe, md.Link's escaper leaves pipes alone, and a pipe in a link title inside // a table cell opens a column. So the chrome carries the link and the prose // goes through ui.Cell, which is the escaper that knows it is in a table. func proposalTable(ids []store.ID) string { now := runtime.ChainHeight() // Finding 325-cost-at-caps-1: this rendered every proposal a crew has // ever had, and proposing is open to every member with no delete path. // Newest first already, so the bound is on where the walk stops. total := len(ids) stop := 0 if total > IndexProposals { stop = total - IndexProposals } t := ui.NewTable("#", "proposal", "state", "yes", "no") for i := total - 1; i >= stop; i-- { p, ok := crews.Proposal(ids[i]) if !ok { continue } t.Row( md.Link("#"+ids[i].String(), proposalURL(ids[i])), // Cut on a rune boundary first, escape once after: escaping // first and cutting after can strand a lone backslash. ui.Cell(ui.ShortN(p.Text, crew.ExcerptLen, 0)), state(p, now), strconv.FormatInt(p.Yes, 10), strconv.FormatInt(p.No, 10), ) } out := t.OrEmpty("Nothing has been proposed yet.") if total > IndexProposals { out += md.Italic("Showing the newest "+strconv.Itoa(IndexProposals)+" of "+ strconv.Itoa(total)+" proposals.") + "\n" } return out } // state is the one word a proposal is in at height now. func state(p *crew.Proposal, now int64) string { switch { case p.Open(now): return "open until " + strconv.FormatInt(p.Deadline, 10) case !p.Closed: return "awaiting a close" case p.Passed: return "passed" default: return "failed" } } // crewURL is the gnoweb path of one crew. func crewURL(id store.ID) string { return realmURL() + ":crew/" + id.String() } // proposalURL is the gnoweb path of one proposal. func proposalURL(id store.ID) string { return realmURL() + ":proposal/" + id.String() } // realmURL is this realm's gnoweb path. The chain domain is the first element // of a package path and a gnoweb path is the rest of it, so this is a prefix // strip and not a hostname the realm has to know. func realmURL() string { for i := 0; i < len(realmPath); i++ { if realmPath[i] == '/' { return realmPath[i:] } } return "/" + realmPath }
Result log
msg:0,success:true,log:,events:[]