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

gnomod.toml

module = "gno.land/r/nym-smelt001/portbook"
gno = "0.9"

[addpkg]
  creator = "g1klc60zh8m3a7v688qt0m5lessx28fttxm0s0y9"
  height = 1501180
  max_deposit = "20000000ugnot"

portbook.gno

// Package portbook is the on-chain Solidity -> Gno Migration Registry & Request Board
// powered by Smelt (https://smeltcli.xyz).
package portbook

import (
	"chain"
	"chain/runtime"
	"strconv"
	"strings"

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

// PortEntry records a Solidity contract transpiled and deployed to Gno.land.
type PortEntry struct {
	ID         uint64
	Name       string
	Category   string
	SourceURL  string
	SolHash    string
	RealmPath  string
	Mode       string // "strict", "idiomatic", or "ai-assisted"
	CleanFuncs int
	TotalFuncs int
	Warns      int
	Holes      int
	Summary    string
	Author     address
	CreatedAt  int64
	Upvotes    uint64
}

// PortRequest records a community request to port a Solidity contract to Gno.land.
type PortRequest struct {
	ID              uint64
	ContractName    string
	Category        string
	SourceURL       string
	Notes           string
	Requester       address
	CreatedAt       int64
	Votes           uint64
	FulfilledPortID uint64
}

var (
	admin        address
	nextPortID   uint64
	nextReqID    uint64
	totalVotes   uint64
	openReqCount uint64

	portsByID    *avl.Tree // key: idKey(id) -> *PortEntry
	requestsByID *avl.Tree // key: idKey(id) -> *PortRequest
	portUpvoters *avl.Tree // key: idKey(id) + ":" + string(addr) -> true
	reqVoters    *avl.Tree // key: idKey(id) + ":" + string(addr) -> true
	contributors *avl.Tree // key: string(addr) -> true
)

func init(cur realm) {
	admin = cur.Previous().Address()
	portsByID = avl.NewTree()
	requestsByID = avl.NewTree()
	portUpvoters = avl.NewTree()
	reqVoters = avl.NewTree()
	contributors = avl.NewTree()
}

// RegisterPort publishes a Solidity -> Gno migration record on-chain.
func RegisterPort(
	cur realm,
	name string,
	category string,
	sourceURL string,
	solHash string,
	realmPath string,
	mode string,
	cleanFuncs int,
	totalFuncs int,
	warns int,
	holes int,
	summary string,
) uint64 {
	name = strings.TrimSpace(name)
	category = normalizeCategory(category)
	sourceURL = strings.TrimSpace(sourceURL)
	solHash = strings.TrimSpace(solHash)
	realmPath = strings.TrimSpace(realmPath)
	mode = normalizeMode(mode)
	summary = strings.TrimSpace(summary)

	if name == "" {
		panic("portbook: name is required")
	}
	if !strings.HasPrefix(realmPath, "gno.land/r/") && !strings.HasPrefix(realmPath, "gno.land/p/") {
		panic("portbook: realmPath must start with gno.land/r/ or gno.land/p/")
	}
	if cleanFuncs < 0 || totalFuncs < 0 || cleanFuncs > totalFuncs {
		panic("portbook: invalid cleanFuncs/totalFuncs counts")
	}
	if warns < 0 || holes < 0 {
		panic("portbook: warns and holes must be non-negative")
	}

	caller := cur.Previous().Address()
	nextPortID++
	entry := &PortEntry{
		ID:         nextPortID,
		Name:       name,
		Category:   category,
		SourceURL:  sourceURL,
		SolHash:    solHash,
		RealmPath:  realmPath,
		Mode:       mode,
		CleanFuncs: cleanFuncs,
		TotalFuncs: totalFuncs,
		Warns:      warns,
		Holes:      holes,
		Summary:    summary,
		Author:     caller,
		CreatedAt:  runtime.ChainHeight(),
		Upvotes:    0,
	}

	portsByID.Set(idKey(entry.ID), entry)
	contributors.Set(string(caller), true)

	chain.Emit(
		"PortRegistered",
		"id", strconv.FormatUint(entry.ID, 10),
		"name", entry.Name,
		"realmPath", entry.RealmPath,
		"mode", entry.Mode,
		"author", string(caller),
	)
	return entry.ID
}

// UpvotePort casts a single upvote per address on a registered port.
func UpvotePort(cur realm, portID uint64) {
	raw := portsByID.Get(idKey(portID))
	if raw == nil {
		panic("portbook: port not found")
	}
	caller := cur.Previous().Address()
	voteKey := idKey(portID) + ":" + string(caller)
	if portUpvoters.Has(voteKey) {
		panic("portbook: already upvoted this port")
	}

	entry := raw.(*PortEntry)
	entry.Upvotes++
	totalVotes++
	portUpvoters.Set(voteKey, true)
	contributors.Set(string(caller), true)

	chain.Emit(
		"PortUpvoted",
		"portID", strconv.FormatUint(portID, 10),
		"voter", string(caller),
		"upvotes", strconv.FormatUint(entry.Upvotes, 10),
	)
}

// RequestPort submits a Solidity contract that the community wants ported to Gno.land.
// Automatically casts the requester's initial vote.
func RequestPort(
	cur realm,
	contractName string,
	category string,
	sourceURL string,
	notes string,
) uint64 {
	contractName = strings.TrimSpace(contractName)
	category = normalizeCategory(category)
	sourceURL = strings.TrimSpace(sourceURL)
	notes = strings.TrimSpace(notes)

	if contractName == "" {
		panic("portbook: contractName is required")
	}

	caller := cur.Previous().Address()
	nextReqID++
	req := &PortRequest{
		ID:              nextReqID,
		ContractName:    contractName,
		Category:        category,
		SourceURL:       sourceURL,
		Notes:           notes,
		Requester:       caller,
		CreatedAt:       runtime.ChainHeight(),
		Votes:           1,
		FulfilledPortID: 0,
	}

	requestsByID.Set(idKey(req.ID), req)
	reqVoters.Set(idKey(req.ID)+":"+string(caller), true)
	contributors.Set(string(caller), true)
	openReqCount++
	totalVotes++

	chain.Emit(
		"PortRequested",
		"id", strconv.FormatUint(req.ID, 10),
		"contractName", req.ContractName,
		"category", req.Category,
		"requester", string(caller),
	)
	return req.ID
}

// VoteRequest casts a single vote per address on an open port request.
func VoteRequest(cur realm, requestID uint64) {
	raw := requestsByID.Get(idKey(requestID))
	if raw == nil {
		panic("portbook: request not found")
	}
	req := raw.(*PortRequest)
	if req.FulfilledPortID != 0 {
		panic("portbook: request is already fulfilled")
	}

	caller := cur.Previous().Address()
	voteKey := idKey(requestID) + ":" + string(caller)
	if reqVoters.Has(voteKey) {
		panic("portbook: already voted on this request")
	}

	req.Votes++
	totalVotes++
	reqVoters.Set(voteKey, true)
	contributors.Set(string(caller), true)

	chain.Emit(
		"RequestVoted",
		"requestID", strconv.FormatUint(requestID, 10),
		"voter", string(caller),
		"votes", strconv.FormatUint(req.Votes, 10),
	)
}

// FulfillRequest links an open community request to a registered PortEntry.
// Callable by the port author, the requester, or the realm admin.
func FulfillRequest(cur realm, requestID uint64, portID uint64) {
	rawReq := requestsByID.Get(idKey(requestID))
	if rawReq == nil {
		panic("portbook: request not found")
	}
	rawPort := portsByID.Get(idKey(portID))
	if rawPort == nil {
		panic("portbook: port not found")
	}

	req := rawReq.(*PortRequest)
	if req.FulfilledPortID != 0 {
		panic("portbook: request already fulfilled")
	}

	port := rawPort.(*PortEntry)
	caller := cur.Previous().Address()
	if caller != port.Author && caller != req.Requester && caller != admin {
		panic("portbook: only port author, requester, or admin can fulfill")
	}

	req.FulfilledPortID = portID
	if openReqCount > 0 {
		openReqCount--
	}

	chain.Emit(
		"RequestFulfilled",
		"requestID", strconv.FormatUint(requestID, 10),
		"portID", strconv.FormatUint(portID, 10),
		"by", string(caller),
	)
}

// Stats returns aggregate registry counters for indexers, tests, and cross-realm reads.
func Stats() (ports uint64, requests uint64, openRequests uint64, votes uint64, uniqueContributors int) {
	return nextPortID, nextReqID, openReqCount, totalVotes, contributors.Size()
}

// GetPort returns a registered port by ID, or nil if it does not exist.
func GetPort(id uint64) *PortEntry {
	raw := portsByID.Get(idKey(id))
	if raw == nil {
		return nil
	}
	return raw.(*PortEntry)
}

// GetRequest returns a community port request by ID, or nil if it does not exist.
func GetRequest(id uint64) *PortRequest {
	raw := requestsByID.Get(idKey(id))
	if raw == nil {
		return nil
	}
	return raw.(*PortRequest)
}

// DeterministicPct returns the integer percentage (0..100) of clean deterministic functions.
func (p *PortEntry) DeterministicPct() int {
	if p.TotalFuncs == 0 {
		if p.Holes == 0 {
			return 100
		}
		return 0
	}
	pct := (p.CleanFuncs * 100) / p.TotalFuncs
	if p.Holes > 0 && pct == 100 {
		return 99
	}
	return pct
}

func idKey(id uint64) string {
	s := strconv.FormatUint(id, 10)
	if len(s) >= 20 {
		return s
	}
	return strings.Repeat("0", 20-len(s)) + s
}

func normalizeMode(mode string) string {
	switch strings.ToLower(strings.TrimSpace(mode)) {
	case "", "strict", "deterministic":
		return "strict"
	case "idiomatic":
		return "idiomatic"
	case "ai-assisted", "hybrid", "assist":
		return "ai-assisted"
	default:
		panic("portbook: mode must be 'strict', 'idiomatic', or 'ai-assisted'")
	}
}

func normalizeCategory(cat string) string {
	cat = strings.TrimSpace(cat)
	if cat == "" {
		return "Utility"
	}
	return cat
}

portbook_test.gno

package portbook

import (
	"strings"
	"testing"

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

func expectPanic(t *testing.T, label string, fn func()) {
	t.Helper()
	if r := revive(fn); r == nil {
		t.Fatalf("%s: expected panic, got none", label)
	}
}

func TestPortBookFullLifecycle(cur realm, t *testing.T) {
	deployer := testutils.TestAddress("deployer")
	alice := testutils.TestAddress("alice")
	bob := testutils.TestAddress("bob")
	admin = deployer

	// 1. Validation checks
	testing.SetRealm(testing.NewUserRealm(alice))
	expectPanic(t, "empty name", func() {
		RegisterPort(cross(cur), "", "Utility", "", "", "gno.land/r/nym-smelt001/x", "strict", 1, 1, 0, 0, "")
	})
	expectPanic(t, "invalid realmPath", func() {
		RegisterPort(cross(cur), "Bad", "Utility", "", "", "https://evil.example/x", "strict", 1, 1, 0, 0, "")
	})
	expectPanic(t, "invalid mode", func() {
		RegisterPort(cross(cur), "BadMode", "Utility", "", "", "gno.land/r/nym-smelt001/x", "magic", 1, 1, 0, 0, "")
	})

	// 2. Register two ports
	id1 := RegisterPort(
		cross(cur),
		"BatchDisperse",
		"Utility",
		"https://github.com/aber-dev-crypto/smelt/blob/main/example-sol/cryptobatch.disperse.sol",
		"sha256:disperse001",
		"gno.land/r/nym-smelt001/disperse",
		"ai-assisted",
		5, 5, 2, 0,
		"Batch native ugnot and token sender refined from Solidity with Smelt.",
	)
	if id1 != 1 {
		t.Fatalf("expected port ID 1, got %d", id1)
	}

	testing.SetRealm(testing.NewUserRealm(bob))
	id2 := RegisterPort(
		cross(cur),
		"SimpleERC20 (GRC-20)",
		"Token",
		"https://github.com/aber-dev-crypto/smelt/blob/main/testdata/contracts/SimpleERC20.sol",
		"sha256:erc20001",
		"gno.land/r/nym-smelt001/demo_grc20",
		"idiomatic",
		7, 7, 1, 0,
		"ERC-20 transpiled idiomatically to native GRC-20 + Ownable.",
	)
	if id2 != 2 {
		t.Fatalf("expected port ID 2, got %d", id2)
	}

	// 3. Upvote and prevent double upvote
	UpvotePort(cross(cur), id1)
	if p := GetPort(id1); p == nil || p.Upvotes != 1 {
		t.Fatalf("expected 1 upvote on port 1, got %+v", p)
	}
	expectPanic(t, "double upvote", func() {
		UpvotePort(cross(cur), id1)
	})

	// 4. Community Request + Vote + Prevent double vote + Fulfill
	testing.SetRealm(testing.NewUserRealm(alice))
	reqID := RequestPort(
		cross(cur),
		"WETH9",
		"DeFi",
		"https://etherscan.io/address/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
		"Wrapped native GNOT interface for DeFi composability",
	)
	if reqID != 1 {
		t.Fatalf("expected request ID 1, got %d", reqID)
	}
	if r := GetRequest(reqID); r == nil || r.Votes != 1 || r.FulfilledPortID != 0 {
		t.Fatalf("unexpected initial request state: %+v", r)
	}

	// Requester already auto-voted
	expectPanic(t, "requester double vote", func() {
		VoteRequest(cross(cur), reqID)
	})

	// Bob votes on the request
	testing.SetRealm(testing.NewUserRealm(bob))
	VoteRequest(cross(cur), reqID)
	if r := GetRequest(reqID); r == nil || r.Votes != 2 {
		t.Fatalf("expected 2 votes on request 1, got %+v", r)
	}

	// Random stranger cannot fulfill
	stranger := testutils.TestAddress("stranger")
	testing.SetRealm(testing.NewUserRealm(stranger))
	expectPanic(t, "unauthorized fulfill", func() {
		FulfillRequest(cross(cur), reqID, id2)
	})

	// Port author (bob) fulfills the request with id2
	testing.SetRealm(testing.NewUserRealm(bob))
	FulfillRequest(cross(cur), reqID, id2)
	if r := GetRequest(reqID); r == nil || r.FulfilledPortID != id2 {
		t.Fatalf("expected request fulfilled by port %d, got %+v", id2, r)
	}

	// Cannot vote on fulfilled request
	testing.SetRealm(testing.NewUserRealm(stranger))
	expectPanic(t, "vote on fulfilled request", func() {
		VoteRequest(cross(cur), reqID)
	})

	// 5. Verify stats
	ports, reqs, openReqs, votes, uniq := Stats()
	if ports != 2 || reqs != 1 || openReqs != 0 || votes != 3 || uniq != 2 {
		t.Fatalf("unexpected stats: ports=%d reqs=%d open=%d votes=%d uniq=%d", ports, reqs, openReqs, votes, uniq)
	}

	// 6. Verify Render routes
	home := Render("")
	for _, want := range []string{"Smelt PortBook", "BatchDisperse", "SimpleERC20 (GRC-20)", "WETH9", "UpvotePort", "RegisterPort", "RequestPort"} {
		if !strings.Contains(home, want) {
			t.Errorf("home Render() missing %q:\n%s", want, home)
		}
	}
	if detail := Render("port/1"); !strings.Contains(detail, "BatchDisperse") || !strings.Contains(detail, "sha256:disperse001") {
		t.Errorf("port/1 Render() unexpected:\n%s", detail)
	}
	if reqView := Render("request/1"); !strings.Contains(reqView, "WETH9") || !strings.Contains(reqView, "Fulfilled") {
		t.Errorf("request/1 Render() unexpected:\n%s", reqView)
	}
	if allPorts := Render("ports"); !strings.Contains(allPorts, "SimpleERC20") {
		t.Errorf("ports Render() unexpected:\n%s", allPorts)
	}
	if allReqs := Render("requests"); !strings.Contains(allReqs, "WETH9") {
		t.Errorf("requests Render() unexpected:\n%s", allReqs)
	}
}

render.gno

package portbook

import (
	"strconv"
	"strings"

	"gno.land/p/moul/txlink/v0"
	"gno.land/p/nt/ufmt/v0"
)

// Render exposes the interactive Markdown UI in gnoweb with clickable Adena txlinks.
func Render(path string) string {
	path = strings.Trim(path, "/")

	switch {
	case path == "":
		return renderHome()
	case path == "ports":
		return renderAllPorts()
	case path == "requests":
		return renderAllRequests()
	case strings.HasPrefix(path, "port/"):
		id, err := strconv.ParseUint(strings.TrimPrefix(path, "port/"), 10, 64)
		if err != nil {
			return "# Invalid Port ID\n\n[← Back to PortBook](:)\n"
		}
		return renderPortDetail(id)
	case strings.HasPrefix(path, "request/"):
		id, err := strconv.ParseUint(strings.TrimPrefix(path, "request/"), 10, 64)
		if err != nil {
			return "# Invalid Request ID\n\n[← Back to PortBook](:)\n"
		}
		return renderRequestDetail(id)
	default:
		return "# Smelt PortBook — 404\n\nUnknown route `" + path + "`.\n\n[← Back to PortBook](:)\n"
	}
}

func renderHome() string {
	var b strings.Builder

	b.WriteString("# Smelt PortBook\n\n")
	b.WriteString("**On-Chain Solidity → Native Gno Migration Registry & Community Port Board.**\n\n")
	b.WriteString("Powered by **[Smelt](https://smeltcli.xyz)** (`smelt analyze` · `smelt convert` · `smelt verify` · `smelt deploy`) — *independent community tool for Gno.land.*\n\n")

	// KPI summary
	b.WriteString("| Registered Ports | Open Requests | Community Votes | Unique Contributors |\n")
	b.WriteString("| :---: | :---: | :---: | :---: |\n")
	b.WriteString(ufmt.Sprintf("| **%d** | **%d** | **%d** | **%d** |\n\n",
		nextPortID, openReqCount, totalVotes, contributors.Size()))

	// Quick actions via txlink (Adena 1-click)
	regURL := txlink.NewLink("RegisterPort").
		AddArgs("name", "", "category", "Utility", "sourceURL", "", "solHash", "", "realmPath", "gno.land/r/", "mode", "idiomatic", "cleanFuncs", "1", "totalFuncs", "1", "warns", "0", "holes", "0", "summary", "").
		URL()
	reqURL := txlink.NewLink("RequestPort").
		AddArgs("contractName", "", "category", "DeFi", "sourceURL", "", "notes", "").
		URL()

	b.WriteString(ufmt.Sprintf("**Actions:** [+ Register a Port](%s) · [+ Request a Solidity Contract](%s) · [All Ports](:ports) · [All Requests](:requests)\n\n",
		regURL, reqURL))

	b.WriteString("---\n\n")
	b.WriteString("## Live Transpiled Contracts\n\n")
	b.WriteString(renderPortsTable(10))

	b.WriteString("\n---\n\n")
	b.WriteString("## Community Port Requests\n\n")
	b.WriteString("Vote on which Ethereum/Solidity protocol should be ported to native Gno next:\n\n")
	b.WriteString(renderRequestsTable(10))

	b.WriteString("\n---\n\n")
	b.WriteString("### Built with Smelt\n")
	b.WriteString("- Shared on-chain runtime: [`gno.land/p/nym-smelt001/solrt`](/p/nym-smelt001/solrt)\n")
	b.WriteString("- CLI & Docs: [smeltcli.xyz](https://smeltcli.xyz) · [github.com/aber-dev-crypto/smelt](https://github.com/aber-dev-crypto/smelt)\n")

	return b.String()
}

func renderAllPorts() string {
	var b strings.Builder
	b.WriteString("# Smelt PortBook — All Registered Ports\n\n")
	b.WriteString("[← Home](:) · [Requests Board](:requests)\n\n")
	b.WriteString(renderPortsTable(0))
	return b.String()
}

func renderAllRequests() string {
	var b strings.Builder
	b.WriteString("# Smelt PortBook — Community Port Requests\n\n")
	b.WriteString("[← Home](:) · [Registered Ports](:ports)\n\n")
	b.WriteString(renderRequestsTable(0))
	return b.String()
}

func renderPortsTable(limit int) string {
	if portsByID.Size() == 0 {
		return "_No ports registered yet. Be the first to publish a Solidity → Gno migration!_\n"
	}

	var b strings.Builder
	b.WriteString("| # | Contract | Category | Mode | Deterministic | Live Deployment | Upvotes |\n")
	b.WriteString("| :---: | :--- | :--- | :---: | :---: | :--- | :---: |\n")

	count := 0
	portsByID.ReverseIterate("", "", func(_ string, v interface{}) bool {
		if limit > 0 && count >= limit {
			return true
		}
		p := v.(*PortEntry)
		relRealm := strings.TrimPrefix(p.RealmPath, "gno.land")
		upURL := txlink.NewLink("UpvotePort").AddArgs("portID", strconv.FormatUint(p.ID, 10)).URL()
		b.WriteString(ufmt.Sprintf(
			"| [#%d](:port/%d) | **%s** | %s | `%s` | %d%% (%d/%d) | [`%s`](%s) | %d [▲](%s) |\n",
			p.ID, p.ID, escapeCell(p.Name), escapeCell(p.Category), p.Mode,
			p.DeterministicPct(), p.CleanFuncs, p.TotalFuncs,
			p.RealmPath, relRealm, p.Upvotes, upURL,
		))
		count++
		return false
	})

	return b.String()
}

func renderRequestsTable(limit int) string {
	if requestsByID.Size() == 0 {
		return "_No open requests yet. Submit a Solidity contract you want ported to Gno!_\n"
	}

	var b strings.Builder
	b.WriteString("| # | Solidity Contract | Category | Status | Votes | Action |\n")
	b.WriteString("| :---: | :--- | :--- | :---: | :---: | :---: |\n")

	count := 0
	requestsByID.ReverseIterate("", "", func(_ string, v interface{}) bool {
		if limit > 0 && count >= limit {
			return true
		}
		r := v.(*PortRequest)
		status := "Open"
		action := ufmt.Sprintf("[▲ Vote](%s)", txlink.NewLink("VoteRequest").AddArgs("requestID", strconv.FormatUint(r.ID, 10)).URL())
		if r.FulfilledPortID != 0 {
			status = ufmt.Sprintf("Ported → [#%d](:port/%d)", r.FulfilledPortID, r.FulfilledPortID)
			action = "✓"
		}
		b.WriteString(ufmt.Sprintf(
			"| [#%d](:request/%d) | **%s** | %s | %s | **%d** | %s |\n",
			r.ID, r.ID, escapeCell(r.ContractName), escapeCell(r.Category), status, r.Votes, action,
		))
		count++
		return false
	})

	return b.String()
}

func renderPortDetail(id uint64) string {
	p := GetPort(id)
	if p == nil {
		return "# Port Not Found\n\n[← Back to PortBook](:)\n"
	}

	relRealm := strings.TrimPrefix(p.RealmPath, "gno.land")
	upURL := txlink.NewLink("UpvotePort").AddArgs("portID", strconv.FormatUint(p.ID, 10)).URL()

	var b strings.Builder
	b.WriteString(ufmt.Sprintf("# Port #%d — %s\n\n", p.ID, p.Name))
	b.WriteString("[← Home](:) · [All Ports](:ports)\n\n")

	if p.Summary != "" {
		b.WriteString("> " + p.Summary + "\n\n")
	}

	b.WriteString("| Field | Value |\n| :--- | :--- |\n")
	b.WriteString(ufmt.Sprintf("| **Live Deployment** | [`%s`](%s) |\n", p.RealmPath, relRealm))
	b.WriteString(ufmt.Sprintf("| **Category** | %s |\n", escapeCell(p.Category)))
	b.WriteString(ufmt.Sprintf("| **Transpile Mode** | `%s` |\n", p.Mode))
	b.WriteString(ufmt.Sprintf("| **Deterministic Score** | **%d%%** (%d/%d clean functions) |\n", p.DeterministicPct(), p.CleanFuncs, p.TotalFuncs))
	b.WriteString(ufmt.Sprintf("| **Analyzer Diagnostics** | %d warns · %d holes |\n", p.Warns, p.Holes))
	if p.SolHash != "" {
		b.WriteString(ufmt.Sprintf("| **Solidity SHA-256** | `%s` |\n", p.SolHash))
	}
	if p.SourceURL != "" {
		b.WriteString(ufmt.Sprintf("| **Solidity Source** | [%s](%s) |\n", p.SourceURL, p.SourceURL))
	}
	b.WriteString(ufmt.Sprintf("| **Author** | `%s` |\n", string(p.Author)))
	b.WriteString(ufmt.Sprintf("| **Block Height** | #%d |\n", p.CreatedAt))
	b.WriteString(ufmt.Sprintf("| **Upvotes** | **%d** ([▲ Upvote this Port](%s)) |\n", p.Upvotes, upURL))

	return b.String()
}

func renderRequestDetail(id uint64) string {
	r := GetRequest(id)
	if r == nil {
		return "# Request Not Found\n\n[← Back to PortBook](:)\n"
	}

	var b strings.Builder
	b.WriteString(ufmt.Sprintf("# Request #%d — %s\n\n", r.ID, r.ContractName))
	b.WriteString("[← Home](:) · [All Requests](:requests)\n\n")

	if r.Notes != "" {
		b.WriteString("> " + r.Notes + "\n\n")
	}

	b.WriteString("| Field | Value |\n| :--- | :--- |\n")
	b.WriteString(ufmt.Sprintf("| **Category** | %s |\n", escapeCell(r.Category)))
	if r.SourceURL != "" {
		b.WriteString(ufmt.Sprintf("| **Reference Source** | [%s](%s) |\n", r.SourceURL, r.SourceURL))
	}
	b.WriteString(ufmt.Sprintf("| **Requester** | `%s` |\n", string(r.Requester)))
	b.WriteString(ufmt.Sprintf("| **Block Height** | #%d |\n", r.CreatedAt))
	b.WriteString(ufmt.Sprintf("| **Votes** | **%d** |\n", r.Votes))

	if r.FulfilledPortID != 0 {
		b.WriteString(ufmt.Sprintf("| **Status** | Fulfilled by [Port #%d](:port/%d) |\n", r.FulfilledPortID, r.FulfilledPortID))
	} else {
		voteURL := txlink.NewLink("VoteRequest").AddArgs("requestID", strconv.FormatUint(r.ID, 10)).URL()
		fulfillURL := txlink.NewLink("FulfillRequest").AddArgs("requestID", strconv.FormatUint(r.ID, 10), "portID", "").URL()
		b.WriteString(ufmt.Sprintf("| **Status** | Open — [▲ Vote](%s) · [Mark Fulfilled](%s) |\n", voteURL, fulfillURL))
	}

	return b.String()
}

func escapeCell(s string) string {
	s = strings.ReplaceAll(s, "|", "\\|")
	s = strings.ReplaceAll(s, "\n", " ")
	return s
}