Playground
fee.gno
package nsmarket
import (
"strconv"
"strings"
"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
)
// The house fee, expressed the same way the pricing rules are so there
// is one convention on this project and not two:
//
// "1000000" a flat amount in ugnot — 1 GNOT
// "%3" three percent of the sale
// "%2.5" two and a half percent; one decimal place is honoured
//
// Stored in the vault as a global so it can be changed without
// redeploying anything, read fresh on every sale so a change takes
// effect immediately rather than at the next deploy.
const (
keyFee = "marketfee"
defaultFee = "1000000" // 1 GNOT
// A flat fee is a percentage in disguise on a cheap name: 1 GNOT on
// a 0.5 GNOT sale is 200%. Rather than forbid cheap listings or let
// a seller be charged more than they earn, the fee is capped at half
// the sale. The listing screen shows the seller the actual number
// before they sign, which is the part that matters.
maxFeeBps = int64(5000) // 50%
bpsDenom = int64(10000)
)
func FeeSpec() string {
if v := nsdata.GetGlobal(keyFee); v != "" {
return v
}
return defaultFee
}
// SetFee changes it. Admin only, and validated here rather than trusted,
// because a malformed spec would otherwise be read on every sale and
// silently resolve to zero.
/*
SetFee CANNOT WORK FROM HERE, and saying so is the fix.
nsdata.SetGlobalRecord opens with assertIsTrustedLogic, and this realm is
deliberately outside the trusted set — types.gno says so in capitals, and
the deploy panel actively revokes anything but nslogic. So every call
here passed its own admin check and its own validation and then panicked
inside the vault, for everybody, including the correct admin. A dead
control that reads as live is worse than no control: it fails at signing
time, during the incident that prompted reaching for it.
Granting nsmarket vault trust to fix this would surrender the property
the whole realm is built around. So the setter moved to nslogic, which
already has the grant, and runs the same parseFee validation there.
*/
func SetFee(cur realm, spec string) {
panic("nsmarket: fees are set with nslogic.SetMarketFee — this realm has no vault privileges and never did")
}
// parseFee returns (flat ugnot, basis points, error). Exactly one of the
// first two is non-zero.
func parseFee(spec string) (int64, int64, string) {
spec = strings.TrimSpace(spec)
if spec == "" {
return 0, 0, ""
}
if !strings.HasPrefix(spec, "%") {
n, err := strconv.ParseInt(spec, 10, 64)
if err != nil || n < 0 {
return 0, 0, "fee must be an amount in ugnot or a percentage like %2.5 — got " + spec
}
return n, 0, ""
}
// A percentage, carried as basis points so "%2.5" is expressible
// without floating point anywhere near money.
body := spec[1:]
whole, frac := body, ""
if dot := strings.Index(body, "."); dot >= 0 {
whole, frac = body[:dot], body[dot+1:]
}
if whole == "" {
whole = "0"
}
w, err := strconv.ParseInt(whole, 10, 64)
if err != nil || w < 0 {
return 0, 0, "bad percentage — " + spec
}
bps := w * 100
if frac != "" {
if len(frac) > 1 {
return 0, 0, "one decimal place at most — " + spec
}
f, err2 := strconv.ParseInt(frac, 10, 64)
if err2 != nil || f < 0 {
return 0, 0, "bad percentage — " + spec
}
bps += f * 10
}
if bps > maxFeeBps {
return 0, 0, "a fee above 50% is not a marketplace — " + spec
}
return 0, bps, ""
}
// FeeFor is what the house takes on a sale at this price, and what the
// seller is left with. Exported so the listing screen can show both
// before anybody signs — a fee somebody discovers afterwards is a fee
// they were not told about.
func FeeFor(price int64) (fee, toSeller int64) {
if price <= 0 {
return 0, 0
}
flat, bps, err := parseFee(FeeSpec())
if err != "" {
return 0, price // an unreadable spec charges nothing; it never overcharges
}
if bps > 0 {
fee = price * bps / bpsDenom
} else {
fee = flat
}
// The cap, applied last, so it bounds a flat fee and a percentage
// alike however the spec was written.
if ceiling := price * maxFeeBps / bpsDenom; fee > ceiling {
fee = ceiling
}
if fee < 0 {
fee = 0
}
return fee, price - fee
}
func assertIsAdmin(cur realm) {
if cur.Previous().Address() != nsdata.GetAdmin() {
panic("nsmarket: restricted to project admin")
}
}
gnomod.toml
module = "gno.land/r/nym-mnsrehearsal001/nsmarket/v2" gno = "0.9" [addpkg] creator = "g1lh4rrf9pq9k9tvka9p6vwhyv70e4h09szap6zu" height = 453095 max_deposit = "5000000ugnot"
market.gno
package nsmarket
import (
"strings"
"time"
"chain"
"chain/banker"
"chain/runtime/unsafe"
"gno.land/p/nt/ufmt/v0"
"gno.land/r/nym-mnsrehearsal001/nsdata/v2"
"gno.land/r/nym-mnsrehearsal001/nsnft/v2"
)
// List puts a name up for sale at a price in ugnot.
//
// It does NOT take the name. The seller keeps it, keeps using it, and
// keeps the right to change their mind — revoking the approval stops the
// listing from completing without needing this realm's cooperation.
// (It does not DELETE the listing: this realm is not told. Unlist, or
// anyone's Prune, clears it. See staleReason.)
//
// The approval is required BEFORE listing rather than checked only at
// sale time, so a listing that could never complete cannot exist. A
// buyer finding out at the checkout that the seller never approved
// anything is the worst moment to find out.
func List(cur realm, tid string, price int64) {
assertNoSend()
seller := cur.Previous().Address()
marketAddr = cur.Address()
label, domainLabel := splitTokenID(tid)
if label == "" || domainLabel == "" {
panic("nsmarket: a token id looks like label*domain")
}
if strings.HasPrefix(tid, "*") {
panic("nsmarket: domains are project-owned and not for sale")
}
if price < minPrice || price > maxPrice {
panic("nsmarket: price out of range")
}
// A frozen name should not sit on the marketplace advertising itself.
// nsnft would refuse the transfer anyway; a buyer should not find out
// by paying.
if !nsdata.NameExists(label, domainLabel) {
panic("nsmarket: no such name")
}
_, registered, _, _, frozen, _ := nsdata.GetNameInfo(label, domainLabel)
if frozen {
panic("nsmarket: this name is frozen and cannot be listed or sold")
}
if nsdata.GetNameOwner(label, domainLabel) != seller {
panic("nsmarket: only the owner may list a name")
}
// An expired name must not be sold here. Saying so at listing time
// rather than letting somebody list it and take an offer.
if !nsdata.IsNameValid(label, domainLabel) {
panic("nsmarket: this name has expired — renew it before selling it")
}
if !nsdata.IsNamePaid(label, domainLabel) {
panic("nsmarket: a free-tier name cannot be sold — upgrade it first")
}
// A hold for any other reason — frozen is the one today — stops the
// listing here rather than at checkout.
if nsnft.IsLocked(tid) {
panic("nsmarket: this name is held by the registry and cannot be sold")
}
if !approvedTo(cur.Address(), seller, tid) {
panic("nsmarket: approve the marketplace for this name first, so a sale can complete in one transaction")
}
listings.Set(tid, &Listing{seller: seller, price: price,
listed: time.Now().Unix(), registered: registered, epoch: nsnft.Epoch(tid)})
chain.Emit("Listed", "tid", tid, "price", ufmt.Sprintf("%d", price), "seller", seller.String())
}
// Unlist withdraws a listing. The seller, or the admin for a name that
// should not be on sale at all — the same manual lever the takedown
// process already relies on elsewhere.
func Unlist(cur realm, tid string) {
assertNoSend()
caller := cur.Previous().Address()
l := get(tid)
if l == nil {
panic("nsmarket: not listed")
}
if caller != l.seller && caller != nsdata.GetAdmin() {
panic("nsmarket: only the seller may withdraw a listing")
}
listings.Remove(tid)
chain.Emit("Unlisted", "tid", tid)
}
/*
Prune clears a listing that can no longer complete. Anyone may call it.
WHY ANYONE. A listing goes stale without this realm hearing about it: the
name is transferred elsewhere, lapses, is frozen, or the seller revokes
the approval. Buy refuses such a listing — but a refusal is a panic, and a
panic reverts everything, including any attempt to delete the listing on
the way out. Found on Pearl, 2026-09-10: three refused buys, three
listings still stored, each message saying "the listing is gone".
A stale listing is not harmless while it sits there. Revoking the approval
is how a seller would naturally "cancel"; if that seller later grants the
marketplace an operator approval to list something else, the old listing
completes again, at the old price. Clearing it is the fix, and nobody
should have to wait for the seller to think of it.
The caller gains nothing but the storage deposit the listing held, which
the chain refunds to whoever frees storage. That is the right incentive:
the only thing Prune can do is remove a listing that is already dead —
staleReason must name a reason, or it refuses.
*/
func Prune(cur realm, tid string) {
assertNoSend()
l := get(tid)
if l == nil {
panic("nsmarket: not listed")
}
why := staleReason(cur.Address(), tid, l)
if why == "" {
panic("nsmarket: this listing can still complete — only the seller may withdraw it")
}
listings.Remove(tid)
chain.Emit("Pruned", "tid", tid, "reason", why)
}
// Buy completes a sale in the buyer's own transaction.
//
// Order matters here. Everything that can refuse the sale is checked
// before a single coin moves, and the name moves before the money does,
// so there is no arrangement of failures that leaves the seller paid and
// the buyer empty-handed. A panic anywhere reverts all of it.
func Buy(cur realm, tid string) {
if !cur.Previous().IsUserCall() {
panic("nsmarket: only direct wallet calls may buy")
}
buyer := cur.Previous().Address()
l := get(tid)
if l == nil {
panic("nsmarket: not listed")
}
// The world can have moved since the listing was written. The refusal
// cannot also delete the listing — see Prune for why.
if why := staleReason(cur.Address(), tid, l); why != "" {
panic("nsmarket: " + why + " — this listing can no longer complete (anyone may clear it with Prune)")
}
if buyer == l.seller {
panic("nsmarket: you already own this")
}
sent := unsafe.OriginSend()
for _, c := range sent {
if c.Denom != ugnot {
panic("nsmarket: only ugnot is accepted, got: " + c.Denom)
}
}
paid := sent.AmountOf(ugnot)
if paid < l.price {
panic(ufmt.Sprintf("nsmarket: %d ugnot short of the asking price", l.price-paid))
}
// The name first. If this fails nothing has been paid out yet, and
// the revert takes the buyer's coins back with it.
//
// ON nsnft, AS THE APPROVED OPERATOR — exactly the call any external
// marketplace makes. This realm has no privileged transfer path, which
// is the point: the sale is only possible because the seller approved
// this realm on the ledger.
nsnft.TransferFrom(cross(cur), l.seller, buyer, tid)
fee, toSeller := FeeFor(l.price)
b := banker.NewBanker(banker.BankerTypeRealmSend, cur)
self := cur.Address()
if toSeller > 0 {
b.SendCoins(self, l.seller, chain.Coins{chain.NewCoin(ugnot, toSeller)})
}
if fee > 0 {
b.SendCoins(self, nsdata.GetTreasury(), chain.Coins{chain.NewCoin(ugnot, fee)})
}
if excess := paid - l.price; excess > 0 {
b.SendCoins(self, buyer, chain.Coins{chain.NewCoin(ugnot, excess)})
}
listings.Remove(tid)
sold++
chain.Emit("Sold", "tid", tid, "price", ufmt.Sprintf("%d", l.price),
"seller", l.seller.String(), "buyer", buyer.String(),
"fee", ufmt.Sprintf("%d", fee))
}
// -- helpers --
func get(tid string) *Listing {
v := listings.Get(tid)
if v == nil {
return nil
}
return v.(*Listing)
}
/*
staleReason says why a listing can no longer complete, or "" when it can.
ONE ANSWER FOR THREE CALLERS. Buy refuses on it, Prune clears on it, and
the reads report live=false on it. They used to be three separate lists of
checks, and the reads' list had no approval check: a listing whose seller
had revoked permission showed as live, with an enabled Buy button, and
failed at the checkout.
Each of these is a real thing that happens, not a defensive flourish:
- changed hands: the seller transferred the name elsewhere
- lapsed and re-registered: owner and validity match again, but it is
not the asset the listing was written against (Listing.registered)
- sold and bought back: same owner, same registration, but a different
ownership epoch — an operator grant survives transfers (Listing.epoch)
- withdrawn permission: the seller revoked the approval
*/
func staleReason(self address, tid string, l *Listing) string {
label, domainLabel := splitTokenID(tid)
if !nsdata.NameExists(label, domainLabel) {
return "this name no longer exists"
}
_, registered, _, _, frozen, _ := nsdata.GetNameInfo(label, domainLabel)
if frozen || nsnft.IsLocked(tid) {
return "this name is frozen"
}
if nsdata.GetNameOwner(label, domainLabel) != l.seller {
return "this name has changed hands since it was listed"
}
if !nsdata.IsNameValid(label, domainLabel) {
return "this name has expired"
}
// Zero means written before the field existed: unpinned, not mismatched.
if l.registered != 0 && registered != l.registered {
return "this name lapsed and was registered again since it was listed"
}
if l.epoch != 0 && l.epoch != nsnft.Epoch(tid) {
return "this name has changed hands since it was listed"
}
if self == "" || !approvedTo(self, l.seller, tid) {
return "the seller has withdrawn permission"
}
return ""
}
// Whether this realm may move that token on the seller's behalf. Either
// form of GRC-721 permission counts: approved for the one token, or an
// operator for everything the seller holds.
//
// `self` is threaded in from the caller rather than looked up, because a
// realm can only learn its own address from its own `cur`.
func approvedTo(self, seller address, tid string) bool {
if nsdata.IsApprovedForAll(seller, self) {
return true
}
return nsdata.GetApproved(tid) == self
}
func splitTokenID(tid string) (label, domainLabel string) {
at := strings.Index(tid, "*")
if at < 1 || at == len(tid)-1 {
return "", ""
}
return tid[:at], tid[at+1:]
}
// This realm takes no payment on anything except Buy.
func assertNoSend() {
if !unsafe.OriginSend().IsZero() {
panic("nsmarket: this function takes no payment; do not attach coins")
}
}
read.gno
package nsmarket
import (
"strings"
"gno.land/p/nt/ufmt/v0"
)
// Reads for the site. Rows are ";"-separated records of
// "label*domain,price,seller,listed,live" where `live` is false when the
// listing has gone stale under it — the seller moved the name, let it
// lapse, or revoked permission.
//
// Stale listings are REPORTED, not hidden and not silently deleted.
// Hiding them makes a seller's page lie about what they have up; and
// deleting them would mean a read function writing to storage, which is
// how a query starts costing gas. Prune is the write that clears them.
func row(tid string, l *Listing) string {
live := staleReason(marketAddr, tid, l) == ""
return ufmt.Sprintf("%s,%d,%s,%d,%t", tid, l.price, l.seller.String(), l.listed, live)
}
// GetListing returns one row, or "" when nothing is listed.
func GetListing(tid string) string {
l := get(tid)
if l == nil {
return ""
}
return row(tid, l)
}
// ListForSale pages through everything on offer, cheapest first within a
// page. `after` is the last token id of the previous page.
func ListForSale(after string, limit int) (rows, next string) {
if limit <= 0 || limit > maxPage {
limit = maxPage
}
var out []string
var last string
listings.Iterate(after, "", func(key string, v any) bool {
if key == after {
return false // the cursor is exclusive
}
out = append(out, row(key, v.(*Listing)))
last = key
return len(out) >= limit
})
if len(out) < limit {
last = "" // the end; no cursor to hand back
}
return strings.Join(out, ";"), last
}
// ListingsBy is everything one wallet has up for sale. Walks the whole
// tree because listings are keyed by token id, not by seller: a second
// index would be a second thing to keep correct and a second thing the
// seller pays storage for, to save a walk over a list that is small by
// construction.
func ListingsBy(seller address) string {
var out []string
listings.Iterate("", "", func(key string, v any) bool {
l := v.(*Listing)
if l.seller == seller {
out = append(out, row(key, l))
}
return false
})
return strings.Join(out, ";")
}
func CountListed() int64 { return int64(listings.Size()) }
func CountSold() int64 { return sold }
// Quote is what a buyer pays and what the seller receives, before
// anybody signs anything. The fee is read live, so this is the same
// arithmetic Buy will do rather than a copy of it that can drift.
func Quote(tid string) (price, fee, toSeller int64) {
l := get(tid)
if l == nil {
return 0, 0, 0
}
f, s := FeeFor(l.price)
return l.price, f, s
}
// Version lets the site tell which shape it is talking to without
// guessing from a function signature.
func Version() string { return "v1" }
types.gno
// nsmarket — names for sale, without anybody holding anything.
//
// HOW A SALE WORKS, and why it is built this way.
//
// The seller keeps their name. Listing does not move it here: it records
// an asking price and relies on the GRC-721 approval the seller has
// already granted this realm. Ownership does not change until somebody
// buys, and the seller can walk away at any moment by revoking the
// approval — at which point the listing simply stops working.
//
// The buyer's money is never held either. Buy is ONE call: it checks the
// listing still stands, moves the name, pays the seller, takes the fee,
// refunds any overpayment. All of it inside the transaction the buyer
// signed. If any part fails the whole thing reverts and nothing moved.
//
// Which means: at no point does this realm hold somebody else's name or
// somebody else's money. That is not a nice-to-have. An escrow that
// holds either one is a different kind of business, with a different set
// of rules, run by people with licences.
//
// THIS REALM HAS NO VAULT PRIVILEGES. It is not in nsdata's trusted set
// and does not ask to be. Every transfer goes through nslogic's ordinary
// GRC-721 path, which means it can only move a name the owner has
// explicitly approved — the same permission any other marketplace would
// need. However wrong the code below turns out to be, the worst it can
// do is fail.
package nsmarket
import (
"gno.land/p/nt/avl/v0"
)
// A listing. Kept small on purpose: the seller pays to store it, and
// everything derivable is derived rather than copied. The seller's
// address is here because the name can change hands outside this realm
// and a stale seller must be caught, not trusted.
type Listing struct {
seller address
price int64 // ugnot
listed int64 // unix seconds
/* PINNED TO ONE REGISTRATION, the same way nsskin pins a binding.
Without it a listing outlives the registration it was made
against: list at 50 GNOT having granted SetApprovalForAll, let the
name lapse, re-register it yourself — the burn clears the
per-token approval but NOT the operator grant, so owner matches,
IsNameValid is true, and any passer-by executes the year-old
listing against the name you just paid to get back. */
registered int64
/* PINNED TO ONE OWNERSHIP EPOCH as well as one registration.
The registration pin does not catch a name that was SOLD AND BOUGHT
BACK: owner matches, the name is valid, the registration date never
changed, and an operator grant (SetApprovalForAll) survives
transfers — so a seller who listed, sold elsewhere and later bought
the name back found their old listing executable by anyone at the old
price. The ledger's epoch moves on every transfer, so it catches it.
Zero means a listing written before this field, treated as unpinned. */
epoch int64
}
var (
// Keyed by token id, "label*domain".
listings avl.Tree
sold int64 // completed sales, for the honest version of a stat
/* This realm's own address, remembered by List. The reads need it to
ask whether the seller's approval still names this realm, and a read
has no `cur` to learn it from. Nothing can be listed before List
runs, so it is always set when a listing exists to be read. */
marketAddr address
)
/*
WHO PAYS FOR A LISTING'S STORAGE, AND WHO GETS IT BACK. Measured on Pearl,
2026-09-10. The seller's List transaction pays the storage deposit for the
listing. The chain refunds a deposit to whoever's transaction FREES the
storage, so when Buy removes the listing the refund goes to the BUYER: the
buyer's balance fell by 0.31 GNOT less than price plus gas. Unlist refunds
the seller, and Prune refunds whoever prunes.
This is gno's rule, not ours, and it cannot be routed elsewhere. The amount
is small, but the site's quote should not promise a seller "price minus
fee" as if listing were free: listing costs the deposit, recovered only by
unlisting.
*/
const (
maxPage = 200
minPrice = int64(1) // zero would be a giveaway, not a sale
maxPrice = int64(1) << 52 // guards the fee arithmetic from overflow
ugnot = "ugnot"
)