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

admin.gno

package pool

import (
	mimir "gno.land/p/g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz/mimir"
)

// Role administration. The rules live in mimir.Roles; see its doc.

func TransferOwnership(cur realm, next address) { roles.TransferOwnership(caller(cur), next, now()) }
func CancelOwnershipTransfer(cur realm)         { roles.CancelOwnershipTransfer(caller(cur)) }
func AcceptOwnership(cur realm)                 { roles.AcceptOwnership(caller(cur), now()) }
func QueueOracle(cur realm, next address)       { roles.QueueOracle(caller(cur), next, now()) }
func RevokeOracle(cur realm)                    { roles.RevokeOracle(caller(cur)) }
func CancelOracle(cur realm)                    { roles.CancelOracle(caller(cur)) }
func ExecuteOracle(cur realm)                   { roles.ExecuteOracle(now()) }
func SetArbiter(cur realm, next address)        { roles.SetArbiter(caller(cur), next) }
func QueueFeeRecipient(cur realm, next address) { roles.QueueFeeRecipient(caller(cur), next, now()) }
func CancelFeeRecipient(cur realm)              { roles.CancelFeeRecipient(caller(cur)) }
func ExecuteFeeRecipient(cur realm)             { roles.ExecuteFeeRecipient(now()) }
func SetPaused(cur realm, p bool)               { roles.SetPaused(caller(cur), p) }

// SetAuditAgent appoints the reviewer that may dispute with a bond; "" disables it.
func SetAuditAgent(cur realm, next string) {
	roles.SetAuditAgent(caller(cur), mimir.ParseOptional(next))
}

// SetCaps sets guarded launch caps in net mUSD units (0 = none). They only gate new stakes.
func SetCaps(cur realm, market, account int64) { roles.SetCaps(caller(cur), market, account) }

// SetLockAt closes a market to new stakes early (kickoff), by its creator or
// the owner. Only ever earlier.
func SetLockAt(cur realm, id int64, at int64) {
	m := getMarket(id)
	c := caller(cur)
	if c != m.Creator && c != roles.Owner {
		panic("BadLock")
	}
	if m.State != StOpen || at < now() || at+LockSeconds > m.Deadline {
		panic("BadLock")
	}
	if m.LockAt != 0 && at > m.LockAt {
		panic("BadLock")
	}
	m.LockAt = at
	emit("LockSet", "id", itoa(id), "lockAt", itoa(at))
}

claims.gno

package pool

import (
	mimir "gno.land/p/g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz/mimir"
)

// owed is what `user` is owed from a resolved market: gross = stake back +
// share of the losing side. Full refund when either side is empty or on DRAW /
// UNRESOLVABLE. feeBase is the profit copy fees may be charged on: the user's
// NET profit (the share less their own stake on the losing side, so a hedger
// never pays a copy fee on their own money), counted only on the copied part
// of the winning stake. Deposits at or after the settlement cutoff are late:
// their net principal comes back and they share in nothing.
func owed(m *Market, p *Position) (gross, feeBase int64) {
	if p == nil {
		return 0, 0
	}
	raw := p.A + p.B
	if m.Outcome >= Draw {
		return raw, 0
	}
	totals := m.history.Before(m.SettlementCutoff)
	mine := p.history.Before(m.SettlementCutoff)
	if totals.A == 0 || totals.B == 0 {
		return raw, 0
	}
	late := raw - mine.A - mine.B
	win, lose, copied, opposite, winners := mine.A, mine.B, mine.CopiedA, totals.B, totals.A
	if m.Outcome == SideB {
		win, lose, copied, opposite, winners = mine.B, mine.A, mine.CopiedB, totals.A, totals.B
	}
	if win == 0 {
		return late, 0
	}
	profit := mimir.MulDiv(win, opposite, winners)
	gross = late + win + profit
	if profit > lose && copied != 0 {
		feeBase = mimir.MulDiv(profit-lose, copied, win)
	}
	return gross, feeBase
}

func winnerPayout(m *Market, p *Position) bool {
	if m.Outcome >= Draw || p == nil {
		return false
	}
	totals := m.history.Before(m.SettlementCutoff)
	if totals.A == 0 || totals.B == 0 {
		return false
	}
	mine := p.history.Before(m.SettlementCutoff)
	if m.Outcome == SideA {
		return mine.A != 0
	}
	return mine.B != 0
}

// copyFees are the copy-trade fees on the copied net profit: (to the
// referrer, to the platform). Nobody pays themselves: a referrer or fee
// recipient who is the user waives that leg.
func copyFees(user address, p *Position, feeBase int64) (toRef, toPlatform int64) {
	if feeBase == 0 || p.Referrer == "" || p.Referrer == user {
		return 0, 0
	}
	toRef = mimir.MulDiv(feeBase, ReferrerFeeBps, 10_000)
	if roles.FeeRecipient != user {
		toPlatform = mimir.MulDiv(feeBase, CopyFeeBps, 10_000)
	}
	return toRef, toPlatform
}

// Claim collects the caller's own payout.
func Claim(cur realm, id int64) {
	claimFor(cur, id, caller(cur))
}

// ClaimFor lets anyone push a user's payout to them. The money only ever goes to `user`.
func ClaimFor(cur realm, id int64, user address) {
	claimFor(cur, id, user)
}

func claimFor(cur realm, id int64, user address) {
	m := getMarket(id)
	if m.State != StResolved {
		panic("NotResolved")
	}
	p := m.position(user)
	// Paused: refunds still go out; a winner waits for the unpause.
	if roles.Paused && winnerPayout(m, p) {
		panic("IsPaused")
	}
	if p != nil && p.Claimed {
		panic("AlreadyClaimed")
	}
	gross, feeBase := owed(m, p)
	if gross == 0 {
		panic("NothingToClaim")
	}
	p.Claimed = true
	toRef, toPlatform := copyFees(user, p, feeBase)
	if toRef != 0 {
		accrue(id, p.Referrer, toRef)
	}
	if toPlatform != 0 {
		accrue(id, roles.FeeRecipient, toPlatform)
	}
	fee := toRef + toPlatform
	emit("Claimed", "id", itoa(id), "user", user.String(), "paid", itoa(gross-fee), "fee", itoa(fee))
	push(cur, user, gross-fee)
}

// ClaimFees pays the caller's accrued fees (entry fees, copy fees, forfeited bonds).
func ClaimFees(cur realm) {
	claimFeesTo(cur, caller(cur))
}

func ClaimFeesTo(cur realm, to address) {
	if !to.IsValid() {
		panic("ZeroAddress")
	}
	claimFeesTo(cur, to)
}

func claimFeesTo(cur realm, to address) {
	c := caller(cur)
	amount := feesOf(c)
	if amount == 0 {
		panic("NothingToWithdraw")
	}
	accruedFees.Set(c.String(), int64(0))
	lifetimeFeesClaimed = mimir.Add(lifetimeFeesClaimed, amount)
	emit("FeeClaimed", "recipient", c.String(), "to", to.String(), "amount", itoa(amount))
	push(cur, to, amount)
}

gnomod.toml

module = "gno.land/r/g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz/pool"
gno = "0.9"

[addpkg]
  creator = "g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz"
  height = 1404518
  max_deposit = "500000000ugnot"

markets.gno

package pool

import (
	mimir "gno.land/p/g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz/mimir"
)

// CreateMarket opens a market with `amount` mUSD (pulled from the caller,
// less the entry fee) staked on `side` (SideA or SideB). `referrer` is the
// copied basket's creator, or "" for none. Returns the new market's id.
func CreateMarket(cur realm, question, labelA, labelB, resolutionURL, category string,
	deadline int64, side int, referrer string, amount int64) int64 {
	assertNotPaused()
	if question == "" {
		panic("EmptyQuestion")
	}
	// At most a year out, so a staked market never locks funds indefinitely.
	if deadline < now()+LockSeconds || deadline > now()+MaxDeadlineAhead {
		panic("BadDeadline")
	}
	marketCount++
	id := marketCount
	m := &Market{
		ID:            id,
		Creator:       caller(cur),
		Deadline:      deadline,
		CreatedAt:     now(),
		Question:      question,
		LabelA:        labelA,
		LabelB:        labelB,
		ResolutionURL: resolutionURL,
		Category:      category,
	}
	markets.Set(key(id), m)
	emit("MarketCreated", "id", itoa(id), "creator", m.Creator.String(), "deadline", itoa(deadline), "category", category)
	addStake(cur, m, side, parseReferrer(referrer), amount)
	return id
}

// Stake puts `amount` mUSD (less the entry fee) on `side`. Repeated stakes add up.
func Stake(cur realm, id int64, side int, referrer string, amount int64) {
	assertNotPaused()
	m := getMarket(id)
	if m.State != StOpen {
		panic("NotOpen")
	}
	if now()+LockSeconds > m.Deadline {
		panic("BettingClosed")
	}
	if m.LockAt != 0 && now() >= m.LockAt {
		panic("BettingClosed")
	}
	addStake(cur, m, side, parseReferrer(referrer), amount)
}

func addStake(cur realm, m *Market, side int, referrer address, amount int64) {
	if amount < MinStake {
		panic("StakeTooSmall")
	}
	user := caller(cur)
	pull(cur, user, amount)
	bps := entryBps(user)
	if bps > MaxEntryBps {
		panic("EntryFeeTooHigh")
	}
	fee := mimir.MulDiv(amount, bps, 10_000)
	if fee != 0 {
		m.EntryFees += fee
		accrue(m.ID, roles.FeeRecipient, fee)
	}
	net := amount - fee
	p := m.mustPosition(user)
	switch side {
	case SideA:
		p.A = mimir.Add(p.A, net)
		m.TotalA = mimir.Add(m.TotalA, net)
		if referrer != "" {
			p.CopyA += net
		}
	case SideB:
		p.B = mimir.Add(p.B, net)
		m.TotalB = mimir.Add(m.TotalB, net)
		if referrer != "" {
			p.CopyB += net
		}
	default:
		panic("BadSide")
	}
	if referrer != "" && p.Referrer == "" {
		p.Referrer = referrer
		emit("ReferrerSet", "id", itoa(m.ID), "user", user.String(), "referrer", referrer.String())
	}
	mine := p.A + p.B
	roles.CheckCaps(mine, m.TotalA+m.TotalB)
	m.history.Record(now(), mimir.Amounts{A: m.TotalA, B: m.TotalB})
	p.history.Record(now(), mimir.Amounts{A: p.A, B: p.B, CopiedA: p.CopyA, CopiedB: p.CopyB})
	emit("Staked", "id", itoa(m.ID), "user", user.String(), "side", itoa(int64(side)), "amount", itoa(net))
}

pool.gno

// Package pool is Mimir's two-sided pool prediction market, settled by an AI
// oracle: the gno.land port of contracts/MimirPoolErc20.sol. Stakes are mUSD
// (gno.land/r/.../musd, 6 decimals).
//
// Model
//   - A market has two sides, A and B (YES / NO). The creator opens it with a
//     stake on one side. Anyone, the creator included, can then stake on either
//     side until LockSeconds before the deadline. Stakes by the same address
//     add up per side.
//   - After the deadline the oracle proposes A, B, DRAW or UNRESOLVABLE. A
//     participant can dispute within the dispute window by posting
//     DisputeBond; the arbiter then rules. The bond comes back if the ruling
//     changes the verdict and goes to the platform otherwise. An undisputed
//     proposal is finalized by anyone.
//   - Escape hatch: ResolutionGraceSeconds after the deadline (or after the
//     proposal or dispute), anyone can refund the market in full. From that
//     moment the oracle and the arbiter can no longer rule.
//   - Fees: every stake pays an entry fee, fees.EntryBps(caller) of the amount
//     (0.5% by default, less with a signed ticket); the rest is staked. The
//     entry fee is kept on refunds. Winnings pay no fee, except copy trades: a
//     stake made with a referrer pays ReferrerFeeBps of its net profit to the
//     referrer and CopyFeeBps to the platform.
//   - Payout: a winner gets their stake back plus a pro-rata share of the
//     losing side, rounded down (dust stays in the realm). If either side is
//     empty, or on DRAW / UNRESOLVABLE, everyone gets their stake back.
//   - Settlement only records the outcome. Each staker is then paid by
//     Claim(id), or by anyone through ClaimFor(id, user).
//   - Roles: owner, arbiter (rules disputes), oracle (may never also be owner,
//     arbiter or fee recipient), fee recipient, and an optional audit agent
//     that may dispute. Ownership, oracle and fee-recipient changes are
//     timelocked; the owner can revoke the oracle at once, veto a proposal to
//     the arbiter, cap stakes, set an early lock and pause.
//   - Pause stops new markets and stakes AND settlement and winners' payouts;
//     refunds are still paid, and RefundExpired while paused refunds instead of
//     honouring a proposal.
//
// Differences from the EVM contract, all from the transport:
//   - Amounts are mUSD units in int64; MinStake, DisputeBond and caps are in
//     those units. The caller approves this realm on mUSD first; Adena sends
//     the approve and the call in one transaction, so there are no *WithPermit
//     variants.
//   - mUSD has no blacklist and no callbacks, so a payout cannot be refused and
//     cannot re-enter: payouts are sent directly (no parked withdrawals, no
//     gas stipend, no reentrancy lock).
//   - Times are block-time unix seconds.
package pool

import (
	"chain"
	"chain/runtime"
	"strconv"
	"time"

	mimir "gno.land/p/g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz/mimir"
	"gno.land/p/nt/avl/v0"
	"gno.land/r/g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz/fees"
	"gno.land/r/g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz/musd"
)

// Market states.
const (
	StOpen     = 0
	StProposed = 1
	StDisputed = 2
	StResolved = 3
)

// Sides and outcomes.
const (
	SideA        = 1
	SideB        = 2
	Draw         = 3
	Unresolvable = 4
)

const (
	// MinStake is the smallest gross stake: 0.1 mUSD.
	MinStake = int64(100_000)
	// DisputeBond is 2 mUSD, independent of the stake minimum so disputes stay costly to spam.
	DisputeBond = int64(2_000_000)
	// No new stakes in the final LockSeconds before the deadline (anti-sniping).
	LockSeconds      = int64(60)
	MaxDeadlineAhead = int64(365 * 24 * 60 * 60)
	// Entry fees above 1% are refused, whatever the fee realm answers.
	MaxEntryBps            = int64(100)
	ReferrerFeeBps         = int64(100)
	CopyFeeBps             = int64(100)
	ResolutionGraceSeconds = int64(7 * 24 * 60 * 60)
	MaxDisputeWindow       = int64(7 * 24 * 60 * 60)
	// On mainnet a proposal stays disputable at least this long.
	MinLiveDisputeWindow = int64(24 * 60 * 60)
	// TestnetDisputeWindow lets a testnet show the whole flow in minutes.
	TestnetDisputeWindow = int64(10 * 60)
)

// Initial roles. The owner can change each one afterwards.
const (
	Deployer       = address("g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz")
	InitialOracle  = address("g18pnec3atge4msr5hhanm790tljtdyd87s0wguh")
	InitialArbiter = address("g1af78r3tuv84mf3cd0kxrssmw6g2v2mvvc6phpv")
)

type Market struct {
	ID            int64
	Creator       address
	Deadline      int64
	CreatedAt     int64
	State         int
	Outcome       int // final, once resolved
	Proposed      int // the oracle's proposal
	ProposedAt    int64
	DisputedAt    int64
	Disputer      address
	Bond          int64
	TotalA        int64
	TotalB        int64
	EvidenceHash  string // hex sha256 of the oracle's evidence
	Question      string
	LabelA        string
	LabelB        string
	ResolutionURL string
	Category      string
	Summary       string
	// 0 includes all deposits; otherwise only deposits strictly before it compete.
	SettlementCutoff int64
	// Optional early close: stakes stop at LockAt instead of LockSeconds before the deadline.
	LockAt    int64
	EntryFees int64

	history   mimir.History // market totals over time
	positions avl.Tree      // address -> *Position
}

type Position struct {
	A, B         int64 // net stakes
	CopyA, CopyB int64 // the copied part of each
	Referrer     address
	Claimed      bool
	history      mimir.History
}

var (
	markets     avl.Tree // padded id -> *Market
	marketCount int64

	accruedFees         avl.Tree // address -> int64
	lifetimeFeesAccrued int64
	lifetimeFeesClaimed int64

	roles         *mimir.Roles
	disputeWindow int64
)

func init(cur realm) {
	roles = mimir.NewRoles(Deployer, InitialArbiter, InitialOracle, Deployer)
	disputeWindow = TestnetDisputeWindow
	if runtime.ChainID() == "gnoland-1" {
		disputeWindow = MinLiveDisputeWindow
	}
}

func now() int64 { return time.Now().Unix() }

func emit(typ string, attrs ...string) { chain.Emit(typ, attrs...) }

func itoa(n int64) string { return strconv.FormatInt(n, 10) }

func key(id int64) string {
	s := itoa(id)
	for len(s) < 12 {
		s = "0" + s
	}
	return s
}

func getMarket(id int64) *Market {
	v := markets.Get(key(id))
	if v == nil {
		panic("NoMarket")
	}
	return v.(*Market)
}

func (m *Market) position(user address) *Position {
	if v := m.positions.Get(user.String()); v != nil {
		return v.(*Position)
	}
	return nil
}

func (m *Market) mustPosition(user address) *Position {
	p := m.position(user)
	if p == nil {
		p = &Position{}
		m.positions.Set(user.String(), p)
	}
	return p
}

func feesOf(a address) int64 {
	if v := accruedFees.Get(a.String()); v != nil {
		return v.(int64)
	}
	return 0
}

func accrue(id int64, to address, amount int64) {
	accruedFees.Set(to.String(), mimir.Add(feesOf(to), amount))
	lifetimeFeesAccrued = mimir.Add(lifetimeFeesAccrued, amount)
	emit("FeeAccrued", "id", itoa(id), "recipient", to.String(), "amount", itoa(amount))
}

// pull moves exactly amount mUSD from the caller into this realm (needs an allowance).
func pull(cur realm, from address, amount int64) {
	musd.TransferFrom(cross(cur), from, cur.Address(), amount)
}

func push(cur realm, to address, amount int64) {
	if amount == 0 {
		return
	}
	musd.Transfer(cross(cur), to, amount)
}

func caller(cur realm) address { return cur.Previous().Address() }

func assertOwner(cur realm) { roles.AssertOwner(caller(cur)) }

func assertNotPaused() { roles.AssertNotPaused() }

func parseReferrer(s string) address { return mimir.ParseOptional(s) }

func entryBps(a address) int64 { return fees.EntryBps(a) }

pool_test.gno

package pool

import (
	"chain"
	"testing"

	mimir "gno.land/p/g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz/mimir"
	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
	"gno.land/r/g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz/musd"
)

const (
	usd   = int64(1_000_000)
	block = int64(5) // seconds per test block
)

var (
	alice  = testutils.TestAddress("alice")
	bob    = testutils.TestAddress("bob")
	carol  = testutils.TestAddress("carol")
	dave   = testutils.TestAddress("dave")
	poolAt = chain.PackageAddress("gno.land/r/g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz/pool")
)

// Each helper sets the acting user in its own frame, then calls.

func fund(cur realm, user address, amount int64) {
	testing.SetRealm(testing.NewUserRealm(musd.Deployer))
	musd.Mint(cross(cur), user, amount)
	testing.SetRealm(testing.NewUserRealm(user))
	musd.Approve(cross(cur), poolAt, musd.Allowance(user, poolAt)+amount)
}

func open(cur realm, user address, side int, amount, closesIn int64) int64 {
	fund(cur, user, amount)
	testing.SetRealm(testing.NewUserRealm(user))
	return CreateMarket(cross(cur), "Will it rain?", "Yes", "No", "https://example.com", "World",
		now()+closesIn, side, "", amount)
}

func stake(cur realm, user address, id int64, side int, amount int64, referrer string) {
	fund(cur, user, amount)
	testing.SetRealm(testing.NewUserRealm(user))
	Stake(cross(cur), id, side, referrer, amount)
}

func asOracle(cur realm, id int64, outcome int, cutoff int64) {
	testing.SetRealm(testing.NewUserRealm(InitialOracle))
	ResolveWithCutoff(cross(cur), id, outcome, "verdict", "", cutoff)
}

func claim(cur realm, user address, id int64) int64 {
	before := musd.BalanceOf(user)
	testing.SetRealm(testing.NewUserRealm(user))
	Claim(cross(cur), id)
	return musd.BalanceOf(user) - before
}

func skip(seconds int64) { testing.SkipHeights(seconds/block + 1) }

func TestStakeFeesAndProRataPayout(cur realm, t *testing.T) {
	id := open(cur, alice, SideA, 100*usd, 3600)
	stake(cur, bob, id, SideB, 50*usd, "")
	a, b := SideTotals(id)
	uassert.Equal(t, int64(99_500_000), a) // 0.5% entry fee
	uassert.Equal(t, int64(49_750_000), b)
	uassert.Equal(t, int64(750_000), AccruedFees(Deployer))

	testing.SetRealm(testing.NewUserRealm(InitialOracle))
	uassert.AbortsContains(t, cur, "NotExpired", func() { Resolve(cross(cur), id, SideA, "x", "") })
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsContains(t, cur, "NotOracle", func() { Resolve(cross(cur), id, SideA, "x", "") })

	skip(3600)
	asOracle(cur, id, SideA, 0)
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "NotResolved", func() { Claim(cross(cur), id) })
	uassert.AbortsContains(t, cur, "WindowOpen", func() { Finalize(cross(cur), id) })

	skip(DisputeWindow())
	Finalize(cross(cur), id)
	uassert.Equal(t, int64(149_250_000), claim(cur, alice, id))
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "AlreadyClaimed", func() { Claim(cross(cur), id) })
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsContains(t, cur, "NothingToClaim", func() { Claim(cross(cur), id) })

	// The fee recipient pulls its entry fees.
	testing.SetRealm(testing.NewUserRealm(Deployer))
	before := musd.BalanceOf(Deployer)
	ClaimFees(cross(cur))
	uassert.Equal(t, int64(750_000), musd.BalanceOf(Deployer)-before)
}

func TestOneSidedAndDrawRefund(cur realm, t *testing.T) {
	id := open(cur, alice, SideA, 10*usd, 3600)
	stake(cur, bob, id, SideA, 10*usd, "")
	skip(3600)
	asOracle(cur, id, SideA, 0)
	skip(DisputeWindow())
	testing.SetRealm(testing.NewUserRealm(carol))
	Finalize(cross(cur), id) // anyone
	uassert.Equal(t, int64(9_950_000), claim(cur, bob, id))

	id = open(cur, alice, SideA, 10*usd, 3600)
	stake(cur, bob, id, SideB, 10*usd, "")
	skip(3600)
	asOracle(cur, id, Draw, 0)
	skip(DisputeWindow())
	testing.SetRealm(testing.NewUserRealm(carol))
	Finalize(cross(cur), id)
	uassert.Equal(t, int64(9_950_000), claim(cur, alice, id))
	uassert.Equal(t, int64(9_950_000), claim(cur, bob, id))
}

func TestDisputeBondReturnedWhenRight(cur realm, t *testing.T) {
	id := open(cur, alice, SideA, 10*usd, 3600)
	stake(cur, bob, id, SideB, 10*usd, "")
	skip(3600)
	asOracle(cur, id, SideA, 0)

	testing.SetRealm(testing.NewUserRealm(carol))
	uassert.AbortsContains(t, cur, "NotParticipant", func() { Dispute(cross(cur), id) })

	fund(cur, bob, DisputeBond)
	testing.SetRealm(testing.NewUserRealm(bob))
	Dispute(cross(cur), id)
	uassert.AbortsContains(t, cur, "NotProposed", func() { Dispute(cross(cur), id) })
	uassert.AbortsContains(t, cur, "NotArbiter", func() { ResolveDispute(cross(cur), id, SideB, "x", "") })

	before := musd.BalanceOf(bob)
	testing.SetRealm(testing.NewUserRealm(InitialArbiter))
	ResolveDispute(cross(cur), id, SideB, "the arbiter disagrees", "")
	uassert.Equal(t, DisputeBond, musd.BalanceOf(bob)-before)
	uassert.Equal(t, int64(19_900_000), claim(cur, bob, id))
}

func TestDisputeBondForfeitedWhenWrong(cur realm, t *testing.T) {
	id := open(cur, alice, SideA, 10*usd, 3600)
	stake(cur, bob, id, SideB, 10*usd, "")
	skip(3600)
	asOracle(cur, id, SideA, 0)
	fund(cur, bob, DisputeBond)
	testing.SetRealm(testing.NewUserRealm(bob))
	Dispute(cross(cur), id)
	feesBefore := AccruedFees(Deployer)
	testing.SetRealm(testing.NewUserRealm(InitialArbiter))
	ResolveDispute(cross(cur), id, SideA, "upheld", "")
	uassert.Equal(t, DisputeBond, AccruedFees(Deployer)-feesBefore)
	uassert.Equal(t, int64(19_900_000), claim(cur, alice, id))
}

func TestSettlementCutoffRefundsLateDeposits(cur realm, t *testing.T) {
	id := open(cur, alice, SideA, 10*usd, 3600)
	stake(cur, bob, id, SideB, 10*usd, "")
	skip(600)
	cutoff := now()
	skip(60)
	stake(cur, carol, id, SideB, 10*usd, "") // after the cutoff
	skip(3600)
	asOracle(cur, id, SideB, cutoff)
	a, b := EligibleTotals(id)
	uassert.Equal(t, int64(9_950_000), a)
	uassert.Equal(t, int64(9_950_000), b)
	skip(DisputeWindow())
	testing.SetRealm(testing.NewUserRealm(dave))
	Finalize(cross(cur), id)
	uassert.Equal(t, int64(19_900_000), claim(cur, bob, id))
	uassert.Equal(t, int64(9_950_000), claim(cur, carol, id)) // principal back
}

func TestRefundExpired(cur realm, t *testing.T) {
	// Never resolved: a full refund after the grace.
	id := open(cur, alice, SideA, 10*usd, 3600)
	stake(cur, bob, id, SideB, 10*usd, "")
	skip(3600)
	testing.SetRealm(testing.NewUserRealm(carol))
	uassert.AbortsContains(t, cur, "GraceNotOver", func() { RefundExpired(cross(cur), id) })
	skip(ResolutionGraceSeconds)
	testing.SetRealm(testing.NewUserRealm(InitialOracle))
	uassert.AbortsContains(t, cur, "GraceOver", func() { Resolve(cross(cur), id, SideA, "late", "") })
	testing.SetRealm(testing.NewUserRealm(carol))
	RefundExpired(cross(cur), id)
	uassert.Equal(t, int64(9_950_000), claim(cur, alice, id))

	// An unruled dispute settles to the proposal; the bond is forfeited.
	id = open(cur, alice, SideA, 10*usd, 3600)
	stake(cur, bob, id, SideB, 10*usd, "")
	skip(3600)
	asOracle(cur, id, SideA, 0)
	fund(cur, bob, DisputeBond)
	testing.SetRealm(testing.NewUserRealm(bob))
	Dispute(cross(cur), id)
	skip(ResolutionGraceSeconds)
	testing.SetRealm(testing.NewUserRealm(carol))
	RefundExpired(cross(cur), id)
	uassert.Equal(t, int64(19_900_000), claim(cur, alice, id))
}

func TestVetoRefundsIfUnruled(cur realm, t *testing.T) {
	id := open(cur, alice, SideA, 10*usd, 3600)
	stake(cur, bob, id, SideB, 10*usd, "")
	skip(3600)
	asOracle(cur, id, SideA, 0)
	testing.SetRealm(testing.NewUserRealm(Deployer))
	VetoProposal(cross(cur), id)
	skip(ResolutionGraceSeconds)
	testing.SetRealm(testing.NewUserRealm(carol))
	RefundExpired(cross(cur), id)
	uassert.Equal(t, int64(9_950_000), claim(cur, bob, id))
}

func TestPauseHoldsWinnersNotRefunds(cur realm, t *testing.T) {
	id := open(cur, alice, SideA, 10*usd, 3600)
	stake(cur, bob, id, SideB, 10*usd, "")
	skip(3600)
	asOracle(cur, id, SideA, 0)
	skip(DisputeWindow())
	testing.SetRealm(testing.NewUserRealm(carol))
	Finalize(cross(cur), id)

	testing.SetRealm(testing.NewUserRealm(Deployer))
	SetPaused(cross(cur), true)
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "IsPaused", func() { Claim(cross(cur), id) })
	uassert.AbortsContains(t, cur, "IsPaused", func() {
		CreateMarket(cross(cur), "q", "a", "b", "", "", now()+3600, SideA, "", MinStake)
	})
	testing.SetRealm(testing.NewUserRealm(Deployer))
	SetPaused(cross(cur), false)
	uassert.Equal(t, int64(19_900_000), claim(cur, alice, id))
}

func TestCopyTradeFees(cur realm, t *testing.T) {
	id := open(cur, alice, SideB, 100*usd, 3600)
	stake(cur, bob, id, SideA, 100*usd, dave.String()) // bob copies dave
	skip(3600)
	asOracle(cur, id, SideA, 0)
	skip(DisputeWindow())
	testing.SetRealm(testing.NewUserRealm(carol))
	Finalize(cross(cur), id)
	refBefore := AccruedFees(dave)
	// Profit 99.5; 1% to dave, 1% to the platform.
	uassert.Equal(t, int64(199_000_000-1_990_000), claim(cur, bob, id))
	uassert.Equal(t, int64(995_000), AccruedFees(dave)-refBefore)
}

func TestLimits(cur realm, t *testing.T) {
	fund(cur, alice, 10*usd)
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "StakeTooSmall", func() {
		CreateMarket(cross(cur), "q", "a", "b", "", "", now()+3600, SideA, "", MinStake-1)
	})
	uassert.AbortsContains(t, cur, "BadDeadline", func() {
		CreateMarket(cross(cur), "q", "a", "b", "", "", now()+30, SideA, "", MinStake)
	})
	uassert.AbortsContains(t, cur, "EmptyQuestion", func() {
		CreateMarket(cross(cur), "", "a", "b", "", "", now()+3600, SideA, "", MinStake)
	})
	uassert.AbortsContains(t, cur, "BadSide", func() {
		CreateMarket(cross(cur), "q", "a", "b", "", "", now()+3600, 3, "", MinStake)
	})

	// Betting closes LockSeconds before the deadline, or at an earlier lock.
	id := open(cur, alice, SideA, usd, 600)
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsContains(t, cur, "BadLock", func() { SetLockAt(cross(cur), id, now()+100) })
	testing.SetRealm(testing.NewUserRealm(alice))
	SetLockAt(cross(cur), id, now()+100)
	uassert.AbortsContains(t, cur, "BadLock", func() { SetLockAt(cross(cur), id, now()+200) })
	skip(100)
	fund(cur, bob, usd)
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsContains(t, cur, "BettingClosed", func() { Stake(cross(cur), id, SideB, "", usd) })

	// Caps gate new stakes only.
	testing.SetRealm(testing.NewUserRealm(Deployer))
	SetCaps(cross(cur), 0, 5*usd)
	id = open(cur, alice, SideA, usd, 3600)
	fund(cur, bob, 10*usd)
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsContains(t, cur, "CapExceeded", func() { Stake(cross(cur), id, SideB, "", 10*usd) })
	testing.SetRealm(testing.NewUserRealm(Deployer))
	SetCaps(cross(cur), 0, 0)
}

func TestRolesAndTimelocks(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsContains(t, cur, "NotOwner", func() { SetPaused(cross(cur), true) })

	testing.SetRealm(testing.NewUserRealm(Deployer))
	uassert.AbortsContains(t, cur, "RoleCollision", func() { QueueOracle(cross(cur), InitialArbiter) })
	uassert.AbortsContains(t, cur, "RoleCollision", func() { SetArbiter(cross(cur), InitialOracle) })
	SetAuditAgent(cross(cur), carol.String())
	uassert.AbortsContains(t, cur, "RoleCollision", func() { SetArbiter(cross(cur), carol) })

	QueueOracle(cross(cur), dave)
	uassert.AbortsContains(t, cur, "Timelocked", func() { ExecuteOracle(cross(cur)) })
	RevokeOracle(cross(cur))
	uassert.Equal(t, address(""), Oracle())
	skip(mimir.TimelockSeconds)
	testing.SetRealm(testing.NewUserRealm(bob))
	ExecuteOracle(cross(cur)) // permissionless once due
	uassert.Equal(t, dave, Oracle())

	// Restore the oracle for later tests.
	testing.SetRealm(testing.NewUserRealm(Deployer))
	QueueOracle(cross(cur), InitialOracle)
	skip(mimir.TimelockSeconds)
	ExecuteOracle(cross(cur))
	SetAuditAgent(cross(cur), "")
}

func TestViews(cur realm, t *testing.T) {
	id := open(cur, alice, SideA, 2*usd, 3600)
	uassert.True(t, len(MarketJSON(id)) > 0)
	uassert.True(t, len(MarketsJSON(0, 5)) > 2)
	uassert.True(t, len(PositionJSON(id, alice)) > 0)
	uassert.True(t, len(ConfigJSON()) > 0)
	uassert.True(t, len(Render("")) > 0)
	uassert.True(t, len(Render("1")) > 0)
}

render.gno

package pool

import (
	"strconv"
	"strings"
	"time"

	mimir "gno.land/p/g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz/mimir"
	"gno.land/p/nt/ufmt/v0"
)

var stateNames = []string{"Open", "Proposed", "Disputed", "Resolved"}

func outcomeName(m *Market, o int) string {
	switch o {
	case SideA:
		return mimir.Escape(m.LabelA)
	case SideB:
		return mimir.Escape(m.LabelB)
	case Draw:
		return "Draw (refund)"
	case Unresolvable:
		return "Unresolvable (refund)"
	}
	return "-"
}

func pct(a, b int64) int64 {
	if a+b == 0 {
		return 50
	}
	return mimir.MulDiv(a, 100, a+b)
}

func when(unix int64) string {
	return time.Unix(unix, 0).UTC().Format("2006-01-02 15:04 UTC")
}

func Render(path string) string {
	if path == "" {
		return renderHome()
	}
	id, err := strconv.ParseInt(path, 10, 64)
	if err != nil || id < 1 || id > marketCount {
		return "# Not found\n\n[All markets](:)\n"
	}
	return renderMarket(getMarket(id))
}

func renderHome() string {
	var b strings.Builder
	b.WriteString("# Mimir pools\n\n")
	b.WriteString("Claim markets that settle themselves. Stake mUSD on either side of a question; ")
	b.WriteString("an AI oracle proposes the result after the deadline, anyone in the market can dispute it, ")
	b.WriteString("and draws or unclear questions refund everyone.\n\n")
	b.WriteString(ufmt.Sprintf("%d markets · minimum stake %s mUSD · dispute bond %s mUSD · dispute window %d min\n\n",
		marketCount, mimir.FormatUSD(MinStake), mimir.FormatUSD(DisputeBond), disputeWindow/60))
	if marketCount == 0 {
		b.WriteString("No markets yet.\n")
		return b.String()
	}
	b.WriteString("| # | Question | Sides | Pool (mUSD) | State | Closes |\n|---|---|---|---|---|---|\n")
	markets.ReverseIterateByOffset(0, 50, func(_ string, v any) bool {
		m := v.(*Market)
		b.WriteString(ufmt.Sprintf("| [%d](:%d) | %s | %s %d%% · %s %d%% | %s | %s | %s |\n",
			m.ID, m.ID, mimir.Escape(m.Question),
			mimir.Escape(m.LabelA), pct(m.TotalA, m.TotalB), mimir.Escape(m.LabelB), pct(m.TotalB, m.TotalA),
			mimir.FormatUSD(m.TotalA+m.TotalB), stateNames[m.State], when(m.Deadline)))
		return false
	})
	return b.String()
}

func renderMarket(m *Market) string {
	var b strings.Builder
	b.WriteString(ufmt.Sprintf("# %s\n\n", mimir.Escape(m.Question)))
	b.WriteString(ufmt.Sprintf("Market #%d · %s · %s\n\n", m.ID, mimir.Escape(m.Category), stateNames[m.State]))
	b.WriteString(ufmt.Sprintf("| Side | Pool (mUSD) | Implied |\n|---|---|---|\n| A: %s | %s | %d%% |\n| B: %s | %s | %d%% |\n\n",
		mimir.Escape(m.LabelA), mimir.FormatUSD(m.TotalA), pct(m.TotalA, m.TotalB),
		mimir.Escape(m.LabelB), mimir.FormatUSD(m.TotalB), pct(m.TotalB, m.TotalA)))
	b.WriteString(ufmt.Sprintf("- Closes: %s\n- Source: %s\n- Creator: %s\n- Participants: %d\n",
		when(m.Deadline), mimir.Escape(m.ResolutionURL), m.Creator.String(), m.positions.Size()))
	if m.LockAt != 0 {
		b.WriteString(ufmt.Sprintf("- Staking locks early: %s\n", when(m.LockAt)))
	}
	switch m.State {
	case StProposed:
		b.WriteString(ufmt.Sprintf("\n## Proposed: %s\n\nDisputable until %s.\n\n> %s\n\nEvidence: %s\n",
			outcomeName(m, m.Proposed), when(m.ProposedAt+disputeWindow), mimir.Escape(m.Summary), hashOrNone(m.EvidenceHash)))
	case StDisputed:
		b.WriteString(ufmt.Sprintf("\n## Disputed\n\nThe oracle proposed %s; the arbiter rules.\n\n> %s\n",
			outcomeName(m, m.Proposed), mimir.Escape(m.Summary)))
	case StResolved:
		b.WriteString(ufmt.Sprintf("\n## Result: %s\n\n> %s\n\nEvidence: %s\n",
			outcomeName(m, m.Outcome), mimir.Escape(m.Summary), hashOrNone(m.EvidenceHash)))
	}
	b.WriteString("\n## Act\n\n")
	b.WriteString("Approve this realm on mUSD first, then call:\n\n")
	b.WriteString(ufmt.Sprintf("- [Stake](%s) · [Claim](%s) · [Finalize](%s) · [Dispute](%s)\n\n[All markets](:)\n",
		helpLink("Stake", m.ID), helpLink("Claim", m.ID), helpLink("Finalize", m.ID), helpLink("Dispute", m.ID)))
	return b.String()
}

func helpLink(fn string, id int64) string {
	return ufmt.Sprintf("$help&func=%s&id=%d", fn, id)
}

func hashOrNone(h string) string {
	if h == "" {
		return "none"
	}
	return "`" + h + "`"
}

settle.gno

package pool

func validOutcome(outcome int) {
	if outcome < SideA || outcome > Unresolvable {
		panic("BadSide")
	}
}

func validHash(h string) {
	if h == "" {
		return
	}
	if len(h) != 64 {
		panic("BadEvidenceHash")
	}
	for _, c := range h {
		if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
			panic("BadEvidenceHash")
		}
	}
}

// refundAt is when RefundExpired opens: grace from the latest deadline, proposal or dispute.
func refundAt(m *Market) int64 {
	start := m.Deadline
	if m.ProposedAt > start {
		start = m.ProposedAt
	}
	if m.DisputedAt > start {
		start = m.DisputedAt
	}
	return start + ResolutionGraceSeconds
}

func setCutoff(m *Market, cutoff int64) {
	if cutoff > now() || cutoff < 0 {
		panic("BadCutoff")
	}
	m.SettlementCutoff = cutoff
	emit("SettlementCutoffSet", "id", itoa(m.ID), "cutoff", itoa(cutoff))
}

// Resolve is the oracle's verdict: final at once with no dispute window, else a proposal.
func Resolve(cur realm, id int64, outcome int, summary, evidenceHash string) {
	resolve(cur, id, outcome, summary, evidenceHash, 0)
}

// ResolveWithCutoff also sets the settlement cutoff: only deposits strictly
// before it compete; later ones get their net principal back.
func ResolveWithCutoff(cur realm, id int64, outcome int, summary, evidenceHash string, cutoff int64) {
	resolve(cur, id, outcome, summary, evidenceHash, cutoff)
}

func resolve(cur realm, id int64, outcome int, summary, evidenceHash string, cutoff int64) {
	assertNotPaused()
	roles.AssertOracle(caller(cur))
	m := getMarket(id)
	if m.State != StOpen {
		panic("NotOpen")
	}
	if now() < m.Deadline {
		panic("NotExpired")
	}
	if now() >= refundAt(m) {
		panic("GraceOver")
	}
	validOutcome(outcome)
	validHash(evidenceHash)
	setCutoff(m, cutoff)
	if disputeWindow == 0 {
		settle(m, outcome, summary, evidenceHash)
		return
	}
	m.State = StProposed
	m.Proposed = outcome
	m.ProposedAt = now()
	m.EvidenceHash = evidenceHash
	m.Summary = summary
	emit("ResolutionProposed", "id", itoa(id), "outcome", itoa(int64(outcome)),
		"evidenceHash", evidenceHash, "disputableUntil", itoa(now()+disputeWindow))
}

// Dispute escalates the proposal to the arbiter, pulling DisputeBond mUSD.
// Open to the market's participants, the audit agent and the arbiter.
func Dispute(cur realm, id int64) {
	m := getMarket(id)
	if m.State != StProposed {
		panic("NotProposed")
	}
	if now() >= m.ProposedAt+disputeWindow {
		panic("WindowClosed")
	}
	c := caller(cur)
	p := m.position(c)
	staked := p != nil && (p.A != 0 || p.B != 0)
	if !staked && (roles.AuditAgent == "" || c != roles.AuditAgent) && c != roles.Arbiter {
		panic("NotParticipant")
	}
	pull(cur, c, DisputeBond)
	m.State = StDisputed
	m.Disputer = c
	m.DisputedAt = now()
	m.Bond = DisputeBond
	emit("ResolutionDisputed", "id", itoa(id), "disputer", c.String(), "bond", itoa(DisputeBond))
}

// VetoProposal lets the owner send a proposal it believes wrong to the
// arbiter, inside the window. No bond; if the arbiter never rules,
// RefundExpired refunds every stake rather than honouring the vetoed proposal.
func VetoProposal(cur realm, id int64) {
	assertOwner(cur)
	m := getMarket(id)
	if m.State != StProposed {
		panic("NotProposed")
	}
	if now() >= m.ProposedAt+disputeWindow {
		panic("WindowClosed")
	}
	m.State = StDisputed
	m.DisputedAt = now()
	emit("ResolutionDisputed", "id", itoa(id), "disputer", "", "bond", "0")
}

// Finalize settles an undisputed proposal once the window has closed. Anyone may call it.
func Finalize(cur realm, id int64) {
	assertNotPaused()
	m := getMarket(id)
	if m.State != StProposed {
		panic("NotProposed")
	}
	if now() < m.ProposedAt+disputeWindow {
		panic("WindowOpen")
	}
	settle(m, m.Proposed, m.Summary, m.EvidenceHash)
}

// ResolveDispute is the arbiter's final word on a disputed market.
func ResolveDispute(cur realm, id int64, outcome int, summary, evidenceHash string) {
	m := getMarket(id)
	resolveDispute(cur, m, outcome, summary, evidenceHash, m.SettlementCutoff)
}

func ResolveDisputeWithCutoff(cur realm, id int64, outcome int, summary, evidenceHash string, cutoff int64) {
	resolveDispute(cur, getMarket(id), outcome, summary, evidenceHash, cutoff)
}

func resolveDispute(cur realm, m *Market, outcome int, summary, evidenceHash string, cutoff int64) {
	assertNotPaused()
	roles.AssertArbiter(caller(cur))
	if m.State != StDisputed {
		panic("NotDisputed")
	}
	if now() >= refundAt(m) {
		panic("GraceOver")
	}
	validOutcome(outcome)
	validHash(evidenceHash)
	disputerRight := outcome != m.Proposed || cutoff != m.SettlementCutoff
	setCutoff(m, cutoff)
	emit("DisputeResolved", "id", itoa(m.ID), "outcome", itoa(int64(outcome)), "disputerRight", boolStr(disputerRight))
	// Settled before the bond moves.
	settle(m, outcome, summary, evidenceHash)
	settleBond(cur, m, disputerRight)
}

// RefundExpired is the escape hatch, open to anyone once the grace has passed.
// A market the oracle never resolved is refunded in full; a dispute the
// arbiter never ruled on settles to the oracle's proposal and the bond is
// forfeited, so a cheap dispute cannot turn a loss into a free refund. A
// vetoed proposal, or any proposal while paused, refunds instead.
func RefundExpired(cur realm, id int64) {
	m := getMarket(id)
	disputed := m.State == StDisputed
	if !disputed && m.State != StOpen && !(roles.Paused && m.State == StProposed) {
		panic("NotOpen")
	}
	if now() < refundAt(m) {
		panic("GraceNotOver")
	}
	switch {
	case disputed && !roles.Paused && m.Disputer != "":
		emit("DisputeResolved", "id", itoa(id), "outcome", itoa(int64(m.Proposed)), "disputerRight", "false")
		settle(m, m.Proposed, m.Summary, m.EvidenceHash)
		settleBond(cur, m, false)
	case disputed:
		emit("DisputeResolved", "id", itoa(id), "outcome", itoa(Unresolvable), "disputerRight", "true")
		settle(m, Unresolvable, "Refunded: vetoed or paused", "")
		settleBond(cur, m, true)
	default:
		emit("MarketExpiredRefund", "id", itoa(id), "caller", caller(cur).String())
		settle(m, Unresolvable, "Refunded: not resolved within the grace period", "")
	}
}

func settle(m *Market, outcome int, summary, evidenceHash string) {
	m.State = StResolved
	m.Outcome = outcome
	m.Summary = summary
	m.EvidenceHash = evidenceHash
	emit("MarketResolved", "id", itoa(m.ID), "outcome", itoa(int64(outcome)), "summary", summary, "evidenceHash", evidenceHash)
}

func settleBond(cur realm, m *Market, returnIt bool) {
	bond := m.Bond
	if bond == 0 {
		return
	}
	m.Bond = 0
	if returnIt {
		push(cur, m.Disputer, bond)
	} else {
		accrue(m.ID, roles.FeeRecipient, bond)
	}
}

func boolStr(b bool) string {
	if b {
		return "true"
	}
	return "false"
}

views.gno

package pool

import (
	"strings"

	mimir "gno.land/p/g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz/mimir"
)

func MarketCount() int64          { return marketCount }
func Owner() address              { return roles.Owner }
func Arbiter() address            { return roles.Arbiter }
func Oracle() address             { return roles.Oracle }
func AuditAgent() address         { return roles.AuditAgent }
func FeeRecipient() address       { return roles.FeeRecipient }
func Paused() bool                { return roles.Paused }
func DisputeWindow() int64        { return disputeWindow }
func AccruedFees(a address) int64 { return feesOf(a) }

// SideTotals are the pool sizes: the implied probability of A is totalA / (totalA + totalB).
func SideTotals(id int64) (int64, int64) {
	m := getMarket(id)
	return m.TotalA, m.TotalB
}

func StakeOf(id int64, user address) (int64, int64) {
	p := getMarket(id).position(user)
	if p == nil {
		return 0, 0
	}
	return p.A, p.B
}

// EligibleTotals are the side totals that compete under the settlement cutoff.
func EligibleTotals(id int64) (int64, int64) {
	m := getMarket(id)
	t := m.history.Before(m.SettlementCutoff)
	return t.A, t.B
}

// Claimable is what ClaimFor would pay `user` now (net) and the copy fees it
// would take. 0 if unresolved, already claimed or nothing owed.
func Claimable(id int64, user address) (payout, fee int64) {
	m := getMarket(id)
	p := m.position(user)
	if m.State != StResolved || p == nil || p.Claimed {
		return 0, 0
	}
	gross, feeBase := owed(m, p)
	toRef, toPlatform := copyFees(user, p, feeBase)
	fee = toRef + toPlatform
	return gross - fee, fee
}

func ConfigJSON() string {
	return "{" + strings.Join([]string{
		kv("owner", mimir.Quote(roles.Owner.String())),
		kv("arbiter", mimir.Quote(roles.Arbiter.String())),
		kv("oracle", mimir.Quote(roles.Oracle.String())),
		kv("auditAgent", mimir.Quote(roles.AuditAgent.String())),
		kv("feeRecipient", mimir.Quote(roles.FeeRecipient.String())),
		kv("paused", boolStr(roles.Paused)),
		kv("disputeWindow", itoa(disputeWindow)),
		kv("minStake", itoa(MinStake)),
		kv("disputeBond", itoa(DisputeBond)),
		kv("lockSeconds", itoa(LockSeconds)),
		kv("graceSeconds", itoa(ResolutionGraceSeconds)),
		kv("maxMarketStake", itoa(roles.MaxMarketStake)),
		kv("maxAccountStake", itoa(roles.MaxAccountStake)),
		kv("marketCount", itoa(marketCount)),
		kv("lifetimeFeesAccrued", itoa(lifetimeFeesAccrued)),
		kv("lifetimeFeesClaimed", itoa(lifetimeFeesClaimed)),
		kv("now", itoa(now())),
	}, ",") + "}"
}

func MarketJSON(id int64) string { return marketJSON(getMarket(id)) }

// MarketsJSON lists markets newest first: `offset` skips that many from the newest.
func MarketsJSON(offset, limit int) string {
	if limit <= 0 || limit > 100 {
		limit = 100
	}
	if offset < 0 {
		offset = 0
	}
	var out []string
	markets.ReverseIterateByOffset(offset, limit, func(_ string, v any) bool {
		out = append(out, marketJSON(v.(*Market)))
		return false
	})
	return "[" + strings.Join(out, ",") + "]"
}

// PositionJSON is one user's stake, claim state and claimable amount in a market.
func PositionJSON(id int64, user address) string {
	m := getMarket(id)
	p := m.position(user)
	if p == nil {
		p = &Position{}
	}
	payout, fee := Claimable(id, user)
	return "{" + strings.Join([]string{
		kv("a", itoa(p.A)), kv("b", itoa(p.B)),
		kv("copyA", itoa(p.CopyA)), kv("copyB", itoa(p.CopyB)),
		kv("referrer", mimir.Quote(p.Referrer.String())),
		kv("claimed", boolStr(p.Claimed)),
		kv("claimable", itoa(payout)), kv("claimFee", itoa(fee)),
	}, ",") + "}"
}

func marketJSON(m *Market) string {
	ea, eb := EligibleTotals(m.ID)
	return "{" + strings.Join([]string{
		kv("id", itoa(m.ID)),
		kv("creator", mimir.Quote(m.Creator.String())),
		kv("deadline", itoa(m.Deadline)),
		kv("createdAt", itoa(m.CreatedAt)),
		kv("state", itoa(int64(m.State))),
		kv("outcome", itoa(int64(m.Outcome))),
		kv("proposed", itoa(int64(m.Proposed))),
		kv("proposedAt", itoa(m.ProposedAt)),
		kv("disputedAt", itoa(m.DisputedAt)),
		kv("disputer", mimir.Quote(m.Disputer.String())),
		kv("bond", itoa(m.Bond)),
		kv("totalA", itoa(m.TotalA)),
		kv("totalB", itoa(m.TotalB)),
		kv("eligibleA", itoa(ea)),
		kv("eligibleB", itoa(eb)),
		kv("entryFees", itoa(m.EntryFees)),
		kv("settlementCutoff", itoa(m.SettlementCutoff)),
		kv("lockAt", itoa(m.LockAt)),
		kv("participants", itoa(int64(m.positions.Size()))),
		kv("evidenceHash", mimir.Quote(m.EvidenceHash)),
		kv("question", mimir.Quote(m.Question)),
		kv("labelA", mimir.Quote(m.LabelA)),
		kv("labelB", mimir.Quote(m.LabelB)),
		kv("resolutionUrl", mimir.Quote(m.ResolutionURL)),
		kv("category", mimir.Quote(m.Category)),
		kv("summary", mimir.Quote(m.Summary)),
	}, ",") + "}"
}

func kv(k, v string) string { return mimir.Quote(k) + ":" + v }