Playground
admin.gno
package rooms
import "chain"
// The admin can pause new activity, set the fee for rooms opened later (at
// most MaxFeeBps), move the treasury, and verify assets, each verification
// counting only VerifyDelay later. A pause stops Open, Join, deposits, Lock,
// Offer and Fill; it never stops Withdraw, Unlock or Cancel, so deposits
// can always leave. The admin has no way to move anyone's assets.
var (
admin address // set to the deployer in init
pendingAdmin address
paused bool
)
// SetPaused stops or resumes new activity.
func SetPaused(cur realm, value bool) {
assertAdmin(cur)
paused = value
state := "resumed"
if value {
state = "paused"
}
chain.Emit("Paused", "state", state)
}
// ProposeAdmin names the next admin; the change happens when that address
// calls AcceptAdmin. Pass "" to withdraw a proposal.
func ProposeAdmin(cur realm, next string) {
assertAdmin(cur)
if next == "" {
pendingAdmin = ""
return
}
addr := address(next)
if !addr.IsValid() {
panic("next admin is not a valid address")
}
pendingAdmin = addr
chain.Emit("AdminProposed", "next", addr.String())
}
// AcceptAdmin completes a handover started with ProposeAdmin.
func AcceptAdmin(cur realm) {
who := callerOf(cur)
if pendingAdmin == "" || who != pendingAdmin {
panic("you are not the proposed admin")
}
admin = who
pendingAdmin = ""
chain.Emit("AdminChanged", "admin", who.String())
}
// IsPaused reports whether new activity is stopped.
func IsPaused() bool {
return paused
}
// Admin returns the current admin address, or "" when there is none.
func Admin() string {
return admin.String()
}
func assertAdmin(cur realm) {
who := callerOf(cur)
refuseCoins(cur)
if admin == "" || who != admin {
panic("admin only")
}
}
func assertNotPaused() {
if paused {
panic("trade rooms are paused: you can still withdraw, unlock and cancel")
}
}
fee.gno
package rooms
import (
"chain"
"math"
"strconv"
"gno.land/p/nt/avl/v0"
)
// The service fee. When a room settles, the realm keeps FeeBps basis points
// of every coin and token that crosses, from each side, and sends it to the
// treasury; the rest goes to the other party. NFTs cross whole and pay
// nothing. Withdrawing, cancelling and expiring cost nothing.
//
// A room keeps the rate it was opened with, so the admin can never raise
// the fee on a trade already under way, and no rate can exceed MaxFeeBps.
const (
// DefaultFeeBps is 0.5%.
DefaultFeeBps = 50
// MaxFeeBps caps the fee at 1%, whatever the admin sets.
MaxFeeBps = 100
)
var (
feeBps uint64 = DefaultFeeBps
treasury address // set to the deployer in init; fees are off while it is empty
fees avl.Tree // kind + ":" + denom -> int64 fees collected
)
// SetFee sets the rate for rooms opened from now on, in basis points
// (50 is 0.5%), at most MaxFeeBps. Rooms already open keep their rate.
func SetFee(cur realm, bps uint64) {
assertAdmin(cur)
if bps > MaxFeeBps {
panic("the fee can be at most " + strconv.Itoa(MaxFeeBps) + " basis points")
}
feeBps = bps
chain.Emit("FeeChanged", "bps", strconv.FormatUint(bps, 10))
}
// SetTreasury names the account that receives fees from now on.
func SetTreasury(cur realm, to string) {
assertAdmin(cur)
addr := address(to)
if !addr.IsValid() {
panic("treasury is not a valid address")
}
treasury = addr
chain.Emit("TreasuryChanged", "treasury", addr.String())
}
// FeeBps returns the rate a room opened now would get.
func FeeBps() uint64 {
return openingFee()
}
// Treasury returns the account that receives fees, or "" when fees are off.
func Treasury() string {
return treasury.String()
}
// openingFee is the rate a new room keeps for its whole life.
func openingFee() uint64 {
if treasury == "" {
return 0
}
return feeBps
}
// feeOf is the fee on amount at bps basis points, rounded down. It never
// overflows: bps is at most MaxFeeBps.
func feeOf(amount int64, bps uint64) int64 {
if bps == 0 || amount <= 0 {
return 0
}
b := int64(bps)
return amount/10000*b + amount%10000*b/10000
}
// pay sends one asset of a settling room to the party receiving it, less
// the room's fee on coins and tokens.
func (r *room) pay(cur realm, to address, a asset) {
fee := int64(0)
if a.kind != KindNFT {
fee = feeOf(a.amount, r.feeBps)
}
if fee > 0 {
send(cur, treasury, asset{kind: a.kind, denom: a.denom, amount: fee})
addFee(a.kind, a.denom, fee)
}
send(cur, to, asset{kind: a.kind, denom: a.denom, amount: a.amount - fee})
}
func addFee(kind, denom string, amount int64) {
key := kind + ":" + denom
total := int64(0)
if v := fees.Get(key); v != nil {
total = v.(int64)
}
if amount > math.MaxInt64-total {
total = math.MaxInt64
} else {
total += amount
}
fees.Set(key, total)
}
gnomod.toml
module = "gno.land/r/nym-tradewindow001/rooms" gno = "0.9" [addpkg] creator = "g1hsxx0r86afsrwxkf38kqq5zursfrgjmp35fcvy" height = 1427292 max_deposit = "10000000ugnot"
json.gno
package rooms
import (
"strconv"
"strings"
)
// jsonString quotes s as a JSON string. Everything outside printable ASCII
// is written as a \u escape, so the output is plain ASCII.
func jsonString(s string) string {
var b strings.Builder
b.WriteByte('"')
for _, r := range s {
switch {
case r == '"':
b.WriteString(`\"`)
case r == '\\':
b.WriteString(`\\`)
case r >= 0x20 && r < 0x7f:
b.WriteRune(r)
case r > 0xffff:
r -= 0x10000
writeU16(&b, 0xd800+(r>>10))
writeU16(&b, 0xdc00+(r&0x3ff))
default:
writeU16(&b, r)
}
}
b.WriteByte('"')
return b.String()
}
func writeU16(b *strings.Builder, r rune) {
const hex = "0123456789abcdef"
b.WriteString(`\u`)
b.WriteByte(hex[(r>>12)&0xf])
b.WriteByte(hex[(r>>8)&0xf])
b.WriteByte(hex[(r>>4)&0xf])
b.WriteByte(hex[r&0xf])
}
func jsonUint(v uint64) string {
return strconv.FormatUint(v, 10)
}
func jsonInt(v int64) string {
return strconv.FormatInt(v, 10)
}
func jsonBool(v bool) string {
if v {
return "true"
}
return "false"
}
// jsonObject joins already-encoded key/value pairs.
func jsonObject(pairs ...string) string {
if len(pairs)%2 != 0 {
panic("jsonObject needs key/value pairs")
}
var b strings.Builder
b.WriteByte('{')
for i := 0; i < len(pairs); i += 2 {
if i > 0 {
b.WriteByte(',')
}
b.WriteString(jsonString(pairs[i]))
b.WriteByte(':')
b.WriteString(pairs[i+1])
}
b.WriteByte('}')
return b.String()
}
func jsonArray(items []string) string {
return "[" + strings.Join(items, ",") + "]"
}
nft.gno
package rooms
import (
"chain"
"strconv"
"strings"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/grc721/enumerable/v0"
"gno.land/p/nt/grc721/v0"
)
// NFTs: one GRC721 token is one asset on a side, held whole. gno.land has no
// GRC721 registry yet, so rooms keeps its own, on the trust model of
// gno.land/r/nt/grc20reg/v0: a collection registers itself, from its own
// realm, under the key "<realm path>.<symbol>". An NFT asset's denom is that
// key, "#" and the token id; a key never holds "#".
// MaxTokenIDLen bounds what a room stores per NFT.
const MaxTokenIDLen = 64
type collection struct {
token *grc721.Token
// list is the collection's enumerable view, when it has one: it lets
// OwnedJSON show a wallet's NFTs of this collection.
list *enumerable.Enumerable
}
var collections avl.Tree // "<realm path>.<symbol>" -> *collection
// RegisterCollection makes a GRC721 collection tradable in rooms and returns
// its key. Only the collection's own realm can register it, once; list is
// its enumerable view, or nil. A collection's realm also lets owners
// approve this realm (see Address) for one token id, as its own Approve
// does; DepositNFT spends that approval.
//
// key := rooms.RegisterCollection(cross(cur), Token, List)
func RegisterCollection(cur realm, token *grc721.Token, list *enumerable.Enumerable) string {
if !cur.IsCurrent() {
panic("unauthorized: realm token is not current")
}
refuseCoins(cur)
if token == nil {
panic("collection is nil")
}
path := cur.Previous().PkgPath()
if !strings.HasPrefix(path, "gno.land/r/") || strings.Contains(path, "#") {
panic("register a collection from its own realm")
}
key := path + "." + token.GetSymbol()
// Token.ID() is "<creating realm path>.<symbol>.<id>" and cannot be
// forged: the token was created by the realm that registers it.
if !strings.HasPrefix(token.ID(), key+".") {
panic("register a collection from its own realm")
}
if list != nil && list.TokenID() != token.ID() {
panic("the list belongs to another collection")
}
if collections.Has(key) {
panic("collection already registered")
}
collections.Set(key, &collection{token: token, list: list})
chain.Emit("CollectionRegistered",
"key", key,
"name", token.GetName(),
"symbol", token.GetSymbol(),
)
return key
}
// DepositNFT moves one NFT of a registered collection from the caller to
// this realm and adds it to the caller's side. The caller must first
// approve this realm's address (see Address) for that token id, in the
// collection's realm.
func DepositNFT(cur realm, roomID uint64, collectionKey string, tokenID string) {
who := callerOf(cur)
refuseCoins(cur)
assertNotPaused()
col := mustCollection(collectionKey)
assertTokenID(tokenID)
r := mustRoom(roomID)
r.assertLive()
mine, _ := r.sideOf(who)
r.assertAccepts(KindNFT, collectionKey)
denom := collectionKey + "#" + tokenID
tid := grc721.TokenID(tokenID)
// Say plainly what is missing before anything changes.
if owner, err := col.token.OwnerOf(tid); err != nil || owner != who {
panic("you do not own that NFT")
}
if to, err := col.token.GetApproved(tid); (err != nil || to != cur.Address()) && !col.token.IsApprovedForAll(who, cur.Address()) {
panic("approve this realm for that NFT first")
}
// Record first, move second: a GRC721 transfer runs the issuer's
// extension hooks, and anything they call back into must already see
// the room as it will be. A failed transfer aborts the whole call.
mine.addNFT(denom)
r.bump()
// This realm is the spender: the owner's approval to it is what moves.
if err := col.token.RealmTeller(0, cur).TransferFrom(0, cur, who, cur.Address(), tid); err != nil {
panic(err.Error())
}
chain.Emit("Deposited",
"id", idString(r.id),
"party", who.String(),
"nft", collectionKey,
"tokenId", tokenID,
"version", idString(r.version),
)
}
// WithdrawNFT returns one NFT from the caller's side to the caller. Same
// rules as WithdrawCoins: it works while the room is open, also after it
// has expired or while the realm is paused.
func WithdrawNFT(cur realm, roomID uint64, collectionKey string, tokenID string) {
withdraw(cur, roomID, KindNFT, collectionKey+"#"+tokenID, 1)
}
// sendNFT pays one NFT out of this realm's custody.
func sendNFT(cur realm, to address, denom string) {
key, tid, ok := strings.Cut(denom, "#")
if !ok {
panic("unknown NFT")
}
col := mustCollection(key)
if err := col.token.RealmTeller(0, cur).TransferFrom(0, cur, cur.Address(), to, grc721.TokenID(tid)); err != nil {
panic(err.Error())
}
}
func (s *side) addNFT(denom string) {
for _, a := range s.assets {
if a.kind == KindNFT && a.denom == denom {
panic("that NFT is already in the room")
}
}
if len(s.assets) >= MaxAssetsPerSide {
panic("a side can hold at most 8 different assets")
}
s.assets = append(s.assets, asset{kind: KindNFT, denom: denom, amount: 1})
}
func mustCollection(key string) *collection {
v := collections.Get(key)
if v == nil {
panic("collection is not registered with rooms")
}
return v.(*collection)
}
func assertTokenID(tid string) {
if tid == "" || len(tid) > MaxTokenIDLen {
panic("token id must be 1 to " + strconv.Itoa(MaxTokenIDLen) + " bytes")
}
for _, r := range tid {
if r < 0x20 || r == 0x7f {
panic("token id has a control character")
}
}
}
offer.gno
package rooms
import (
"chain"
"chain/runtime/unsafe"
"strconv"
"strings"
"gno.land/p/nt/grc721/v0"
"gno.land/r/nt/grc20reg/v0"
)
// Offers: a room that completes in one transaction.
//
// The maker puts their side in as usual, then calls Offer with the exact
// list of what they want in return. That locks the maker's side on the new
// version. Whoever may take the other seat (the invited account, or anyone
// when the seat is open) calls Fill naming the version they reviewed and
// putting in exactly the wanted list: coins attached to the call, tokens
// and NFTs approved to this realm beforehand (the app sends the approvals
// and Fill in one transaction). Fill takes the seat, moves the wanted
// assets in and settles the room before it returns. Nothing partial: a
// wrong coin, a missing approval or a changed room fails the whole call.
//
// The maker can withdraw the offer at any time: Unlock, any deposit or
// withdrawal, or Cancel. Every change to the room clears it, and Fill names
// the version, so an offer can never be filled on terms the taker did not
// see. While an offer stands, Join is refused, so nobody can block an open
// offer by taking its seat without filling it.
// Offer turns the room into an offer for exactly want, on the room as it is
// at version. want lists one asset per line, at most 8:
//
// coin <amount> <denom>
// token <amount> <grc20reg key>
// nft 1 <collection key>#<token id>
//
// Amounts are in base units. Returns the new version, which the taker
// fills.
func Offer(cur realm, roomID uint64, version uint64, want string) uint64 {
who := callerOf(cur)
refuseCoins(cur)
assertNotPaused()
r := mustRoom(roomID)
r.assertLive()
if who != r.maker.owner {
panic("only the maker can make an offer")
}
if version != r.version {
panic("the room changed: review version " + idString(r.version) + " and offer again")
}
if len(r.maker.assets) == 0 {
panic("put something in before you make an offer")
}
if len(r.taker.assets) > 0 {
panic("they have already put something in: agree in the room instead")
}
items := parseWant(want)
for _, a := range items {
r.assertAccepts(a.kind, a.denom)
}
r.assertStillVerified()
r.bump()
r.want = items
r.maker.locked = r.version
chain.Emit("Offered",
"id", idString(r.id),
"version", idString(r.version),
"want", wantString(items),
)
return r.version
}
// Fill completes an offer: the caller takes the other seat, puts in exactly
// what the offer wants, and the room settles in this call. version is the
// version the caller reviewed. Coins in the offer must be attached to this
// call, from the caller's own account.
func Fill(cur realm, roomID uint64, version uint64) {
if !cur.IsCurrent() {
panic("unauthorized: realm token is not current")
}
prev := cur.Previous()
who := prev.Address()
assertNotPaused()
r := mustRoom(roomID)
r.assertLive()
if len(r.want) == 0 {
panic("this room has no standing offer")
}
if version != r.version {
panic("the offer changed: review version " + idString(r.version) + " and fill again")
}
if r.maker.locked != r.version {
panic("the offer is withdrawn")
}
if who == r.maker.owner {
panic("you made this offer")
}
if r.taker.owner != "" && r.taker.owner != who {
panic("this offer is for another account")
}
if r.taker.owner == "" && !r.openSeat {
panic("this offer is for another account")
}
if len(r.taker.assets) > 0 {
panic("this room is not an offer any more")
}
r.assertStillVerified()
// Coins can only arrive with a direct call from the signing account,
// and they must be exactly the wanted coins: no more, no less, no other.
var sent chain.Coins
if prev.IsUserCall() {
sent = unsafe.OriginSend()
}
wantCoins := chain.Coins{}
for _, a := range r.want {
if a.kind == KindCoin {
wantCoins = append(wantCoins, chain.Coin{Denom: a.denom, Amount: a.amount})
}
}
if len(wantCoins) > 0 && !prev.IsUserCall() {
panic("send the coins with a direct call from your account")
}
if !sameCoins(sent, wantCoins) {
if len(wantCoins) == 0 {
panic("this offer does not take coins")
}
panic("attach exactly " + wantCoins.String())
}
// Say plainly what is missing before anything changes.
for _, a := range r.want {
switch a.kind {
case KindToken:
tok := grc20reg.Get(a.denom)
if tok == nil {
panic("token is not in the GRC20 registry")
}
if tok.BalanceOf(who) < a.amount {
panic("you do not have enough " + tok.GetSymbol())
}
if tok.Allowance(who, cur.Address()) < a.amount {
panic("approve this realm for " + tok.GetSymbol() + " first")
}
case KindNFT:
key, tid, _ := strings.Cut(a.denom, "#")
col := mustCollection(key)
if owner, err := col.token.OwnerOf(grc721.TokenID(tid)); err != nil || owner != who {
panic("you do not own " + col.token.GetName() + " #" + tid)
}
if to, err := col.token.GetApproved(grc721.TokenID(tid)); (err != nil || to != cur.Address()) && !col.token.IsApprovedForAll(who, cur.Address()) {
panic("approve this realm for " + col.token.GetName() + " #" + tid + " first")
}
}
}
// Hold the room while the wanted assets move in: an NFT's transfer runs
// its issuer's code, and nothing that code calls may change this room.
r.status = statusFilling
for _, a := range r.want {
switch a.kind {
case KindToken:
grc20reg.TransferFrom(0, cur, a.denom, who, cur.Address(), a.amount)
case KindNFT:
key, tid, _ := strings.Cut(a.denom, "#")
col := mustCollection(key)
if err := col.token.RealmTeller(0, cur).TransferFrom(0, cur, who, cur.Address(), grc721.TokenID(tid)); err != nil {
panic(err.Error())
}
}
}
// Everything is in custody: record the taker's side and swap.
r.status = StatusOpen
if r.taker.owner == "" {
r.taker.owner = who
index(who, r.id)
}
r.taker.assets = append([]asset{}, r.want...)
r.taker.locked = r.version
r.want = nil
chain.Emit("Filled",
"id", idString(r.id),
"taker", who.String(),
"version", idString(r.version),
)
r.settle(cur, who)
}
// parseWant reads an offer's want list; see Offer.
func parseWant(want string) []asset {
items := []asset{}
for _, line := range strings.Split(want, "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
kind, rest, ok := strings.Cut(line, " ")
if !ok {
panic("each line of the want list is: kind amount denom")
}
amountText, denom, ok := strings.Cut(strings.TrimSpace(rest), " ")
denom = strings.TrimSpace(denom)
if !ok || denom == "" {
panic("each line of the want list is: kind amount denom")
}
amount, err := strconv.ParseInt(amountText, 10, 64)
if err != nil || amount <= 0 {
panic("want amounts must be positive whole numbers of base units")
}
switch kind {
case KindCoin:
assertDenom(denom)
case KindToken:
if grc20reg.Get(denom) == nil {
panic("token is not in the GRC20 registry: " + denom)
}
case KindNFT:
key, tid, ok := strings.Cut(denom, "#")
if !ok {
panic("an NFT is written as collection key#token id")
}
col := mustCollection(key)
assertTokenID(tid)
if _, err := col.token.OwnerOf(grc721.TokenID(tid)); err != nil {
panic("that NFT does not exist: " + denom)
}
if amount != 1 {
panic("an NFT is wanted whole: amount 1")
}
default:
panic("unknown kind in the want list: " + kind)
}
for _, a := range items {
if a.kind == kind && a.denom == denom {
panic("the want list names " + denom + " twice")
}
}
if len(items) >= MaxAssetsPerSide {
panic("an offer can want at most 8 different assets")
}
items = append(items, asset{kind: kind, denom: denom, amount: amount})
}
if len(items) == 0 {
panic("say what you want in return")
}
return items
}
// wantString writes a want list back in Offer's format.
func wantString(items []asset) string {
lines := make([]string, 0, len(items))
for _, a := range items {
lines = append(lines, a.kind+" "+strconv.FormatInt(a.amount, 10)+" "+a.denom)
}
return strings.Join(lines, "\n")
}
// assertDenom accepts bank denoms: 3 to 128 characters of lowercase
// letters, digits and / : . _ -, starting with a letter.
func assertDenom(d string) {
if len(d) < 3 || len(d) > 128 {
panic("not a coin denom: " + d)
}
for i, c := range d {
ok := c >= 'a' && c <= 'z' || i > 0 && (c >= '0' && c <= '9' || c == '/' || c == ':' || c == '.' || c == '_' || c == '-')
if !ok {
panic("not a coin denom: " + d)
}
}
}
// sameCoins reports whether a and b hold the same amount of every denom.
func sameCoins(a, b chain.Coins) bool {
total := func(cs chain.Coins) map[string]int64 {
m := map[string]int64{}
for _, c := range cs {
if c.Amount != 0 {
m[c.Denom] += c.Amount
}
}
return m
}
ma, mb := total(a), total(b)
if len(ma) != len(mb) {
return false
}
for d, n := range ma {
if mb[d] != n {
return false
}
}
return true
}
query.gno
package rooms
import (
"strings"
"time"
"gno.land/p/nt/grc20/v0"
"gno.land/p/nt/grc721/v0"
"gno.land/r/nt/grc20reg/v0"
)
// Read-only views for clients. Each returns a JSON document as a string so
// a frontend can read it with one vm/qeval query. Amounts are strings
// because int64 does not fit a JavaScript number. Times are unix seconds;
// "now" is the block time the answer was computed at.
const maxPage = 50
// Address returns this realm's address: the spender to approve before
// DepositToken, and the account that holds deposits.
func Address() string {
return self.String()
}
// RoomJSON returns one room, or null when it does not exist.
func RoomJSON(id uint64) string {
v := rooms.Get(roomKey(id))
if v == nil {
return "null"
}
return v.(*room).json(time.Now().Unix())
}
// RoomsOfJSON lists the rooms where addr is maker or taker, newest first.
func RoomsOfJSON(addr string, offset, limit int) string {
offset, limit = page(offset, limit)
now := time.Now().Unix()
items := []string{}
var ids []uint64
if v := byParty.Get(strings.TrimSpace(addr)); v != nil {
ids = v.([]uint64)
}
more := false
for i := len(ids) - 1 - offset; i >= 0; i-- {
if len(items) == limit {
more = true
break
}
items = append(items, mustRoom(ids[i]).json(now))
}
return jsonObject(
"rooms", jsonArray(items),
"more", jsonBool(more),
"now", jsonInt(now),
)
}
// LatestJSON lists all rooms, newest first.
func LatestJSON(offset, limit int) string {
offset, limit = page(offset, limit)
now := time.Now().Unix()
items := []string{}
rooms.ReverseIterateByOffset(offset, limit, func(_ string, v any) bool {
items = append(items, v.(*room).json(now))
return false
})
return jsonObject(
"rooms", jsonArray(items),
"total", jsonUint(lastID),
"now", jsonInt(now),
)
}
// StatsJSON returns counters and the settled volume per asset.
func StatsJSON() string {
vol := []string{}
volume.Iterate("", "", func(key string, v any) bool {
kind, denom, _ := strings.Cut(key, ":")
vol = append(vol, jsonObject(
"kind", jsonString(kind),
"denom", jsonString(denom),
"amount", jsonString(jsonInt(v.(int64))),
))
return false
})
collected := []string{}
fees.Iterate("", "", func(key string, v any) bool {
kind, denom, _ := strings.Cut(key, ":")
collected = append(collected, jsonObject(
"kind", jsonString(kind),
"denom", jsonString(denom),
"amount", jsonString(jsonInt(v.(int64))),
))
return false
})
return jsonObject(
"rooms", jsonUint(lastID),
"settled", jsonUint(nSettled),
"cancelled", jsonUint(nCancelled),
"volume", jsonArray(vol),
"fees", jsonArray(collected),
"feeBps", jsonUint(openingFee()),
"treasury", jsonString(treasury.String()),
"paused", jsonBool(paused),
"address", jsonString(self.String()),
"now", jsonInt(time.Now().Unix()),
)
}
// TokensJSON lists GRC20 tokens from the registry that rooms accept.
func TokensJSON(offset, limit int) string {
offset, limit = page(offset, limit)
items := []string{}
grc20reg.GetRegistry().IterateByOffset(offset, limit, func(key string, v any) bool {
items = append(items, tokenJSON(key, v.(*grc20.Token)))
return false
})
return jsonObject("tokens", jsonArray(items))
}
// TokenJSON describes one registered token and, when owner is given, the
// owner's balance and current allowance to this realm.
func TokenJSON(key string, owner string) string {
tok := grc20reg.Get(key)
if tok == nil {
return "null"
}
if owner == "" {
return tokenJSON(key, tok)
}
who := address(owner)
if !who.IsValid() {
return "null"
}
return jsonObject(
"key", jsonString(key),
"name", jsonString(tok.GetName()),
"symbol", jsonString(tok.GetSymbol()),
"decimals", jsonInt(int64(tok.GetDecimals())),
"balance", jsonString(jsonInt(tok.BalanceOf(who))),
"allowance", jsonString(jsonInt(tok.Allowance(who, self))),
)
}
// BalancesJSON lists the registered GRC20 tokens that owner holds, with the
// balance and the allowance to this realm: a wallet's inventory in one
// query. A page covers limit registry entries (at most 50); read on while
// "more" is true.
func BalancesJSON(owner string, offset, limit int) string {
offset, limit = page(offset, limit)
who := address(strings.TrimSpace(owner))
if !who.IsValid() {
return "null"
}
reg := grc20reg.GetRegistry()
items := []string{}
seen := 0
reg.IterateByOffset(offset, limit, func(key string, v any) bool {
seen++
tok := v.(*grc20.Token)
if bal := tok.BalanceOf(who); bal > 0 {
items = append(items, jsonObject(
"key", jsonString(key),
"name", jsonString(tok.GetName()),
"symbol", jsonString(tok.GetSymbol()),
"decimals", jsonInt(int64(tok.GetDecimals())),
"balance", jsonString(jsonInt(bal)),
"allowance", jsonString(jsonInt(tok.Allowance(who, self))),
))
}
return false
})
return jsonObject(
"tokens", jsonArray(items),
"more", jsonBool(offset+seen < reg.Size()),
)
}
// CollectionsJSON lists the GRC721 collections registered with rooms.
func CollectionsJSON(offset, limit int) string {
offset, limit = page(offset, limit)
items := []string{}
collections.IterateByOffset(offset, limit, func(key string, v any) bool {
col := v.(*collection)
items = append(items, jsonObject(
"key", jsonString(key),
"name", jsonString(col.token.GetName()),
"symbol", jsonString(col.token.GetSymbol()),
"listed", jsonBool(col.list != nil),
"verified", jsonBool(IsVerified(KindNFT, key)),
))
return false
})
return jsonObject(
"collections", jsonArray(items),
"more", jsonBool(offset+len(items) < collections.Size()),
)
}
// NFTJSON describes one NFT of a registered collection: who owns it, and
// whether this realm is approved to move it. null when the collection is
// not registered or the token does not exist.
func NFTJSON(collectionKey string, tokenID string) string {
v := collections.Get(collectionKey)
if v == nil {
return "null"
}
col := v.(*collection)
tid := grc721.TokenID(tokenID)
owner, err := col.token.OwnerOf(tid)
if err != nil {
return "null"
}
approved := col.token.IsApprovedForAll(owner, self)
if to, err := col.token.GetApproved(tid); err == nil && to == self {
approved = true
}
return jsonObject(
"key", jsonString(collectionKey),
"name", jsonString(col.token.GetName()),
"symbol", jsonString(col.token.GetSymbol()),
"tokenId", jsonString(tokenID),
"owner", jsonString(owner.String()),
"approved", jsonBool(approved),
)
}
// maxOwnedPerCollection bounds one OwnedJSON page.
const maxOwnedPerCollection = 20
// OwnedJSON lists the NFTs owner holds in registered collections that can
// be listed (those registered with their enumerable view), at most 20 per
// collection, and whether this realm is approved for each. A page covers
// limit collections; read on while "more" is true.
func OwnedJSON(owner string, offset, limit int) string {
offset, limit = page(offset, limit)
who := address(strings.TrimSpace(owner))
if !who.IsValid() {
return "null"
}
items := []string{}
seen := 0
collections.IterateByOffset(offset, limit, func(key string, v any) bool {
seen++
col := v.(*collection)
if col.list == nil {
return false
}
n, err := col.token.BalanceOf(who)
if err != nil || n <= 0 {
return false
}
if n > maxOwnedPerCollection {
n = maxOwnedPerCollection
}
operator := col.token.IsApprovedForAll(who, self)
for i := int64(0); i < n; i++ {
tid, err := col.list.TokenOfOwnerByIndex(who, i)
if err != nil {
break
}
approved := operator
if !approved {
if to, err := col.token.GetApproved(tid); err == nil && to == self {
approved = true
}
}
items = append(items, jsonObject(
"key", jsonString(key),
"name", jsonString(col.token.GetName()),
"symbol", jsonString(col.token.GetSymbol()),
"tokenId", jsonString(string(tid)),
"approved", jsonBool(approved),
))
}
return false
})
return jsonObject(
"nfts", jsonArray(items),
"more", jsonBool(offset+seen < collections.Size()),
)
}
func tokenJSON(key string, tok *grc20.Token) string {
return jsonObject(
"key", jsonString(key),
"name", jsonString(tok.GetName()),
"symbol", jsonString(tok.GetSymbol()),
"decimals", jsonInt(int64(tok.GetDecimals())),
"verified", jsonBool(IsVerified(KindToken, key)),
)
}
// json describes the room at block time now (unix seconds).
func (r *room) json(now int64) string {
return jsonObject(
"id", jsonUint(r.id),
"status", jsonString(r.status),
"expired", jsonBool(r.status == StatusOpen && now >= r.expiresAt),
"version", jsonUint(r.version),
"openSeat", jsonBool(r.openSeat),
"openMarket", jsonBool(r.openMarket),
"createdAt", jsonInt(r.createdAt),
"expiresAt", jsonInt(r.expiresAt),
"closedAt", jsonInt(r.closedAt),
"closedBy", jsonString(r.closedBy.String()),
"maker", r.maker.json(),
"taker", r.taker.json(),
"want", assetsJSON(r.want),
"feeBps", jsonUint(r.feeBps),
"now", jsonInt(now),
)
}
func assetsJSON(list []asset) string {
items := make([]string, 0, len(list))
for _, a := range list {
items = append(items, jsonObject(
"kind", jsonString(a.kind),
"denom", jsonString(a.denom),
"amount", jsonString(jsonInt(a.amount)),
))
}
return jsonArray(items)
}
func (s *side) json() string {
return jsonObject(
"address", jsonString(s.owner.String()),
"locked", jsonUint(s.locked),
"assets", assetsJSON(s.assets),
)
}
func page(offset, limit int) (int, int) {
if offset < 0 {
offset = 0
}
if limit <= 0 || limit > maxPage {
limit = maxPage
}
return offset, limit
}
render.gno
package rooms
import (
"strconv"
"strings"
"time"
"gno.land/p/nt/markdown/sanitize/v0"
"gno.land/r/nt/grc20reg/v0"
)
// Render shows the realm on gnoweb: the home page lists recent rooms, and
// room/<id> shows one room. Every value that comes from a caller goes
// through sanitize before it reaches the markdown.
func Render(path string) string {
path = strings.TrimSpace(path)
if path == "" {
return renderHome()
}
if rest, ok := strings.CutPrefix(path, "room/"); ok {
id, err := strconv.ParseUint(rest, 10, 64)
if err == nil {
if v := rooms.Get(roomKey(id)); v != nil {
return renderRoom(v.(*room), time.Now().Unix())
}
}
}
return "# Not found\n\nNo room at this address.\n"
}
func renderHome() string {
now := time.Now().Unix()
var b strings.Builder
b.WriteString("# Trade Window rooms\n\n")
b.WriteString("Two parties put assets into a room. Each change raises the room's version. ")
b.WriteString("Both lock the same version, and the second lock swaps everything in one transaction. ")
b.WriteString("Until then either side can withdraw or cancel. ")
b.WriteString("A room can also be an offer: the maker's side and an exact list of what they want, filled by the first allowed account in one transaction.\n\n")
if fee := openingFee(); fee > 0 {
b.WriteString("Service fee on settlement: " + decimal(int64(fee), 2) + "% of every coin and token that crosses, from each side. NFTs, withdrawals and cancellations pay nothing.\n\n")
}
b.WriteString("Rooms opened: " + jsonUint(lastID) +
", settled: " + jsonUint(nSettled) +
", cancelled: " + jsonUint(nCancelled) + ".\n\n")
if paused {
b.WriteString("New activity is paused. Withdraw, unlock and cancel still work.\n\n")
}
if lastID == 0 {
b.WriteString("No rooms yet.\n")
return b.String()
}
b.WriteString("## Latest\n\n")
rooms.ReverseIterateByOffset(0, 20, func(_ string, v any) bool {
r := v.(*room)
b.WriteString("- [Room " + jsonUint(r.id) + "](:room/" + jsonUint(r.id) + "): " +
r.statusLabel(now) + ", " + sideSummary(&r.maker) + " for " + sideSummary(&r.taker) + "\n")
return false
})
return b.String()
}
func renderRoom(r *room, now int64) string {
var b strings.Builder
b.WriteString("# Room " + jsonUint(r.id) + "\n\n")
b.WriteString("Status: " + r.statusLabel(now) + ", version " + jsonUint(r.version) + ".\n\n")
b.WriteString("Opened " + stamp(r.createdAt))
if r.status == StatusOpen {
b.WriteString(". Can settle until " + stamp(r.expiresAt))
} else if r.closedAt != 0 {
b.WriteString(". Closed " + stamp(r.closedAt))
}
b.WriteString(".")
if r.openMarket {
b.WriteString(" Open market: this room takes any registered asset, verified or not.")
} else {
b.WriteString(" Verified assets only.")
}
if r.feeBps > 0 {
b.WriteString(" Fee on settlement: " + decimal(int64(r.feeBps), 2) + "% of coins and tokens, from each side.")
}
b.WriteString("\n\n")
b.WriteString(renderSide("Maker", &r.maker, r.version))
if len(r.want) > 0 {
b.WriteString("## Offer\n\nThe maker wants exactly this in return; the first allowed account that puts it in completes the trade:\n\n")
for _, a := range r.want {
b.WriteString("- " + sanitize.InlineText(formatAsset(a)) + ", " + sanitize.InlineCode(a.denom) + "\n")
}
b.WriteString("\n")
}
if r.taker.owner == "" && len(r.want) > 0 {
b.WriteString("## Taker\n\nThe seat is open: any account can fill the offer.\n\n")
} else if r.taker.owner == "" {
b.WriteString("## Taker\n\nThe seat is open: any account can join.\n\n")
} else {
b.WriteString(renderSide("Taker", &r.taker, r.version))
}
return b.String()
}
func renderSide(title string, s *side, version uint64) string {
var b strings.Builder
b.WriteString("## " + title + "\n\n")
b.WriteString(sanitize.InlineCode(s.owner.String()))
if s.locked != 0 && s.locked == version {
b.WriteString(", locked this version")
}
b.WriteString("\n\n")
if len(s.assets) == 0 {
b.WriteString("Nothing deposited.\n\n")
return b.String()
}
for _, a := range s.assets {
b.WriteString("- " + sanitize.InlineText(formatAsset(a)) + ", " + sanitize.InlineCode(a.denom) + "\n")
}
b.WriteString("\n")
return b.String()
}
func sideSummary(s *side) string {
if len(s.assets) == 0 {
return "nothing"
}
parts := make([]string, 0, len(s.assets))
for _, a := range s.assets {
parts = append(parts, sanitize.InlineText(formatAsset(a)))
}
return strings.Join(parts, " and ")
}
// wugnotKey is wrapped GNOT in the GRC20 registry. Its token declares 0
// decimals because one unit is one ugnot, so it is shown in GNOT like the
// coin, marked as wrapped so the two are never confused.
const wugnotKey = "gno.land/r/gnoland/wugnot.wugnot"
// formatAsset writes an amount in whole units: GNOT for ugnot and wrapped
// GNOT, the registry's symbol and decimals for other tokens, the raw denom
// otherwise.
func formatAsset(a asset) string {
switch {
case a.kind == KindCoin && a.denom == "ugnot":
return decimal(a.amount, 6) + " GNOT"
case a.kind == KindToken && a.denom == wugnotKey:
return decimal(a.amount, 6) + " GNOT (wrapped)"
case a.kind == KindToken:
if tok := grc20reg.Get(a.denom); tok != nil {
return decimal(a.amount, tok.GetDecimals()) + " " + tok.GetSymbol()
}
case a.kind == KindNFT:
key, tid, _ := strings.Cut(a.denom, "#")
if v := collections.Get(key); v != nil {
return "NFT " + v.(*collection).token.GetName() + " #" + tid
}
return "NFT #" + tid
}
return strconv.FormatInt(a.amount, 10) + " " + a.denom
}
// decimal formats amount with the given number of decimals and no
// trailing zeros.
func decimal(amount int64, decimals int) string {
s := strconv.FormatInt(amount, 10)
if decimals <= 0 {
return s
}
if len(s) <= decimals {
s = strings.Repeat("0", decimals-len(s)+1) + s
}
whole, frac := s[:len(s)-decimals], strings.TrimRight(s[len(s)-decimals:], "0")
if frac == "" {
return whole
}
return whole + "." + frac
}
func (r *room) statusLabel(now int64) string {
if r.status == StatusOpen && now >= r.expiresAt {
return "expired"
}
return r.status
}
// stamp writes unix seconds as an RFC 3339 time in UTC.
func stamp(unix int64) string {
return time.Unix(unix, 0).UTC().Format(time.RFC3339)
}
rooms.gno
// Package rooms is the on-chain trade window.
//
// Two parties share a room. Each one puts assets on their own side: native
// coins (GNOT and any other bank denom), GRC20 tokens from the registry at
// gno.land/r/nt/grc20reg/v0, and GRC721 NFTs from collections registered
// with this realm (see RegisterCollection). The realm holds the deposits.
//
// Every change to the room raises its version. A party locks the room by
// naming the exact version they reviewed, so a lock can never apply to
// contents the party has not seen. When both sides hold a lock on the
// current version, the second lock swaps everything in the same
// transaction: the maker's side goes to the taker and the taker's side
// goes to the maker.
//
// Until that moment each party can withdraw their own deposits, and either
// party can cancel the room, which returns every deposit to its owner. An
// expired room can no longer settle; its deposits stay withdrawable, and
// anyone may cancel it to send them home.
//
// A maker can also turn a room into an offer (see Offer): their side plus an
// exact list of what they want in return. The first account allowed to take
// the other seat that puts in exactly that list completes the trade in one
// transaction (see Fill).
//
// On settlement the realm keeps a service fee on coins and tokens (see
// fee.gno); NFTs, withdrawals and cancellations pay nothing.
package rooms
import (
"chain"
"chain/banker"
"chain/runtime/unsafe"
"math"
"strconv"
"strings"
"time"
"gno.land/p/nt/avl/v0"
"gno.land/r/nt/grc20reg/v0"
)
const (
StatusOpen = "open"
StatusSettled = "settled"
StatusCancelled = "cancelled"
// statusFilling holds a room for the length of one Fill, so nothing an
// asset's own code runs during the transfers can change it.
statusFilling = "filling"
KindCoin = "coin"
KindToken = "token"
KindNFT = "nft"
// MaxAssetsPerSide bounds the work a settlement or refund can do.
MaxAssetsPerSide = 8
DefaultTTLMinutes = 24 * 60
MinTTLMinutes = 10
MaxTTLMinutes = 7 * 24 * 60
)
type asset struct {
kind string // KindCoin, KindToken or KindNFT
denom string // bank denom, grc20reg key, or collection key + "#" + token id
amount int64 // always 1 for an NFT
}
type side struct {
owner address
assets []asset
locked uint64 // version this side locked; 0 when not locked
}
// A room keeps both sides inline and its times as unix seconds: every
// separate object costs storage deposit, and a room is opened often.
type room struct {
id uint64
maker side
taker side
openSeat bool // anyone may take the taker seat with Join
// openMarket rooms take any registered asset; ordinary rooms take only
// verified ones (see verified.gno).
openMarket bool
status string
version uint64
// want is the maker's standing offer: exactly what the taker must put
// in for Fill to complete the trade. Any change to the room clears it.
want []asset
feeBps uint64 // the fee rate this room was opened with
createdAt int64 // unix seconds of block time
expiresAt int64
closedAt int64 // 0 while open
closedBy address
}
var (
rooms avl.Tree // padded id -> *room
byParty avl.Tree // address -> []uint64 room ids, oldest first
volume avl.Tree // kind + ":" + denom -> int64 settled amount; NFTs count per collection
lastID uint64
nSettled uint64
nCancelled uint64
self address
)
func init(cur realm) {
if !cur.IsCurrent() {
panic("unauthorized: realm token is not current")
}
self = cur.Address()
seedVerified()
prev := cur.Previous()
if prev.IsUserCall() && prev.Address().IsValid() {
admin = prev.Address()
treasury = admin
}
}
// Open creates a room with the caller as maker and returns its id. The room
// takes only verified assets (see Verify). counterparty is the taker's
// address, or "" to leave the seat open for the first account that calls
// Join. ttlMinutes is how long the room can settle; 0 means 24 hours, and
// the allowed range is 10 minutes to 7 days.
func Open(cur realm, counterparty string, ttlMinutes int) uint64 {
return open(cur, counterparty, ttlMinutes, false)
}
// OpenMarket is Open for a room that takes any registered asset, verified
// or not. Both parties trade unverified assets at their own risk; the app
// says so in every view of such a room.
func OpenMarket(cur realm, counterparty string, ttlMinutes int) uint64 {
return open(cur, counterparty, ttlMinutes, true)
}
func open(cur realm, counterparty string, ttlMinutes int, openMarket bool) uint64 {
maker := callerOf(cur)
refuseCoins(cur)
assertNotPaused()
ttl := ttlMinutes
if ttl == 0 {
ttl = DefaultTTLMinutes
}
if ttl < MinTTLMinutes || ttl > MaxTTLMinutes {
panic("room lifetime must be between 10 minutes and 7 days")
}
r := &room{
maker: side{owner: maker},
status: StatusOpen,
feeBps: openingFee(),
openMarket: openMarket,
}
counterparty = strings.TrimSpace(counterparty)
if counterparty == "" {
r.openSeat = true
} else {
cp := address(counterparty)
if !cp.IsValid() {
panic("counterparty is not a valid address")
}
if cp == maker {
panic("you cannot open a room with yourself")
}
r.taker.owner = cp
}
lastID++
r.id = lastID
r.version = 1
now := time.Now().Unix()
r.createdAt = now
r.expiresAt = now + int64(ttl)*60
rooms.Set(roomKey(r.id), r)
index(maker, r.id)
if r.taker.owner != "" {
index(r.taker.owner, r.id)
}
chain.Emit("RoomOpened",
"id", idString(r.id),
"maker", maker.String(),
"taker", r.taker.owner.String(),
"expires", strconv.FormatInt(r.expiresAt, 10),
"openMarket", strconv.FormatBool(openMarket),
)
return r.id
}
// Join takes the open taker seat of a room.
func Join(cur realm, roomID uint64) {
who := callerOf(cur)
refuseCoins(cur)
assertNotPaused()
r := mustRoom(roomID)
r.assertLive()
if !r.openSeat {
panic("this room is invite only")
}
if r.taker.owner != "" {
panic("the seat is already taken")
}
if who == r.maker.owner {
panic("you opened this room")
}
if len(r.want) > 0 {
panic("this room is an offer: fill it instead")
}
r.taker.owner = who
index(who, r.id)
r.bump()
chain.Emit("RoomJoined", "id", idString(r.id), "taker", who.String())
}
// DepositCoins adds the coins sent with this call to the caller's side.
// It must be called directly from the depositing account (maketx call or a
// wallet MsgCall), because only then are the sent coins guaranteed to have
// reached this realm.
func DepositCoins(cur realm, roomID uint64) {
if !cur.IsCurrent() {
panic("unauthorized: realm token is not current")
}
prev := cur.Previous()
// IsUserCall and OriginSend are a pair: OriginSend describes coins that
// actually arrived here only when the caller is the signing account.
// A code realm or a maketx run script could spend the envelope first.
if !prev.IsUserCall() {
panic("send coins with a direct call from your account")
}
who := prev.Address()
sent := unsafe.OriginSend()
if len(sent) == 0 {
panic("attach the coins to this call")
}
assertNotPaused()
r := mustRoom(roomID)
r.assertLive()
mine, _ := r.sideOf(who)
for _, c := range sent {
if c.Amount <= 0 {
panic("coin amounts must be positive")
}
r.assertAccepts(KindCoin, c.Denom)
mine.add(KindCoin, c.Denom, c.Amount)
}
r.bump()
chain.Emit("Deposited",
"id", idString(r.id),
"party", who.String(),
"coins", sent.String(),
"version", idString(r.version),
)
}
// DepositToken moves amount of a registered GRC20 token from the caller to
// this realm and adds it to the caller's side. The caller must first
// approve this realm's address (see Address) for at least amount.
func DepositToken(cur realm, roomID uint64, tokenKey string, amount int64) {
who := callerOf(cur)
refuseCoins(cur)
assertNotPaused()
if amount <= 0 {
panic("amount must be positive")
}
if grc20reg.Get(tokenKey) == nil {
panic("token is not in the GRC20 registry")
}
r := mustRoom(roomID)
r.assertLive()
mine, _ := r.sideOf(who)
r.assertAccepts(KindToken, tokenKey)
mine.assertRoomFor(KindToken, tokenKey, amount)
// This realm is the spender: the owner's allowance to it is what moves.
// The canonical GRC20 ledger runs no code of the token's author, so
// nothing can call back into this realm before the deposit is recorded.
grc20reg.TransferFrom(0, cur, tokenKey, who, cur.Address(), amount)
mine.add(KindToken, tokenKey, amount)
r.bump()
chain.Emit("Deposited",
"id", idString(r.id),
"party", who.String(),
"token", tokenKey,
"amount", strconv.FormatInt(amount, 10),
"version", idString(r.version),
)
}
// WithdrawCoins returns amount of denom from the caller's side to the
// caller. It works while the room is open, also after it has expired or
// while the realm is paused.
func WithdrawCoins(cur realm, roomID uint64, denom string, amount int64) {
withdraw(cur, roomID, KindCoin, denom, amount)
}
// WithdrawToken returns amount of a GRC20 token from the caller's side to
// the caller. Same rules as WithdrawCoins.
func WithdrawToken(cur realm, roomID uint64, tokenKey string, amount int64) {
withdraw(cur, roomID, KindToken, tokenKey, amount)
}
func withdraw(cur realm, roomID uint64, kind, denom string, amount int64) {
who := callerOf(cur)
refuseCoins(cur)
if amount <= 0 {
panic("amount must be positive")
}
r := mustRoom(roomID)
r.assertOpen()
mine, _ := r.sideOf(who)
mine.sub(kind, denom, amount)
r.bump()
send(cur, who, asset{kind: kind, denom: denom, amount: amount})
chain.Emit("Withdrawn",
"id", idString(r.id),
"party", who.String(),
"kind", kind,
"denom", denom,
"amount", strconv.FormatInt(amount, 10),
"version", idString(r.version),
)
}
// Lock records that the caller agrees to swap the room exactly as it is at
// version. It fails if the room has changed since. When the other side
// already holds a lock on the same version, this call settles the room and
// returns "settled"; otherwise it returns "locked".
func Lock(cur realm, roomID uint64, version uint64) string {
who := callerOf(cur)
refuseCoins(cur)
assertNotPaused()
r := mustRoom(roomID)
r.assertLive()
mine, theirs := r.sideOf(who)
if r.taker.owner == "" {
panic("waiting for a counterparty to join")
}
if version != r.version {
panic("the room changed: review version " + idString(r.version) + " and lock again")
}
if len(r.maker.assets) == 0 || len(r.taker.assets) == 0 {
panic("both sides need at least one asset")
}
r.assertStillVerified()
if mine.locked == version {
return "locked"
}
mine.locked = version
chain.Emit("Locked",
"id", idString(r.id),
"party", who.String(),
"version", idString(version),
)
if theirs.locked == version {
r.settle(cur, who)
return StatusSettled
}
return "locked"
}
// Unlock withdraws the caller's lock on the current version.
func Unlock(cur realm, roomID uint64) {
who := callerOf(cur)
refuseCoins(cur)
r := mustRoom(roomID)
r.assertOpen()
mine, _ := r.sideOf(who)
if mine.locked != r.version {
panic("you have not locked this version")
}
mine.locked = 0
if who == r.maker.owner {
r.want = nil // the maker's lock is what an offer stands on
}
chain.Emit("Unlocked", "id", idString(r.id), "party", who.String())
}
// Cancel closes an open room and returns every deposit to its owner.
// Either party may cancel at any time before settlement; once the room has
// expired, anyone may cancel it.
func Cancel(cur realm, roomID uint64) {
who := callerOf(cur)
refuseCoins(cur)
r := mustRoom(roomID)
r.assertOpen()
if !r.isParty(who) && !r.expired() {
panic("only the two parties can cancel a room before it expires")
}
r.status = StatusCancelled
r.closedAt = time.Now().Unix()
r.closedBy = who
nCancelled++
for _, a := range r.maker.assets {
send(cur, r.maker.owner, a)
}
if r.taker.owner != "" {
for _, a := range r.taker.assets {
send(cur, r.taker.owner, a)
}
}
chain.Emit("Cancelled", "id", idString(r.id), "by", who.String())
}
func (r *room) settle(cur realm, by address) {
r.status = StatusSettled
r.closedAt = time.Now().Unix()
r.closedBy = by
nSettled++
for _, a := range r.maker.assets {
r.pay(cur, r.taker.owner, a)
addVolume(a)
}
for _, a := range r.taker.assets {
r.pay(cur, r.maker.owner, a)
addVolume(a)
}
chain.Emit("Settled",
"id", idString(r.id),
"maker", r.maker.owner.String(),
"taker", r.taker.owner.String(),
"version", idString(r.version),
"feeBps", strconv.FormatUint(r.feeBps, 10),
)
}
// send pays one asset out of this realm's custody.
func send(cur realm, to address, a asset) {
switch a.kind {
case KindCoin:
bnk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
bnk.SendCoins(cur.Address(), to, chain.Coins{{Denom: a.denom, Amount: a.amount}})
case KindToken:
grc20reg.Transfer(0, cur, a.denom, to, a.amount)
case KindNFT:
sendNFT(cur, to, a.denom)
default:
panic("unknown asset kind")
}
}
// assertRoomFor panics if adding amount of an asset would break a limit.
func (s *side) assertRoomFor(kind, denom string, amount int64) {
for _, a := range s.assets {
if a.kind == kind && a.denom == denom {
if amount > math.MaxInt64-a.amount {
panic("amount is too large")
}
return
}
}
if len(s.assets) >= MaxAssetsPerSide {
panic("a side can hold at most 8 different assets")
}
}
func (s *side) add(kind, denom string, amount int64) {
s.assertRoomFor(kind, denom, amount)
for i := range s.assets {
if s.assets[i].kind == kind && s.assets[i].denom == denom {
s.assets[i].amount += amount
return
}
}
s.assets = append(s.assets, asset{kind: kind, denom: denom, amount: amount})
}
func (s *side) sub(kind, denom string, amount int64) {
for i := range s.assets {
if s.assets[i].kind != kind || s.assets[i].denom != denom {
continue
}
if amount > s.assets[i].amount {
panic("you have less than that in the room")
}
s.assets[i].amount -= amount
if s.assets[i].amount == 0 {
s.assets = append(s.assets[:i], s.assets[i+1:]...)
}
return
}
panic("you have not deposited that asset")
}
// sideOf returns the caller's side and the other side, or panics for
// anyone who is not one of the two parties.
func (r *room) sideOf(who address) (*side, *side) {
if who == r.maker.owner {
return &r.maker, &r.taker
}
if r.taker.owner != "" && who == r.taker.owner {
return &r.taker, &r.maker
}
panic("only the two parties of this room can do that")
}
func (r *room) isParty(who address) bool {
return who == r.maker.owner || (r.taker.owner != "" && who == r.taker.owner)
}
func (r *room) expired() bool {
return time.Now().Unix() >= r.expiresAt
}
func (r *room) assertOpen() {
if r.status != StatusOpen {
panic("this room is " + r.status)
}
}
// bump records a change to the room: the version moves on, so every lock on
// an earlier version stops applying, and a standing offer is withdrawn.
func (r *room) bump() {
r.version++
r.want = nil
}
// assertLive is assertOpen plus a check that the room can still settle.
func (r *room) assertLive() {
r.assertOpen()
if r.expired() {
panic("this room has expired: withdraw or cancel to get deposits back")
}
}
// refuseCoins stops a direct call that carries coins to any function other
// than DepositCoins. Such coins would reach this realm with nothing
// recording them; failing the call sends them back.
func refuseCoins(cur realm) {
if !cur.IsCurrent() {
panic("unauthorized: realm token is not current")
}
if cur.Previous().IsUserCall() && len(unsafe.OriginSend()) > 0 {
panic("this call does not take coins: use DepositCoins")
}
}
// callerOf names the immediate caller: the realm or account that was
// current when cur was minted for this crossing call. A crossing
// function's own cur is always current, so the IsCurrent check is belt and
// braces; it keeps every identity read in the shape reviewers and the gno
// audit harness look for.
func callerOf(cur realm) address {
if !cur.IsCurrent() {
panic("unauthorized: realm token is not current")
}
return cur.Previous().Address()
}
func mustRoom(id uint64) *room {
v := rooms.Get(roomKey(id))
if v == nil {
panic("room not found")
}
return v.(*room)
}
// index records that who is a party of room id. One growing list per
// account keeps a returning trader's next room cheap to store.
func index(who address, id uint64) {
key := who.String()
var ids []uint64
if v := byParty.Get(key); v != nil {
ids = v.([]uint64)
}
byParty.Set(key, append(ids, id))
}
func addVolume(a asset) {
key := a.kind + ":" + a.denom
if a.kind == KindNFT {
// One entry per collection, not per token: the tree stays small.
collection, _, _ := strings.Cut(a.denom, "#")
key = a.kind + ":" + collection
}
total := int64(0)
if v := volume.Get(key); v != nil {
total = v.(int64)
}
// Volume is informational; saturate instead of failing a settlement.
if a.amount > math.MaxInt64-total {
total = math.MaxInt64
} else {
total += a.amount
}
volume.Set(key, total)
}
// roomKey zero-pads ids so the tree iterates in numeric order.
func roomKey(id uint64) string {
s := strconv.FormatUint(id, 10)
if len(s) < 20 {
s = strings.Repeat("0", 20-len(s)) + s
}
return s
}
func idString(id uint64) string {
return strconv.FormatUint(id, 10)
}
verified.gno
package rooms
import (
"chain"
"strconv"
"strings"
"time"
"gno.land/p/nt/avl/v0"
"gno.land/r/nt/grc20reg/v0"
)
// Verified assets. A registry proves where a token or a collection comes
// from, not that it is worth anything: anyone can register a token called
// USDC, and an issuer keeps power over its ledger. So a room opened with
// Open accepts only verified assets: GNOT and wrapped GNOT from the start,
// then tokens and NFT collections the admin verifies, each with a public
// reason. A room opened with OpenMarket accepts any registered asset; the
// name of that call is what the wallet shows when it is signed.
//
// A verification counts only VerifyDelay after the admin makes it, so a
// stolen admin key cannot slip a worthless token into ordinary rooms before
// anyone notices; it is public from the moment it is made. Removing a
// verification counts at once: an ordinary room holding that asset can no
// longer settle, and everyone can still take their items back.
// VerifyDelay is how long a new verification waits before it counts.
const VerifyDelay = 24 * 60 * 60 // seconds
// maxReason bounds a verification's public reason.
const maxReason = 280
type verification struct {
reason string
since int64 // unix seconds from which it counts
by address
}
var verified avl.Tree // asset class -> *verification
// seedVerified verifies GNOT and wrapped GNOT from the start.
func seedVerified() {
verified.Set("coin:ugnot", &verification{reason: "The native coin of gno.land."})
verified.Set("token:"+wugnotKey, &verification{reason: "GNOT wrapped one to one by gno.land/r/gnoland/wugnot, a realm with no admin."})
}
// Verify makes a coin denom, a registered GRC20 token or a registered NFT
// collection acceptable in ordinary rooms from VerifyDelay from now. kind
// is coin, token or nft; key is the denom, the registry key or the
// collection key. reason is public: say why this asset is safe to trade.
func Verify(cur realm, kind, key, reason string) {
assertAdmin(cur)
key = strings.TrimSpace(key)
switch kind {
case KindCoin:
assertDenom(key)
case KindToken:
if grc20reg.Get(key) == nil {
panic("token is not in the GRC20 registry")
}
case KindNFT:
mustCollection(key)
default:
panic("kind must be coin, token or nft")
}
reason = strings.TrimSpace(reason)
if reason == "" || len(reason) > maxReason {
panic("give a reason of 1 to " + strconv.Itoa(maxReason) + " bytes")
}
for _, r := range reason {
if r < 0x20 || r == 0x7f {
panic("the reason has a control character")
}
}
since := time.Now().Unix() + VerifyDelay
verified.Set(kind+":"+key, &verification{reason: reason, since: since, by: callerOf(cur)})
chain.Emit("VerifyProposed",
"kind", kind,
"key", key,
"since", strconv.FormatInt(since, 10),
"reason", reason,
)
}
// Unverify removes a verification at once. Ordinary rooms stop accepting
// the asset, and those that hold it can no longer settle; deposits stay
// withdrawable. reason is public.
func Unverify(cur realm, kind, key, reason string) {
assertAdmin(cur)
class := kind + ":" + strings.TrimSpace(key)
if !verified.Has(class) {
panic("that asset is not verified")
}
verified.Remove(class)
chain.Emit("Unverified", "kind", kind, "key", strings.TrimSpace(key), "reason", strings.TrimSpace(reason))
}
// IsVerified reports whether an asset counts as verified now. denom is a
// coin denom, a registry key, or a collection key (with or without
// "#token id").
func IsVerified(kind, denom string) bool {
return isVerified(kind, denom, time.Now().Unix())
}
func classOf(kind, denom string) string {
if kind == KindNFT {
key, _, _ := strings.Cut(denom, "#")
return KindNFT + ":" + key
}
return kind + ":" + denom
}
func isVerified(kind, denom string, now int64) bool {
v := verified.Get(classOf(kind, denom))
return v != nil && now >= v.(*verification).since
}
// assertAccepts refuses an asset an ordinary room does not take.
func (r *room) assertAccepts(kind, denom string) {
if r.openMarket || isVerified(kind, denom, time.Now().Unix()) {
return
}
panic("this room takes only verified assets, and " + denom + " is not verified: trade it in an open-market room")
}
// assertStillVerified stops an ordinary room from settling when one of its
// assets has lost its verification since it went in.
func (r *room) assertStillVerified() {
if r.openMarket {
return
}
now := time.Now().Unix()
for _, list := range [][]asset{r.maker.assets, r.taker.assets, r.want} {
for _, a := range list {
if !isVerified(a.kind, a.denom, now) {
panic(a.denom + " is no longer verified, so this room cannot settle: take your items back")
}
}
}
}
// VerifiedJSON lists verifications, counted or still waiting, with their
// public reasons.
func VerifiedJSON(offset, limit int) string {
offset, limit = page(offset, limit)
now := time.Now().Unix()
items := []string{}
verified.IterateByOffset(offset, limit, func(class string, v any) bool {
kind, key, _ := strings.Cut(class, ":")
ver := v.(*verification)
items = append(items, jsonObject(
"kind", jsonString(kind),
"key", jsonString(key),
"reason", jsonString(ver.reason),
"since", jsonInt(ver.since),
"active", jsonBool(now >= ver.since),
))
return false
})
return jsonObject(
"assets", jsonArray(items),
"more", jsonBool(offset+len(items) < verified.Size()),
"now", jsonInt(now),
)
}