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