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 escrow

import (
	"chain"
	"errors"
	"strconv"
	"strings"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
	"gno.land/p/nt/avl/v0"
)

// State constants for a deal's lifecycle.
const (
	StateOpen     = "Open"
	StateSettled  = "Settled"
	StateCanceled = "Canceled"
)

// Deal is a 2-party escrow record. Accounting only: no funds move,
// this tracks agreement and mutual confirmation between two parties.
type Deal struct {
	ID           int
	Creator      address
	Counterparty address
	Terms        string
	State        string
	CreatorOK    bool
	CounterOK    bool
}

var (
	deals  = avl.NewTree() // id (string) -> *Deal
	nextID int
)

var (
	errNotFound   = errors.New("escrow: deal not found")
	errNotParty   = errors.New("escrow: caller is not a party to this deal")
	errNotOpen    = errors.New("escrow: deal is not open")
	errNotCreator = errors.New("escrow: only the creator can cancel")
	errBadAddr    = errors.New("escrow: invalid counterparty address")
	errSelfDeal   = errors.New("escrow: counterparty must differ from creator")
)

// Create opens a new escrow deal between the caller (creator) and the
// given counterparty, governed by a free-form terms string. Returns the
// new deal id. Panics on invalid input (cross-realm abort).
func Create(cur realm, counterparty address, terms string) int {
	if !cur.IsCurrent() {
		panic("escrow: spoofed realm")
	}
	if !counterparty.IsValid() {
		panic(errBadAddr)
	}
	creator := cur.Previous().Address()
	if counterparty == creator {
		panic(errSelfDeal)
	}

	id := nextID
	nextID++

	d := &Deal{
		ID:           id,
		Creator:      creator,
		Counterparty: counterparty,
		Terms:        terms,
		State:        StateOpen,
	}
	deals.Set(strconv.Itoa(id), d)

	chain.Emit("Created", "id", strconv.Itoa(id),
		"creator", creator.String(), "counterparty", counterparty.String())
	return id
}

// Confirm records confirmation by whichever party is calling. Once both
// parties have confirmed, the deal transitions to Settled.
func Confirm(cur realm, id int) {
	if !cur.IsCurrent() {
		panic("escrow: spoofed realm")
	}
	d := mustGet(id)
	if d.State != StateOpen {
		panic(errNotOpen)
	}
	caller := cur.Previous().Address()

	switch caller {
	case d.Creator:
		d.CreatorOK = true
	case d.Counterparty:
		d.CounterOK = true
	default:
		panic(errNotParty)
	}

	chain.Emit("Confirmed", "id", strconv.Itoa(id), "party", caller.String())

	if d.CreatorOK && d.CounterOK {
		d.State = StateSettled
		chain.Emit("Settled", "id", strconv.Itoa(id))
	}
}

// Cancel voids an open deal. Only the creator may cancel, and only
// before the deal has settled.
func Cancel(cur realm, id int) {
	if !cur.IsCurrent() {
		panic("escrow: spoofed realm")
	}
	d := mustGet(id)
	if d.State != StateOpen {
		panic(errNotOpen)
	}
	caller := cur.Previous().Address()
	if caller != d.Creator {
		panic(errNotCreator)
	}
	d.State = StateCanceled
	chain.Emit("Canceled", "id", strconv.Itoa(id))
}

func mustGet(id int) *Deal {
	v := deals.Get(strconv.Itoa(id))
	if v == nil {
		panic(errNotFound)
	}
	return v.(*Deal)
}

// Render lists all escrow deals with their parties, terms, and state.
// When path is a numeric id, renders just that deal.
func Render(path string) string {
	path = strings.TrimSpace(strings.Trim(path, "/"))
	if path != "" {
		if id, err := strconv.Atoi(path); err == nil {
			v := deals.Get(strconv.Itoa(id))
			if v == nil {
				return "# Escrow\n\nDeal " + md.InlineCode(path) + " not found.\n"
			}
			return renderOne(v.(*Deal))
		}
	}

	var b strings.Builder
	b.WriteString("# Escrow\n\n")
	b.WriteString("2-party escrow deals (accounting only — no funds move).\n\n")

	if deals.Size() == 0 {
		b.WriteString("_No deals yet._\n")
		return b.String()
	}

	b.WriteString("| ID | Creator | Counterparty | State | Confirmations | Terms |\n")
	b.WriteString("|----|---------|--------------|-------|---------------|-------|\n")
	deals.Iterate("", "", func(_ string, v interface{}) bool {
		d := v.(*Deal)
		b.WriteString("| " + strconv.Itoa(d.ID) +
			" | " + ui.Addr(d.Creator) +
			" | " + ui.Addr(d.Counterparty) +
			" | " + d.State +
			" | " + confs(d) +
			" | " + ui.Cell(d.Terms) + " |\n")
		return false
	})
	return b.String()
}

func renderOne(d *Deal) string {
	var b strings.Builder
	b.WriteString("# Escrow Deal #" + strconv.Itoa(d.ID) + "\n\n")
	b.WriteString("- **State:** " + d.State + "\n")
	b.WriteString("- **Creator:** " + d.Creator.String() + " (" + yn(d.CreatorOK) + ")\n")
	b.WriteString("- **Counterparty:** " + d.Counterparty.String() + " (" + yn(d.CounterOK) + ")\n")
	b.WriteString("- **Terms:** " + ui.Inline(d.Terms) + "\n")
	return b.String()
}

func confs(d *Deal) string {
	n := 0
	if d.CreatorOK {
		n++
	}
	if d.CounterOK {
		n++
	}
	return strconv.Itoa(n) + "/2"
}

func yn(b bool) string {
	if b {
		return "confirmed"
	}
	return "pending"
}

escrow_test.gno

package escrow

import (
	"strconv"
	"strings"
	"testing"

	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
)

var (
	alice = testutils.TestAddress("alice")
	bob   = testutils.TestAddress("bob")
	carol = testutils.TestAddress("carol")
)

func resetState() {
	deals = avl.NewTree()
	nextID = 0
}

func TestCreateAndConfirmSettles(cur realm, t *testing.T) {
	resetState()

	// Alice creates a deal with Bob.
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Create(cross(cur), bob, "swap NFT for 100 GNOT")
	uassert.Equal(t, 0, id)

	// Alice confirms (1/2, still open).
	Confirm(cross(cur), id)
	out := Render("0")
	uassert.True(t, strings.Contains(out, "State:** Open"), "expected still open after one confirm")

	// Bob confirms -> settles.
	testing.SetRealm(testing.NewUserRealm(bob))
	Confirm(cross(cur), id)

	out = Render("0")
	uassert.True(t, strings.Contains(out, "Settled"), "expected Settled state")
	uassert.True(t, strings.Contains(out, "swap NFT for 100 GNOT"), "expected terms")
}

func TestCancelByCreator(cur realm, t *testing.T) {
	resetState()

	testing.SetRealm(testing.NewUserRealm(alice))
	id := Create(cross(cur), bob, "rent payment")

	Cancel(cross(cur), id)

	out := Render("")
	uassert.True(t, strings.Contains(out, "Canceled"), "expected Canceled state")
}

func TestNonPartyCannotConfirm(cur realm, t *testing.T) {
	resetState()

	testing.SetRealm(testing.NewUserRealm(alice))
	id := Create(cross(cur), bob, "consulting")

	// Carol is not a party.
	testing.SetRealm(testing.NewUserRealm(carol))
	uassert.AbortsWithMessage(t, cur, "escrow: caller is not a party to this deal", func() {
		Confirm(cross(cur), id)
	})
}

func TestOnlyCreatorCancels(cur realm, t *testing.T) {
	resetState()

	testing.SetRealm(testing.NewUserRealm(alice))
	id := Create(cross(cur), bob, "loan")

	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "escrow: only the creator can cancel", func() {
		Cancel(cross(cur), id)
	})
}

// The list view escaped Terms and the deal page did not, so a caller's terms
// rendered as live markdown on the realm's own page.
func TestDealPageEscapesTerms(cur realm, t *testing.T) {
	resetState()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Create(cross(cur), bob, "[claim](https://evil.example)")
	out := Render(strconv.Itoa(id))
	uassert.False(t, strings.Contains(out, "[claim](https://evil.example)"), out)
}

gnomod.toml

module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/escrow/v1"
gno = "0.9"
private = true

[addpkg]
  creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv"
  height = 914308
  max_deposit = "5000000ugnot"