market.gno
18.34 Kb · 551 lines
1// Package market is the platform's immutable fixed-price market
2// (design §2.5.4). It never holds a token: the seller approves this
3// realm in core, the token stays in the seller's wallet, and Buy moves it
4// through core's official grc721 RealmTeller in the same transaction that
5// pays everyone. It never holds coins either (I-3).
6//
7// A token has at most one listing, addressed by (cid, tid). Stale listings
8// (RA H-2) cannot be bought: a listing pins the token's move counter and
9// core's approval nonces at listing time, and Buy requires owner == seller,
10// the counter unchanged and the approval it was listed under still in
11// place, unchanged (I-8). Once stale, a listing stays dead: approving the
12// market again later never revives it (SA-L3). A stale listing never blocks
13// the new owner: List overwrites it and anyone may CancelStale it.
14//
15// Storage (storage-cost-analysis M1-M3): a listing is one packed string in
16// `listings` (key cid:tid) plus one key in the price index `byCollection`
17// (floor, collection pages). Per-seller history comes from the indexer
18// ("Listed"/"Cancelled" events), not from an on-chain index.
19//
20// Deposit return: gno refunds a freed storage deposit to the signer of the
21// transaction that frees it, so a Buy hands the buyer the deposit the
22// seller locked for the listing (and for a per-token Approve, which the
23// transfer clears). Buy therefore charges the buyer that amount on top of
24// the price and pays it to the seller: listing.deposit, fixed at List from
25// the measured bytes (ListingDeposit, ApprovalDeposit). Net, the seller is
26// whole and the buyer pays the price (the chain's refund cancels the
27// extra) — up to the few bytes by which a real refund differs from the
28// estimate.
29//
30// Pause ("trade" in core) stops List and Buy only. Cancel, CancelStale and
31// UpdatePrice are never paused (I-2).
32package market
33
34import (
35 "chain"
36 "chain/banker"
37 "chain/runtime"
38 "chain/runtime/unsafe"
39 "strconv"
40 "strings"
41
42 "gno.land/p/nt/avl/v0"
43 "gno.land/p/nt/grc721/v0"
44
45 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
46 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/types/v1"
47 "gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/core"
48)
49
50const (
51 MaxPageSize = 50
52 priceWidth = 16 // types.MaxUnitPrice has 16 digits
53
54 // Deposit-return estimate (ugnot), from the bytes measured in this
55 // package's z_bytes_* filetests at gno.land's storage price of 100
56 // ugnot/byte (vm param storage_price on Onyx and gnoland-1). Re-measure
57 // before a deploy to a chain with another price.
58 StoragePrice = 100
59 ListingBytes = 4_090 // a listing while others are active (listings + byCollection keys)
60 ApprovalBytes = 2_044 // grc721 tokenApprovals entry of a per-token Approve, cleared by the transfer
61 ListingDeposit = ListingBytes * StoragePrice
62 ApprovalDeposit = ApprovalBytes * StoragePrice
63)
64
65// listing is the decoded form of one packed `listings` value.
66type listing struct {
67 cid, tid string
68 id int64
69 seller address
70 price int64
71 moves int64 // core.TokenMoves at listing time
72 height int64
73 feeBps int64 // protocol fee at listing time; a sale never pays more (SA-I5)
74 engBps int64 // engine-author fee at listing time; a sale never pays more
75 deposit int64 // deposit return the buyer pays the seller (from the approval path, not stored)
76 // approval the listing was made under (SA-L3): per-token and/or
77 // approval-for-all, each pinned to core's nonce at listing time
78 viaToken, viaAll bool
79 tokenNonce, operatorNonce int64
80}
81
82var (
83 listings avl.Tree // cid:tid -> packed listing (encode)
84 byCollection avl.Tree // cid:paddedPrice:tid -> "" (floor = first key)
85 nextID int64
86 selfPath string // captured in init for read paths without a cur
87)
88
89func init(cur realm) {
90 selfPath = cur.PkgPath()
91}
92
93// List offers a token of a Final collection at price (ugnot). The caller
94// must own it and have approved this realm (Approve or SetApprovalForAll in
95// core). A stale listing of the same token is replaced. Returns the
96// listing's sequence id (events); the listing itself is addressed by
97// (cid, tid).
98func List(cur realm, cid, tid string, price int64) string {
99 assertNoDeposit(cur)
100 assertTradeOpen()
101 assertPrice(price)
102 seller := cur.Previous().Address()
103 if core.Info(cid).State != types.StateFinal {
104 panic("tokens of this collection are locked until it is final")
105 }
106 owner, err := core.OwnerOf(cid, tid)
107 if err != nil {
108 panic(err)
109 }
110 if owner != seller {
111 panic("only the token owner can list it")
112 }
113 viaToken, viaAll := approvals(cid, tid, owner, cur.Address())
114 if !viaToken && !viaAll {
115 panic("approve the market for this token first: core.Approve(cid, tid, " + cur.Address().String() + ")")
116 }
117 if old, ok := lookup(cid, tid); ok {
118 if live(old, cur.Address()) {
119 panic("token is already listed as #" + itoa(old.id) + "; use UpdatePrice")
120 }
121 remove(old, "stale")
122 }
123
124 nextID++
125 tn, on := core.ApprovalNonces(cid, tid, owner, cur.Address())
126 _, engBps := core.EngineFee(cid)
127 l := &listing{
128 cid: cid, tid: tid, id: nextID, seller: seller, price: price,
129 moves: core.TokenMoves(cid, tid), height: runtime.ChainHeight(),
130 feeBps: core.FeeConfig().SecondaryBps, engBps: engBps,
131 viaToken: viaToken, viaAll: viaAll, tokenNonce: tn, operatorNonce: on,
132 }
133 l.deposit = depositOf(l.viaToken)
134 store(l)
135 chain.Emit("Listed", "id", itoa(l.id), "cid", cid, "tid", tid, "seller", seller.String(), "price", itoa(price),
136 "deposit", itoa(l.deposit))
137 return itoa(l.id)
138}
139
140// UpdatePrice changes the price of a live listing; Buy's expectedPrice
141// protects buyers from a change racing their purchase (RA M-10).
142func UpdatePrice(cur realm, cid, tid string, price int64) {
143 assertNoDeposit(cur)
144 assertPrice(price)
145 l := mustListing(cid, tid)
146 assertSeller(cur, l)
147 if !live(l, cur.Address()) {
148 panic("listing is stale; cancel it and list again")
149 }
150 byCollection.Remove(collectionKey(l))
151 l.price = price
152 store(l)
153 chain.Emit("PriceUpdated", "id", itoa(l.id), "cid", l.cid, "tid", l.tid, "price", itoa(price))
154}
155
156// Cancel removes the caller's listing (its storage deposit returns to the
157// caller). Never paused.
158func Cancel(cur realm, cid, tid string) {
159 assertNoDeposit(cur)
160 l := mustListing(cid, tid)
161 assertSeller(cur, l)
162 remove(l, "cancelled")
163}
164
165// CancelStale lets anyone remove a listing that can no longer be bought;
166// the freed deposit goes to the caller (gno's rule), a cleanup bounty.
167func CancelStale(cur realm, cid, tid string) {
168 assertNoDeposit(cur)
169 l := mustListing(cid, tid)
170 if live(l, cur.Address()) {
171 panic("listing is still valid")
172 }
173 remove(l, "stale")
174}
175
176// Buy pays exactly expectedPrice for the token's listing, plus the
177// listing's deposit return (see the package doc); excess attached ugnot is
178// refunded. Order: checks, remove the listing, move the token, then pay —
179// protocol fee to the treasury, royalty to the collection's sub-treasury
180// (then distributed to its payees), the engine author's fee, the rest plus
181// the deposit return to the seller. I-4: protocol + royalty + engine +
182// seller + refund == attached.
183func Buy(cur realm, cid, tid string, expectedPrice int64) {
184 paid := received(cur)
185 assertTradeOpen()
186 buyer := cur.Previous().Address()
187 l := mustListing(cid, tid)
188 if l.price != expectedPrice {
189 panic("price is " + itoa(l.price) + "ugnot, expected " + itoa(expectedPrice))
190 }
191 if paid < l.price+l.deposit {
192 panic("send " + itoa(l.price+l.deposit) + "ugnot (price " + itoa(l.price) + " + deposit return " +
193 itoa(l.deposit) + "), sent " + itoa(paid))
194 }
195 if buyer == l.seller {
196 panic("cannot buy your own listing")
197 }
198 if !live(l, cur.Address()) {
199 panic("listing is stale: the token moved or approval was revoked since it was listed")
200 }
201 remove(l, "sold")
202
203 tok := core.Token(l.cid)
204 if err := tok.RealmTeller(0, cur).TransferFrom(0, cur, l.seller, buyer, grc721.TokenID(l.tid)); err != nil {
205 panic(err)
206 }
207
208 s := settle(l)
209 pay(cur, s.treasury, s.protocol)
210 pay(cur, s.royaltyTo, s.royalty)
211 pay(cur, s.engineAuthor, s.engine)
212 pay(cur, l.seller, s.seller)
213 pay(cur, buyer, paid-l.price-l.deposit)
214 if s.royalty > 0 {
215 core.DistributeRoyalties(cross(cur), l.cid)
216 }
217 chain.Emit("Bought", "id", itoa(l.id), "cid", l.cid, "tid", l.tid,
218 "seller", l.seller.String(), "buyer", buyer.String(), "price", itoa(l.price),
219 "protocolFee", itoa(s.protocol), "royalty", itoa(s.royalty), "engineFee", itoa(s.engine),
220 "engineAuthor", s.engineAuthor.String(), "deposit", itoa(l.deposit))
221}
222
223// settlement is how a sale of l is paid now (I-4: protocol + royalty +
224// engine + seller == price + deposit).
225type settlement struct {
226 treasury, royaltyTo, engineAuthor address
227 protocol, royalty, engine, seller int64
228}
229
230func settle(l *listing) settlement {
231 fee := core.FeeConfig()
232 feeBps := fee.SecondaryBps
233 if l.feeBps < feeBps {
234 feeBps = l.feeBps
235 }
236 author, engBps := core.EngineFee(l.cid)
237 if l.engBps < engBps {
238 engBps = l.engBps
239 }
240 s := settlement{treasury: fee.Treasury, engineAuthor: author}
241 s.protocol = safe.BpsOf(l.price, feeBps)
242 s.engine = safe.BpsOf(l.price, engBps)
243 royaltyTo, royalty, err := core.Royalty(l.cid).RoyaltyInfo(grc721.TokenID(l.tid), l.price)
244 if err != nil {
245 panic(err)
246 }
247 s.royaltyTo, s.royalty = royaltyTo, royalty
248 s.seller = l.price - s.protocol - s.royalty - s.engine + l.deposit
249 return s
250}
251
252// --- reads ---------------------------------------------------------------------
253
254// Listing is the token's listing as JSON, stale ones included with
255// "live":false, or "null".
256func Listing(cid, tid string) string {
257 l, ok := lookup(cid, tid)
258 if !ok {
259 return "null"
260 }
261 w := &safe.JSONWriter{}
262 writeListingLive(w, l, live(l, selfAddress()))
263 return w.String()
264}
265
266// ListingOf is the live listing of a token as JSON, or "null".
267func ListingOf(cid, tid string) string {
268 l, ok := lookup(cid, tid)
269 if !ok || !live(l, selfAddress()) {
270 return "null"
271 }
272 w := &safe.JSONWriter{}
273 writeListingLive(w, l, true)
274 return w.String()
275}
276
277// ActiveListing is the typed read for other realms: the live listing of a
278// token, if any (id is the sequence id).
279func ActiveListing(cid, tid string) (id string, price int64, ok bool) {
280 l, found := lookup(cid, tid)
281 if !found || !live(l, selfAddress()) {
282 return "", 0, false
283 }
284 return itoa(l.id), l.price, true
285}
286
287// Quote is what Buy(cid, tid, price) costs and pays now, as JSON: {live,
288// id, seller, price, deposit, total (attach this), protocolFee, royalty,
289// royaltyTo, engineFee, engineAuthor, sellerProceeds}; "null" if unlisted.
290func Quote(cid, tid string) string {
291 l, ok := lookup(cid, tid)
292 if !ok {
293 return "null"
294 }
295 s := settle(l)
296 w := &safe.JSONWriter{}
297 w.BeginObject()
298 w.BoolField("live", live(l, selfAddress()))
299 w.StrField("id", itoa(l.id))
300 w.StrField("seller", l.seller.String())
301 w.IntField("price", l.price)
302 w.IntField("deposit", l.deposit)
303 w.IntField("total", l.price+l.deposit)
304 w.IntField("protocolFee", s.protocol)
305 w.IntField("royalty", s.royalty)
306 w.StrField("royaltyTo", s.royaltyTo.String())
307 w.IntField("engineFee", s.engine)
308 w.StrField("engineAuthor", s.engineAuthor.String())
309 w.IntField("sellerProceeds", s.seller)
310 w.EndObject()
311 return w.String()
312}
313
314// ListingsByCollection lists by ascending price. Stale listings are
315// included with "live":false so pages stay stable; frontends hide them.
316// Listings by seller: use the indexer (Listed / Cancelled events).
317func ListingsByCollection(cid string, offset, limit int64) string {
318 if limit <= 0 || limit > MaxPageSize {
319 limit = MaxPageSize
320 }
321 prefix := cid + ":"
322 self := selfAddress()
323 w := &safe.JSONWriter{}
324 w.BeginArray()
325 var skipped, written int64
326 byCollection.Iterate(prefix, prefixEnd(prefix), func(k string, _ any) bool {
327 if skipped < offset {
328 skipped++
329 return false
330 }
331 l := mustListing(cid, tidOfKey(k))
332 writeListingLive(w, l, live(l, self))
333 written++
334 return written >= limit
335 })
336 w.EndArray()
337 return w.String()
338}
339
340// Floor is the lowest live price in cid, or -1. It inspects at most
341// MaxPageSize listings from the cheapest, so spam cannot make it unbounded.
342func Floor(cid string) int64 {
343 floor := int64(-1)
344 seen := 0
345 prefix := cid + ":"
346 self := selfAddress()
347 byCollection.Iterate(prefix, prefixEnd(prefix), func(k string, _ any) bool {
348 seen++
349 l := mustListing(cid, tidOfKey(k))
350 if live(l, self) {
351 floor = l.price
352 return true
353 }
354 return seen >= MaxPageSize
355 })
356 return floor
357}
358
359func Render(path string) string {
360 return "# market/v1\n\n" + itoa(int64(listings.Size())) + " open listings. " +
361 "Read them with `ListingsByCollection` or browse the gallery.\n"
362}
363
364// --- internals -------------------------------------------------------------------
365
366// live: still owned by the seller, not moved since listing, and the
367// approval it was listed under is still in place and untouched since: a
368// per-token listing dies with any later Approve of that token, an
369// approval-for-all listing with any later SetApprovalForAll of the market
370// by the seller — even one that approves again (SA-L3).
371func live(l *listing, market address) bool {
372 owner, err := core.OwnerOf(l.cid, l.tid)
373 if err != nil || owner != l.seller || core.TokenMoves(l.cid, l.tid) != l.moves {
374 return false
375 }
376 viaToken, viaAll := approvals(l.cid, l.tid, owner, market)
377 tn, on := core.ApprovalNonces(l.cid, l.tid, owner, market)
378 return (l.viaToken && viaToken && tn == l.tokenNonce) || (l.viaAll && viaAll && on == l.operatorNonce)
379}
380
381// approvals reports whether market is approved for this token, and whether
382// it is approved for all of owner's tokens.
383func approvals(cid, tid string, owner, market address) (viaToken, viaAll bool) {
384 tok := core.Token(cid)
385 a, err := tok.GetApproved(grc721.TokenID(tid))
386 return err == nil && a == market, tok.IsApprovedForAll(owner, market)
387}
388
389// store writes l and its price-index key.
390func store(l *listing) {
391 listings.Set(tokenKey(l.cid, l.tid), encode(l))
392 byCollection.Set(collectionKey(l), "")
393}
394
395// remove deletes a listing and its index key; closed listings are not kept
396// (RA L-6), the "Cancelled" event (reason sold/cancelled/stale) is the record.
397func remove(l *listing, reason string) {
398 listings.Remove(tokenKey(l.cid, l.tid))
399 byCollection.Remove(collectionKey(l))
400 chain.Emit("Cancelled", "id", itoa(l.id), "cid", l.cid, "tid", l.tid, "reason", reason)
401}
402
403// encode packs a listing as one comma-separated string (M1: an inline avl
404// value instead of a *listing object, ~1.3 KB less per listing):
405// id,seller,price,moves,height,feeBps,engBps,flags,tokenNonce,operatorNonce
406// with flags = 1 (per-token) | 2 (for-all); the deposit return follows
407// from the flags (depositOf).
408func encode(l *listing) string {
409 flags := int64(0)
410 if l.viaToken {
411 flags |= 1
412 }
413 if l.viaAll {
414 flags |= 2
415 }
416 return itoa(l.id) + "," + l.seller.String() + "," + itoa(l.price) + "," + itoa(l.moves) + "," +
417 itoa(l.height) + "," + itoa(l.feeBps) + "," + itoa(l.engBps) + "," +
418 itoa(flags) + "," + itoa(l.tokenNonce) + "," + itoa(l.operatorNonce)
419}
420
421func decode(cid, tid, v string) *listing {
422 f := strings.Split(v, ",")
423 if len(f) != 10 {
424 panic("market: corrupt listing " + cid + ":" + tid)
425 }
426 n := func(i int) int64 {
427 x, err := strconv.ParseInt(f[i], 10, 64)
428 if err != nil {
429 panic("market: corrupt listing " + cid + ":" + tid)
430 }
431 return x
432 }
433 flags := n(7)
434 return &listing{
435 cid: cid, tid: tid, id: n(0), seller: address(f[1]), price: n(2), moves: n(3), height: n(4),
436 feeBps: n(5), engBps: n(6), deposit: depositOf(flags&1 != 0), viaToken: flags&1 != 0, viaAll: flags&2 != 0,
437 tokenNonce: n(8), operatorNonce: n(9),
438 }
439}
440
441// depositOf is a listing's deposit return: its own storage, plus the
442// per-token approval the sale's transfer clears (an approval-for-all
443// stays, so the seller keeps that deposit).
444func depositOf(viaToken bool) int64 {
445 if viaToken {
446 return ListingDeposit + ApprovalDeposit
447 }
448 return ListingDeposit
449}
450
451func lookup(cid, tid string) (*listing, bool) {
452 v := listings.Get(tokenKey(cid, tid))
453 if v == nil {
454 return nil, false
455 }
456 return decode(cid, tid, v.(string)), true
457}
458
459func mustListing(cid, tid string) *listing {
460 l, ok := lookup(cid, tid)
461 if !ok {
462 panic("token " + cid + ":" + tid + " is not listed")
463 }
464 return l
465}
466
467func writeListingLive(w *safe.JSONWriter, l *listing, isLive bool) {
468 w.BeginObject()
469 w.StrField("id", itoa(l.id))
470 w.StrField("cid", l.cid)
471 w.StrField("tid", l.tid)
472 w.StrField("seller", l.seller.String())
473 w.IntField("price", l.price)
474 w.IntField("deposit", l.deposit)
475 w.IntField("moves", l.moves)
476 w.IntField("height", l.height)
477 w.IntField("engineFeeBps", l.engBps)
478 w.BoolField("live", isLive)
479 w.EndObject()
480}
481
482func assertSeller(cur realm, l *listing) {
483 if cur.Previous().Address() != l.seller {
484 panic("only the seller can do this")
485 }
486}
487
488func assertTradeOpen() {
489 if core.Paused("trade") {
490 panic("paused: trade")
491 }
492}
493
494func assertPrice(price int64) {
495 if price <= 0 || price > types.MaxUnitPrice {
496 panic("price must be 1.." + itoa(types.MaxUnitPrice) + " ugnot")
497 }
498}
499
500func received(cur realm) int64 {
501 if !cur.Previous().IsUserCall() {
502 panic("payments must come directly from a wallet, not through another realm")
503 }
504 sent := unsafe.OriginSend()
505 for _, c := range sent {
506 if c.Denom != "ugnot" && c.Amount != 0 {
507 panic("only ugnot is accepted")
508 }
509 }
510 return sent.AmountOf("ugnot")
511}
512
513func assertNoDeposit(cur realm) {
514 if cur.Previous().IsUserCall() && !unsafe.OriginSend().IsZero() {
515 panic("this function does not accept coins")
516 }
517}
518
519func pay(cur realm, to address, amount int64) {
520 if amount <= 0 {
521 return
522 }
523 if to == cur.Address() {
524 panic("refusing to pay the market itself: the coins would be stranded (SA-L5)")
525 }
526 banker.NewBanker(banker.BankerTypeRealmSend, cur).
527 SendCoins(cur.Address(), to, chain.NewCoins(chain.NewCoin("ugnot", amount)))
528}
529
530// tokenKey is the listing key. cid and tid are canonical ids (core
531// accepted the token), so the key has one spelling per token.
532func tokenKey(cid, tid string) string { return cid + ":" + tid }
533
534// collectionKey orders a collection's listings by price; the tid is the
535// part after the last ':'.
536func collectionKey(l *listing) string {
537 return l.cid + ":" + safe.PadInt(l.price, priceWidth) + ":" + l.tid
538}
539
540func tidOfKey(k string) string { return k[strings.LastIndex(k, ":")+1:] }
541
542// prefixEnd is the smallest key greater than every key with this prefix
543// (prefixes here end in ':', so bump it to ';').
544func prefixEnd(prefix string) string {
545 return prefix[:len(prefix)-1] + string(rune(prefix[len(prefix)-1]+1))
546}
547
548func itoa(n int64) string { return strconv.FormatInt(n, 10) }
549
550// selfAddress is this realm's address for read paths that have no cur.
551func selfAddress() address { return chain.PackageAddress(selfPath) }