Playground
collection.gno
package shop
import (
"strconv"
"chain"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/grc721/enumerable/v0"
"gno.land/p/nt/grc721/metadata/v0"
"gno.land/p/nt/grc721/v0"
"gno.land/p/nt/seqid/v0"
)
const (
maxImageLen = 200
maxTidLen = 64
saleCap = 100
pageMax = 50
)
var (
token *grc721.Token
ledger *grc721.PrivateLedger
metaView *metadata.Metadata
metaLed *metadata.Ledger
enumView *enumerable.Enumerable
tokenSeq seqid.ID
creator address
ready bool
admins avl.Tree
listings avl.Tree
sales [saleCap]sale
saleN int
)
type listing struct {
Seller address
Price int64
}
type sale struct {
Tid string
Seller address
Buyer address
Price int64
Name string
}
// Init creates the collection once. The caller is the creator and can mint.
func Init(cur realm, name, symbol string) {
caller := requireUser(cur)
if ready {
panic("market: already init")
}
token, ledger = grc721.NewToken(name, symbol, tokenSeq.Next(), cur)
metaView, metaLed = metadata.NewMetadata(ledger)
enumView, _ = enumerable.NewEnumerable(ledger)
creator = caller
ready = true
chain.Emit("Init", "creator", caller.String(), "name", name, "symbol", symbol)
}
// Grant lets who mint. Only the creator can call it.
func Grant(cur realm, who address) {
caller := requireUser(cur)
requireReady()
if caller != creator || !who.IsValid() || who == creator {
panic("market: admin")
}
admins.Set(who.String(), true)
chain.Emit("Grant", "admin", who.String())
}
// Revoke removes a minter. Only the creator can call it.
func Revoke(cur realm, who address) {
caller := requireUser(cur)
requireReady()
if caller != creator {
panic("market: admin")
}
if _, removed := admins.Remove(who.String()); !removed {
panic("market: admin")
}
chain.Emit("Revoke", "admin", who.String())
}
func canMint(caller address) bool {
if caller == creator {
return true
}
return admins.Get(caller.String()) != nil
}
// Mint issues one token to the caller. image is an https URL.
func Mint(cur realm, tid, name, image string) {
caller := requireUser(cur)
requireReady()
if !canMint(caller) {
panic("market: not minter")
}
id := parseTid(tid)
if name == "" || len(name) > grc721.MaxNameLen || !ascii(name) {
panic("market: name")
}
if !httpsURL(image) {
panic("market: image")
}
if err := ledger.Mint(caller, id); err != nil {
panic("market: mint")
}
if err := metaLed.SetTokenURI(id, image); err != nil {
panic("market: tokenURI")
}
if err := metaLed.SetTokenMetadata(id, metadata.Data{
Name: name,
Description: name,
Image: image,
}); err != nil {
panic("market: metadata")
}
chain.Emit("Mint", "tid", tid, "owner", caller.String(), "name", name)
}
// Transfer moves a token the caller owns.
func Transfer(cur realm, to address, tid string) {
caller := requireUser(cur)
requireReady()
if !to.IsValid() || to == caller {
panic("market: to")
}
id := parseTid(tid)
if err := ledger.TransferFrom(caller, caller, to, id); err != nil {
panic("market: transfer")
}
}
func requireReady() {
if !ready {
panic("market: call Init")
}
}
func requireUser(cur realm) address {
prev := cur.Previous()
if !prev.IsUserCall() {
panic("market: eoa")
}
return prev.Address()
}
func parseTid(tid string) grc721.TokenID {
if tid == "" || len(tid) > maxTidLen || !ascii(tid) {
panic("market: tid")
}
for i := 0; i < len(tid); i++ {
c := tid[i]
ok := (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-'
if !ok {
panic("market: tid")
}
}
return grc721.TokenID(tid)
}
func httpsURL(s string) bool {
const prefix = "https://"
if len(s) < len(prefix)+1 || len(s) > maxImageLen || !ascii(s) {
return false
}
return s[:len(prefix)] == prefix
}
func ascii(s string) bool {
for i := 0; i < len(s); i++ {
if s[i] < 0x20 || s[i] > 0x7e {
return false
}
}
return true
}
func ownerOf(tid grc721.TokenID) address {
owner, err := token.OwnerOf(tid)
if err != nil {
panic("market: owner")
}
return owner
}
func metaNameImage(tid grc721.TokenID) (string, string) {
data, err := metaView.TokenMetadata(tid)
if err != nil {
return "", ""
}
return data.Name, data.Image
}
func page(offset, limit int) (int, int) {
if offset < 0 {
offset = 0
}
if limit < 1 {
limit = 1
}
if limit > pageMax {
limit = pageMax
}
return offset, limit
}
func quote(s string) string {
out := "\""
for i := 0; i < len(s); i++ {
c := s[i]
if c == '\\' || c == '"' {
out += "\\"
}
out += s[i : i+1]
}
return out + "\""
}
func i64(n int64) string {
return strconv.FormatInt(n, 10)
}
gnomod.toml
module = "gno.land/r/g1a0cdtzx9tyx2gd9mszuvfgl8t5wvw8lzna4ujr/shop" gno = "0.9" private = true [addpkg] creator = "g1a0cdtzx9tyx2gd9mszuvfgl8t5wvw8lzna4ujr" height = 804070 max_deposit = "50000000ugnot"
trade.gno
package shop
import (
"chain"
"chain/banker"
"chain/runtime/unsafe"
"gno.land/p/nt/grc721/v0"
)
// List puts tid on sale for price ugnot. The token stays with the owner.
// A dead listing (the recorded seller no longer owns it) is replaced.
func List(cur realm, tid string, price int64) {
caller := requireUser(cur)
requireReady()
if price < 1 {
panic("market: price")
}
id := parseTid(tid)
if ownerOf(id) != caller {
panic("market: not owner")
}
listings.Set(string(id), listing{Seller: caller, Price: price})
chain.Emit("List", "tid", string(id), "seller", caller.String(), "price", i64(price))
}
// Cancel removes the caller's listing, or a listing whose seller no longer owns the token.
func Cancel(cur realm, tid string) {
caller := requireUser(cur)
requireReady()
id := parseTid(tid)
lot := mustListing(id)
if caller != lot.Seller && caller != ownerOf(id) {
panic("market: cancel")
}
listings.Remove(string(id))
chain.Emit("Cancel", "tid", string(id), "caller", caller.String())
}
// Buy pays the listing price in ugnot and takes the token.
// The attached send must be exactly the price, one ugnot coin.
func Buy(cur realm, tid string) {
caller := requireUser(cur)
requireReady()
id := parseTid(tid)
lot := mustListing(id)
if caller == lot.Seller {
panic("market: self")
}
if ownerOf(id) != lot.Seller {
panic("market: stale")
}
paid := unsafe.OriginSend()
if len(paid) != 1 || paid[0].Denom != "ugnot" || paid[0].Amount != lot.Price {
panic("market: pay")
}
if err := ledger.TransferFrom(lot.Seller, lot.Seller, caller, id); err != nil {
panic("market: transfer")
}
coins := chain.NewCoins(chain.NewCoin("ugnot", lot.Price))
bank := banker.NewBanker(banker.BankerTypeOriginSend, cur)
bank.SendCoins(cur.Address(), lot.Seller, coins)
listings.Remove(string(id))
name, _ := metaNameImage(id)
pushSale(sale{Tid: string(id), Seller: lot.Seller, Buyer: caller, Price: lot.Price, Name: name})
chain.Emit(
"Buy",
"tid", string(id),
"seller", lot.Seller.String(),
"buyer", caller.String(),
"price", i64(lot.Price),
)
}
func mustListing(id grc721.TokenID) listing {
got := listings.Get(string(id))
if got == nil {
panic("market: no listing")
}
return got.(listing)
}
func pushSale(s sale) {
sales[saleN%saleCap] = s
saleN++
}
views.gno
package shop
import "strconv"
// InfoJSON is the collection header. ready is false until Init.
func InfoJSON() string {
if !ready {
return `{"ready":false}`
}
return `{"ready":true,"name":` + quote(token.GetName()) +
`,"symbol":` + quote(token.GetSymbol()) +
`,"creator":` + quote(creator.String()) +
`,"admins":` + adminsJSON() +
`,"supply":` + i64(token.TotalSupply()) +
`,"listings":` + strconv.Itoa(listings.Size()) + `}`
}
func adminsJSON() string {
parts := make([]string, 0)
admins.IterateByOffset(0, pageMax, func(key string, value any) bool {
parts = append(parts, quote(key))
return false
})
return "[" + join(parts) + "]"
}
// ListingsJSON returns one page of listings, oldest key first.
func ListingsJSON(offset, limit int) string {
if !ready {
return "[]"
}
offset, limit = page(offset, limit)
parts := make([]string, 0)
listings.IterateByOffset(offset, limit, func(key string, value any) bool {
parts = append(parts, lotJSON(key, value.(listing)))
return false
})
return "[" + join(parts) + "]"
}
// ListingJSON returns one listing or "null".
func ListingJSON(tid string) string {
if !ready {
return "null"
}
id := parseTid(tid)
got := listings.Get(string(id))
if got == nil {
return "null"
}
return lotJSON(string(id), got.(listing))
}
// TokenJSON returns one token, listed or not.
func TokenJSON(tid string) string {
if !ready {
return "null"
}
id := parseTid(tid)
owner := ownerOf(id)
name, image := metaNameImage(id)
body := `{"tid":` + quote(string(id)) +
`,"owner":` + quote(owner.String()) +
`,"name":` + quote(name) +
`,"image":` + quote(image)
got := listings.Get(string(id))
if got == nil {
return body + `,"listed":false}`
}
lot := got.(listing)
return body + `,"listed":true,"seller":` + quote(lot.Seller.String()) +
`,"price":` + i64(lot.Price) +
`,"live":` + boolJSON(owner == lot.Seller) + `}`
}
// TokensJSON lists tokens owned by owner.
func TokensJSON(owner address, offset, limit int) string {
if !ready {
return "[]"
}
if !owner.IsValid() {
panic("market: owner")
}
offset, limit = page(offset, limit)
balance, err := token.BalanceOf(owner)
if err != nil {
panic("market: balance")
}
parts := make([]string, 0)
end := int64(offset + limit)
for i := int64(offset); i < balance && i < end; i++ {
id, err := enumView.TokenOfOwnerByIndex(owner, i)
if err != nil {
panic("market: index")
}
name, image := metaNameImage(id)
item := `{"tid":` + quote(string(id)) + `,"name":` + quote(name) + `,"image":` + quote(image)
got := listings.Get(string(id))
if got == nil {
item += `,"listed":false}`
} else {
lot := got.(listing)
item += `,"listed":true,"price":` + i64(lot.Price) + `}`
}
parts = append(parts, item)
}
return "[" + join(parts) + "]"
}
// SalesJSON returns the newest sales first.
func SalesJSON(offset, limit int) string {
if !ready {
return "[]"
}
offset, limit = page(offset, limit)
n := saleN
if n > saleCap {
n = saleCap
}
parts := make([]string, 0)
for i := offset; i < offset+limit && i < n; i++ {
// i = 0 is the newest stored sale.
idx := saleN - 1 - i
s := sales[idx%saleCap]
parts = append(parts, `{"tid":`+quote(s.Tid)+
`,"name":`+quote(s.Name)+
`,"seller":`+quote(s.Seller.String())+
`,"buyer":`+quote(s.Buyer.String())+
`,"price":`+i64(s.Price)+`}`)
}
return "[" + join(parts) + "]"
}
func lotJSON(tid string, lot listing) string {
id := parseTid(tid)
owner := ownerOf(id)
name, image := metaNameImage(id)
return `{"tid":` + quote(tid) +
`,"seller":` + quote(lot.Seller.String()) +
`,"owner":` + quote(owner.String()) +
`,"price":` + i64(lot.Price) +
`,"name":` + quote(name) +
`,"image":` + quote(image) +
`,"live":` + boolJSON(owner == lot.Seller) + `}`
}
func boolJSON(v bool) string {
if v {
return "true"
}
return "false"
}
func join(parts []string) string {
out := ""
for i, p := range parts {
if i > 0 {
out += ","
}
out += p
}
return out
}
func Render(path string) string {
if path != "" {
return "404\n"
}
if !ready {
return "# market\n\ncall Init first\n"
}
return "# " + token.GetName() + " ($" + token.GetSymbol() + ")\n\n" +
"* creator: " + creator.String() + "\n" +
"* supply: " + i64(token.TotalSupply()) + "\n" +
"* listings: " + strconv.Itoa(listings.Size()) + "\n"
}