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