Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

escrow.gno

package cust0dy

import (
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"time"

	"chain"
	"chain/banker"
	"chain/runtime/unsafe"

	core "gno.land/p/g1ejwp09wwnu6psem2sdwrh7l7xcldqm6zz3vu2v/cust0dy_core"
)

func bankerNew(cur realm) banker.Banker {
	return banker.NewBanker(banker.BankerTypeRealmSend, cur)
}

func require(cond bool, msg string) {
	if !cond {
		panic(msg)
	}
}

// ---- roles ----

// ClaimAdmin makes the caller the marketplace operator, once. The deployer
// calls this right after deployment; afterwards it panics for everyone.
// The first admin also becomes the first arbiter.
func ClaimAdmin(cur realm) {
	mustUserCall(cur)
	if admin != address("") {
		panic("admin already claimed")
	}
	admin = cur.Previous().Address()
	arbiter = admin
	chain.Emit("AdminClaimed", "admin", admin.String())
}

// SetArbiter changes the dispute referee. Admin only.
func SetArbiter(cur realm, a address) {
	mustAdmin(cur)
	require(a != address(""), "empty arbiter")
	arbiter = a
	chain.Emit("ArbiterChanged", "arbiter", a.String())
}

// WithdrawFees sends accrued platform fees to the admin. Admin only.
func WithdrawFees(cur realm) {
	mustAdmin(cur)
	require(feesUgnot > 0, "no fees to withdraw")
	amt := feesUgnot
	feesUgnot = 0
	send(cur, admin, amt)
	chain.Emit("FeesWithdrawn", "amount", strconv.FormatInt(amt, 10))
}

// ---- sell side ----

// List creates a sell order for a domain, social handle or Gno handle.
// The asset is not verified yet; see VerificationCode and AttestVerified.
func List(cur realm, kindStr, value string, priceUgnot int64) int {
	mustUserCall(cur)
	kind, err := core.ParseKind(kindStr)
	if err != nil {
		panic(err.Error())
	}
	require(core.ValidateAsset(kind, value) == nil, "invalid asset for its kind")
	require(priceUgnot > 0, "price must be positive")
	require(priceUgnot <= core.MaxPrice, "price too large")

	listingSeq++
	l := &Listing{
		ID:         listingSeq,
		Seller:     cur.Previous().Address(),
		Kind:       kind,
		Value:      value,
		PriceUgnot: priceUgnot,
		State:      core.ListingOpen,
		Created:    time.Now(),
	}
	listings.Set(strconv.Itoa(l.ID), l)
	chain.Emit("ListingCreated",
		"id", strconv.Itoa(l.ID),
		"seller", l.Seller.String(),
		"kind", kind.String(),
		"value", value,
		"price", strconv.FormatInt(priceUgnot, 10),
	)
	return l.ID
}

// VerificationCode is the string the seller must publish off-chain to prove
// control of the asset: a DNS TXT record for a domain, a bio/post code for
// a social or Gno handle. It binds the listing id and the seller address,
// so a code cannot be reused for someone else's listing.
func VerificationCode(id int) string {
	l := getListing(id)
	sum := sha256.Sum256([]byte("cust0dy:" + l.Seller.String() + ":" + strconv.Itoa(id)))
	return "c0_" + hex.EncodeToString(sum[:])[:12]
}

// AttestVerified marks a listing as ownership-verified. Only the arbiter
// (or admin) may attest, and only after an off-chain check, for example
// with verifier/dns_verify.py. The attestation is public and on the record.
func AttestVerified(cur realm, id int) {
	mustArbiter(cur)
	l := getListing(id)
	require(l.State == core.ListingOpen, "listing not open")
	require(!l.Verified, "already verified")
	l.Verified = true
	chain.Emit("ListingVerified", "id", strconv.Itoa(id), "arbiter", cur.Previous().Address().String())
}

// CancelListing withdraws an open listing. Seller only, and only while no
// live escrow holds it.
func CancelListing(cur realm, id int) {
	mustUserCall(cur)
	l := getListing(id)
	require(l.Seller == cur.Previous().Address(), "not your listing")
	require(l.State == core.ListingOpen, "listing not open")
	l.State = core.ListingCancelled
	chain.Emit("ListingCancelled", "id", strconv.Itoa(id))
}

// ---- buy side ----

// Buy purchases a listing at full price. The buyer must attach exactly
// BuyerTotal(price) ugnot (price + 2.5% buyer fee). The coins lock in this
// realm until settlement. Returns the escrow id.
func Buy(cur realm, listingID int) int {
	mustUserCall(cur)
	l := getListing(listingID)
	require(l.State == core.ListingOpen, "listing not open")
	buyer := cur.Previous().Address()
	require(buyer != l.Seller, "cannot buy your own listing")

	want := core.BuyerTotal(l.PriceUgnot)
	sent := unsafe.OriginSend()
	require(len(sent) == 1 && sent[0].Denom == "ugnot" && sent[0].Amount == want,
		"attach exactly "+strconv.FormatInt(want, 10)+"ugnot (price + 2.5% buyer fee)")

	l.State = core.ListingSold
	escrowSeq++
	e := &Escrow{
		ID:          escrowSeq,
		ListingID:   l.ID,
		Seller:      l.Seller,
		Buyer:       buyer,
		PriceUgnot:  l.PriceUgnot,
		LockedUgnot: want,
		State:       core.StateFunded,
		FundedAt:    time.Now(),
	}
	escrows.Set(strconv.Itoa(e.ID), e)
	chain.Emit("EscrowFunded",
		"id", strconv.Itoa(e.ID),
		"listing", strconv.Itoa(l.ID),
		"buyer", buyer.String(),
		"locked", strconv.FormatInt(want, 10),
	)
	return e.ID
}

// MakeOffer locks coins as a buy-side offer on a listing. Offers are
// all-in: no extra buyer fee is charged if the seller accepts. Attach the
// offered amount as ugnot. Returns the offer id.
func MakeOffer(cur realm, listingID int) int {
	mustUserCall(cur)
	l := getListing(listingID)
	require(l.State == core.ListingOpen, "listing not open")
	maker := cur.Previous().Address()
	require(maker != l.Seller, "cannot offer on your own listing")

	sent := unsafe.OriginSend()
	require(len(sent) == 1 && sent[0].Denom == "ugnot" && sent[0].Amount > 0,
		"attach the offered amount in ugnot")

	offerSeq++
	o := &Offer{
		ID:          offerSeq,
		ListingID:   l.ID,
		Maker:       maker,
		AmountUgnot: sent[0].Amount,
		Open:        true,
		Created:     time.Now(),
	}
	offers.Set(strconv.Itoa(o.ID), o)
	chain.Emit("OfferMade",
		"id", strconv.Itoa(o.ID),
		"listing", strconv.Itoa(l.ID),
		"maker", maker.String(),
		"amount", strconv.FormatInt(o.AmountUgnot, 10),
	)
	return o.ID
}

// CancelOffer withdraws an open offer and refunds the maker in full.
func CancelOffer(cur realm, offerID int) {
	mustUserCall(cur)
	o := getOffer(offerID)
	require(o.Open, "offer not open")
	require(o.Maker == cur.Previous().Address(), "not your offer")
	o.Open = false
	send(cur, o.Maker, o.AmountUgnot)
	chain.Emit("OfferCancelled", "id", strconv.Itoa(offerID))
}

// AcceptOffer lets the seller accept an open offer. The offer's locked
// coins become the escrow; the buyer fee is waived (offers are all-in) and
// only the 5% seller fee applies at settlement. Returns the escrow id.
func AcceptOffer(cur realm, offerID int) int {
	mustUserCall(cur)
	o := getOffer(offerID)
	require(o.Open, "offer not open")
	l := getListing(o.ListingID)
	require(l.Seller == cur.Previous().Address(), "not your listing")
	require(l.State == core.ListingOpen, "listing not open")

	o.Open = false
	l.State = core.ListingSold
	escrowSeq++
	e := &Escrow{
		ID:          escrowSeq,
		ListingID:   l.ID,
		Seller:      l.Seller,
		Buyer:       o.Maker,
		PriceUgnot:  o.AmountUgnot,
		LockedUgnot: o.AmountUgnot,
		State:       core.StateFunded,
		FundedAt:    time.Now(),
	}
	escrows.Set(strconv.Itoa(e.ID), e)
	chain.Emit("OfferAccepted",
		"offer", strconv.Itoa(o.ID),
		"escrow", strconv.Itoa(e.ID),
		"listing", strconv.Itoa(l.ID),
	)
	return e.ID
}

// ---- escrow transitions ----

// MarkTransferSubmitted records that the seller has started the off-chain
// handover (registrar push, credential handover, ...). This stops the
// buyer's automatic refund window; from here the exits are buyer
// confirmation or a dispute.
func MarkTransferSubmitted(cur realm, escrowID int) {
	mustUserCall(cur)
	e := getEscrow(escrowID)
	require(e.Seller == cur.Previous().Address(), "seller only")
	require(e.State == core.StateFunded, "not in funded state")
	e.State = core.StateTransferSubmitted
	chain.Emit("TransferSubmitted", "id", strconv.Itoa(escrowID))
}

// ConfirmReceived settles the trade: the seller is paid the agreed price
// minus the 5% seller fee; the remainder of the locked coins is platform
// fee. Buyer only. Never confirm before the asset is actually in your
// control: confirming is final.
func ConfirmReceived(cur realm, escrowID int) {
	mustUserCall(cur)
	e := getEscrow(escrowID)
	require(e.Buyer == cur.Previous().Address(), "buyer only")
	require(core.CanBuyerConfirm(e.State), "cannot confirm in state "+e.State.String())
	e.State = core.StateCompleted
	settle(cur, e)
	chain.Emit("EscrowCompleted", "id", strconv.Itoa(escrowID))
}

// ClaimTimeoutRefund returns the full locked amount to the buyer after
// RefundWindow has passed without the seller submitting a transfer.
func ClaimTimeoutRefund(cur realm, escrowID int) {
	mustUserCall(cur)
	e := getEscrow(escrowID)
	require(e.Buyer == cur.Previous().Address(), "buyer only")
	require(core.CanTimeoutRefund(e.State), "no timeout refund in state "+e.State.String())
	require(time.Since(e.FundedAt) >= RefundWindow, "refund window not reached")
	e.State = core.StateRefunded
	send(cur, e.Buyer, e.LockedUgnot)
	chain.Emit("EscrowRefunded", "id", strconv.Itoa(escrowID), "reason", "timeout")
}

// OpenDispute freezes a live trade for the arbiter. Either party may open
// one; the reason is stored on-chain.
func OpenDispute(cur realm, escrowID int, reason string) {
	mustUserCall(cur)
	e := getEscrow(escrowID)
	party := cur.Previous().Address()
	require(party == e.Buyer || party == e.Seller, "parties only")
	require(core.CanDispute(e.State), "cannot dispute in state "+e.State.String())
	require(reason != "", "give a reason")
	e.State = core.StateDisputed
	e.DisputeReason = reason
	chain.Emit("DisputeOpened",
		"id", strconv.Itoa(escrowID),
		"by", party.String(),
		"reason", reason,
	)
}

// ResolveDispute settles a disputed trade by arbiter decision: paySeller
// true pays the seller as on completion; false refunds the buyer in full.
// Every resolution is public on the record.
func ResolveDispute(cur realm, escrowID int, paySeller bool) {
	mustArbiter(cur)
	e := getEscrow(escrowID)
	require(e.State == core.StateDisputed, "not disputed")
	if paySeller {
		e.State = core.StateResolvedSeller
		settle(cur, e)
	} else {
		e.State = core.StateResolvedBuyer
		send(cur, e.Buyer, e.LockedUgnot)
	}
	chain.Emit("DisputeResolved",
		"id", strconv.Itoa(escrowID),
		"paySeller", strconv.FormatBool(paySeller),
		"arbiter", cur.Previous().Address().String(),
	)
}

// settle pays the seller and books the platform fee. The escrow state must
// already be terminal when this runs.
func settle(cur realm, e *Escrow) {
	payout := core.SellerPayout(e.PriceUgnot)
	fee := e.LockedUgnot - payout
	require(fee >= 0, "fee underflow")
	send(cur, e.Seller, payout)
	feesUgnot += fee
}

gnomod.toml

module = "gno.land/r/g1ejwp09wwnu6psem2sdwrh7l7xcldqm6zz3vu2v/cust0dy"
gno = ""

[addpkg]
  creator = "g1ejwp09wwnu6psem2sdwrh7l7xcldqm6zz3vu2v"
  height = 1539083
  max_deposit = "100000000ugnot"

render.gno

package cust0dy

import (
	"strconv"
	"strings"

	core "gno.land/p/g1ejwp09wwnu6psem2sdwrh7l7xcldqm6zz3vu2v/cust0dy_core"
)

// Render is the gnoweb entry point.
// Routes: "" order book, "l/<id>" listing, "e/<id>" deal room, "u/<addr>" profile.
func Render(path string) string {
	switch {
	case path == "":
		return renderHome()
	case strings.HasPrefix(path, "l/"):
		if id, err := strconv.Atoi(strings.TrimPrefix(path, "l/")); err == nil && id >= 1 && id <= listingSeq {
			return renderListing(getListing(id))
		}
	case strings.HasPrefix(path, "e/"):
		if id, err := strconv.Atoi(strings.TrimPrefix(path, "e/")); err == nil && id >= 1 && id <= escrowSeq {
			return renderEscrow(getEscrow(id))
		}
	case strings.HasPrefix(path, "u/"):
		return renderProfile(strings.TrimPrefix(path, "u/"))
	}
	return "Unknown page. [Back to the order book](:)"
}

func gnot(ugnot int64) string {
	whole := ugnot / 1_000_000
	frac := ugnot % 1_000_000
	if frac == 0 {
		return strconv.FormatInt(whole, 10) + " GNOT"
	}
	fs := strconv.FormatInt(frac+1_000_000, 10)[1:]
	fs = strings.TrimRight(fs, "0")
	return strconv.FormatInt(whole, 10) + "." + fs + " GNOT"
}

func kindBadge(k core.AssetKind) string {
	switch k {
	case core.KindDomain:
		return "domain"
	case core.KindSocial:
		return "social"
	case core.KindGno:
		return "gno handle"
	default:
		return "asset"
	}
}

func renderHome() string {
	var b strings.Builder
	b.WriteString("# Cust0dy\n\n")
	b.WriteString("**Peer-to-peer escrow marketplace for domains and handles.** ")
	b.WriteString("Sell a domain, an X handle or a Gno handle; the buyer's payment locks in this realm and is only released when the buyer confirms the asset arrived. If anything goes wrong, a named arbiter steps in - every decision is on the record.\n\n")
	b.WriteString("> Honest fine print: the assets move off-chain (a registrar push, an account handover). This realm holds the money, records the verification, and referees. It cannot push the domain for you.\n\n")

	b.WriteString("## Order book\n\n")
	open := collectOpenListings()
	if len(open) == 0 {
		b.WriteString("No open listings yet. Use the Actions tab to `List` the first one.\n")
	} else {
		b.WriteString("| Listing | Asset | Price | Verified | Seller |\n")
		b.WriteString("| --- | --- | --- | --- | --- |\n")
		for _, l := range open {
			v := "-"
			if l.Verified {
				v = "**yes**"
			}
			b.WriteString("| [#" + strconv.Itoa(l.ID) + "](:l/" + strconv.Itoa(l.ID) + ") | " +
				kindBadge(l.Kind) + " `" + l.Value + "` | " + gnot(l.PriceUgnot) + " | " + v +
				" | `" + shortAddr(l.Seller.String()) + "` |\n")
		}
	}

	b.WriteString("\n## How it works\n\n")
	b.WriteString("1. **List.** The seller lists the asset and gets a verification code.\n")
	b.WriteString("2. **Verify.** The seller publishes that code where only the owner can - a DNS TXT record for a domain, a bio or post for a handle - and the arbiter attests it on-chain after checking.\n")
	b.WriteString("3. **Fund.** The buyer calls `Buy` (or makes an offer the seller accepts). The payment locks in the realm. Nobody can touch it now except the rules below.\n")
	b.WriteString("4. **Transfer.** The seller moves the asset off-chain and marks the transfer submitted.\n")
	b.WriteString("5. **Settle.** The buyer confirms receipt; the seller is paid minus a 5% seller fee. Buys carry a 2.5% buyer fee; offers are all-in with no buyer fee.\n\n")
	b.WriteString("Safety rails: if the seller never submits a transfer, the buyer gets a full automatic refund after " +
		strconv.Itoa(int(RefundWindow.Hours())) + " hours. If either side disagrees, `OpenDispute` freezes the trade for the arbiter, whose ruling is public.\n")
	if arbiter != address("") {
		b.WriteString("\nArbiter of record: `" + arbiter.String() + "`\n")
	}
	b.WriteString("\n_Fees collected so far: " + gnot(feesUgnot) + "_\n")
	return b.String()
}

func renderListing(l *Listing) string {
	var b strings.Builder
	b.WriteString("# Listing #" + strconv.Itoa(l.ID) + ": `" + l.Value + "`\n\n")
	b.WriteString("| | |\n| --- | --- |\n")
	b.WriteString("| kind | " + kindBadge(l.Kind) + " |\n")
	b.WriteString("| price | **" + gnot(l.PriceUgnot) + "** |\n")
	b.WriteString("| buyer total (with 2.5% fee) | " + gnot(core.BuyerTotal(l.PriceUgnot)) + " |\n")
	b.WriteString("| seller would receive | " + gnot(core.SellerPayout(l.PriceUgnot)) + " |\n")
	b.WriteString("| state | " + l.State.String() + " |\n")
	v := "not yet"
	if l.Verified {
		v = "**verified owner**"
	}
	b.WriteString("| ownership | " + v + " |\n")
	b.WriteString("| seller | `" + l.Seller.String() + "` |\n")

	if l.State == core.ListingOpen {
		b.WriteString("\n## Verification\n\n")
		b.WriteString("The seller proves control by publishing this code where only the owner can:\n\n")
		b.WriteString("```\n" + VerificationCode(l.ID) + "\n```\n\n")
		switch l.Kind {
		case core.KindDomain:
			b.WriteString("As a DNS TXT record on `" + l.Value + "`. Anyone can check it with `verifier/dns_verify.py` from the repo.\n")
		default:
			b.WriteString("In the account's bio or a public post, then shared with the arbiter.\n")
		}
		b.WriteString("\n## Buy or offer\n\n")
		b.WriteString("From the Actions tab (or `gnokey maketx call`):\n\n")
		b.WriteString("- `Buy` with `-send " + strconv.FormatInt(core.BuyerTotal(l.PriceUgnot), 10) + "ugnot` to buy at full price.\n")
		b.WriteString("- `MakeOffer` with your all-in amount attached to offer less.\n")
	} else {
		b.WriteString("\nThis listing is " + l.State.String() + ".\n")
	}
	b.WriteString("\n[Back to the order book](:)\n")
	return b.String()
}

func renderEscrow(e *Escrow) string {
	l := getListing(e.ListingID)
	var b strings.Builder
	b.WriteString("# Deal room #" + strconv.Itoa(e.ID) + "\n\n")
	b.WriteString("Asset: `" + l.Value + "` (" + kindBadge(l.Kind) + ") - [listing #" + strconv.Itoa(l.ID) + "](:l/" + strconv.Itoa(l.ID) + ")\n\n")

	steps := []struct {
		name string
		done bool
	}{
		{"payment locked", true},
		{"transfer submitted", e.State != core.StateFunded},
		{"settled", e.State == core.StateCompleted || e.State == core.StateResolvedSeller},
	}
	for i, s := range steps {
		mark := " "
		if s.done {
			mark = "x"
		}
		b.WriteString("- [" + mark + "] " + strconv.Itoa(i+1) + ". " + s.name + "\n")
	}

	b.WriteString("\n| | |\n| --- | --- |\n")
	b.WriteString("| state | **" + e.State.String() + "** |\n")
	b.WriteString("| agreed price | " + gnot(e.PriceUgnot) + " |\n")
	b.WriteString("| locked | " + gnot(e.LockedUgnot) + " |\n")
	b.WriteString("| buyer | `" + e.Buyer.String() + "` |\n")
	b.WriteString("| seller | `" + e.Seller.String() + "` |\n")
	b.WriteString("| funded | " + e.FundedAt.UTC().Format("2006-01-02 15:04 UTC") + " |\n")
	if e.DisputeReason != "" {
		b.WriteString("| dispute | " + e.DisputeReason + " |\n")
	}

	b.WriteString("\n## Next moves\n\n")
	switch e.State {
	case core.StateFunded:
		b.WriteString("- Seller: move the asset off-chain, then `MarkTransferSubmitted`.\n")
		b.WriteString("- Buyer: if the seller does nothing for " + strconv.Itoa(int(RefundWindow.Hours())) + "h, `ClaimTimeoutRefund` returns everything.\n")
	case core.StateTransferSubmitted:
		b.WriteString("- Buyer: once the asset is in your control, `ConfirmReceived` settles. Confirm only then; it is final.\n")
		b.WriteString("- Either side: `OpenDispute` if something is wrong.\n")
	case core.StateDisputed:
		b.WriteString("- Waiting on the arbiter (`" + arbiter.String() + "`) to rule with `ResolveDispute`.\n")
	default:
		b.WriteString("This trade is closed (" + e.State.String() + ").\n")
	}
	b.WriteString("\n[Back to the order book](:)\n")
	return b.String()
}

func renderProfile(addr string) string {
	var b strings.Builder
	b.WriteString("# Trader `" + addr + "`\n\n")
	var sells, buys []*Escrow
	escrows.IterateByOffset(0, escrowSeq+1, func(_ string, v any) bool {
		e := v.(*Escrow)
		if e.Seller.String() == addr {
			sells = append(sells, e)
		}
		if e.Buyer.String() == addr {
			buys = append(buys, e)
		}
		return false
	})
	var mine []*Listing
	listings.IterateByOffset(0, listingSeq+1, func(_ string, v any) bool {
		l := v.(*Listing)
		if l.Seller.String() == addr {
			mine = append(mine, l)
		}
		return false
	})
	b.WriteString("## Listings\n\n")
	if len(mine) == 0 {
		b.WriteString("None.\n")
	}
	for _, l := range mine {
		b.WriteString("- [#" + strconv.Itoa(l.ID) + "](:l/" + strconv.Itoa(l.ID) + ") `" + l.Value + "` - " + gnot(l.PriceUgnot) + " - " + l.State.String() + "\n")
	}
	b.WriteString("\n## Trades as buyer\n\n")
	if len(buys) == 0 {
		b.WriteString("None.\n")
	}
	for _, e := range buys {
		b.WriteString("- [deal #" + strconv.Itoa(e.ID) + "](:e/" + strconv.Itoa(e.ID) + ") - " + e.State.String() + " - " + gnot(e.LockedUgnot) + " locked\n")
	}
	b.WriteString("\n## Trades as seller\n\n")
	if len(sells) == 0 {
		b.WriteString("None.\n")
	}
	for _, e := range sells {
		b.WriteString("- [deal #" + strconv.Itoa(e.ID) + "](:e/" + strconv.Itoa(e.ID) + ") - " + e.State.String() + " - " + gnot(e.PriceUgnot) + "\n")
	}
	b.WriteString("\n[Back to the order book](:)\n")
	return b.String()
}

func collectOpenListings() []*Listing {
	var out []*Listing
	listings.IterateByOffset(0, listingSeq+1, func(_ string, v any) bool {
		l := v.(*Listing)
		if l.State == core.ListingOpen {
			out = append(out, l)
		}
		return false
	})
	return out
}

func shortAddr(a string) string {
	if len(a) <= 14 {
		return a
	}
	return a[:8] + "..." + a[len(a)-4:]
}

state.gno

// Package cust0dy is the Cust0dy marketplace realm: a peer-to-peer
// order book and automated escrow engine for Web2 domains, social handles
// and Gno handles. Coins lock in this realm at purchase time and move only
// on settlement, refund, or arbiter resolution.
//
// Honesty note: the assets themselves move off-chain (a registrar push, a
// password handover). The realm holds the payment, records verification
// attestations, and gives both sides a referee (the arbiter) when they
// disagree. It cannot force the off-chain transfer itself.
package cust0dy

import (
	"strconv"
	"time"

	"chain"

	core "gno.land/p/g1ejwp09wwnu6psem2sdwrh7l7xcldqm6zz3vu2v/cust0dy_core"
	"gno.land/p/nt/avl/v0"
)

// RefundWindow is how long a buyer can pull an automatic refund while the
// seller has not submitted any transfer. After the seller submits, the exit
// paths are buyer confirmation or a dispute.
const RefundWindow = 24 * time.Hour

// Listing is one sell-side order.
type Listing struct {
	ID         int
	Seller     address
	Kind       core.AssetKind
	Value      string
	PriceUgnot int64
	State      core.ListingState
	Verified   bool
	Created    time.Time
}

// Offer is one buy-side order. The offered amount is locked at creation.
type Offer struct {
	ID           int
	ListingID    int
	Maker        address
	AmountUgnot  int64
	Open         bool
	Created      time.Time
}

// Escrow is one live trade.
type Escrow struct {
	ID            int
	ListingID     int
	Seller        address
	Buyer         address
	PriceUgnot    int64 // agreed price, before fees
	LockedUgnot   int64 // total coins locked by the buyer
	State         core.State
	FundedAt      time.Time
	DisputeReason string
}

var (
	listings   avl.Tree // strconv id -> *Listing
	offers     avl.Tree // strconv id -> *Offer
	escrows    avl.Tree // strconv id -> *Escrow
	listingSeq int
	offerSeq   int
	escrowSeq  int

	admin   address // marketplace operator; claims once, see ClaimAdmin
	arbiter address // dispute referee; set by admin
	feesUgnot int64 // total platform fees accrued (coins sit in the realm balance)
)

func mustUserCall(cur realm) {
	if !cur.Previous().IsUserCall() {
		panic("direct wallet calls only")
	}
}

func mustAdmin(cur realm) {
	mustUserCall(cur)
	if cur.Previous().Address() != admin {
		panic("admin only")
	}
}

func mustArbiter(cur realm) {
	mustUserCall(cur)
	a := cur.Previous().Address()
	if a != arbiter && a != admin {
		panic("arbiter only")
	}
}

func getListing(id int) *Listing {
	v := listings.Get(strconv.Itoa(id))
	if v == nil {
		panic("no such listing")
	}
	return v.(*Listing)
}

func getOffer(id int) *Offer {
	v := offers.Get(strconv.Itoa(id))
	if v == nil {
		panic("no such offer")
	}
	return v.(*Offer)
}

func getEscrow(id int) *Escrow {
	v := escrows.Get(strconv.Itoa(id))
	if v == nil {
		panic("no such escrow")
	}
	return v.(*Escrow)
}

// send moves coins out of the realm balance. Only callable after the state
// transition has already been recorded by the caller.
func send(cur realm, to address, ugnot int64) {
	if ugnot <= 0 {
		return
	}
	b := bankerNew(cur)
	b.SendCoins(cur.Address(), to, chain.Coins{{Denom: "ugnot", Amount: ugnot}})
}

// ---- read helpers used by Render and qeval ----

// ListingCount returns the number of listings ever created.
func ListingCount() int { return listingSeq }

// EscrowCount returns the number of escrows ever created.
func EscrowCount() int { return escrowSeq }

// GetListing returns one listing by id.
func GetListing(id int) Listing { return *getListing(id) }

// GetEscrow returns one escrow by id.
func GetEscrow(id int) Escrow { return *getEscrow(id) }

// AccruedFees returns the total platform fees collected, in ugnot.
func AccruedFees() int64 { return feesUgnot }

// Arbiter returns the current dispute referee.
func Arbiter() address { return arbiter }

// Admin returns the marketplace operator.
func Admin() address { return admin }