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 vs

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) }
func SetCaps(cur realm, market, account int64)  { roles.SetCaps(caller(cur), market, account) }

// 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))
}

// 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("ZeroRecipient")
	}
	claimFeesTo(cur, to)
}

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

create.gno

package vs

import (
	"strings"

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

type createArgs struct {
	question, creatorPosition, counterPosition, resolutionURL string
	deadline, stakeAmount                                     int64
	category                                                  string
	parentID                                                  int64
	marketType, oddsMode                                      string
	challengerPayoutBps                                       int64
	handicapLine, settlementRule                              string
	maxChallengers                                            int
	isPrivate                                                 bool
	referrer                                                  address
}

// CreateClaim opens a claim with `stakeAmount` mUSD (less the entry fee) on
// the creator's position. oddsMode is "pool" or "fixed"; challengerPayoutBps
// applies to fixed odds (below 10000 means the 2x default). maxChallengers 0
// means the maximum. referrer is the copied basket's creator, or "".
func CreateClaim(cur realm,
	question, creatorPosition, counterPosition, resolutionURL string,
	deadline, stakeAmount int64,
	category string, parentID int64,
	marketType, oddsMode string, challengerPayoutBps int64,
	handicapLine, settlementRule string, maxChallengers int,
	isPrivate bool, referrer string) int64 {
	roles.AssertNotPaused()
	return createClaim(cur, createArgs{
		question, creatorPosition, counterPosition, resolutionURL,
		deadline, stakeAmount, category, parentID, marketType, oddsMode,
		challengerPayoutBps, handicapLine, settlementRule, maxChallengers,
		isPrivate, mimir.ParseOptional(referrer),
	})
}

// CreateRematch opens a new claim inheriting its terms from a parent. The
// caller is the creator and pays the stake. The parent's referrer carries over
// only to the parent's own creator.
func CreateRematch(cur realm, parentID, deadline, stakeAmount int64) int64 {
	roles.AssertNotPaused()
	p := getClaim(parentID)
	ref := address("")
	if caller(cur) == p.Creator {
		ref = p.Referrer
	}
	return createClaim(cur, createArgs{
		p.Question, p.CreatorPosition, p.CounterPosition, p.ResolutionURL,
		deadline, stakeAmount, p.Category, parentID, p.MarketType, p.OddsMode,
		p.ChallengerPayoutBps, p.HandicapLine, p.SettlementRule, p.MaxChallengers,
		p.IsPrivate, ref,
	})
}

func createClaim(cur realm, a createArgs) int64 {
	if a.stakeAmount < MinStake {
		panic("StakeTooSmall")
	}
	if a.deadline <= now() {
		panic("DeadlineInPast")
	}
	if a.deadline > now()+MaxDeadlineAhead {
		panic("DeadlineTooFar")
	}
	if a.question == "" {
		panic("EmptyQuestion")
	}
	isFixed := a.oddsMode == "fixed"
	payoutBps := int64(0)
	if isFixed {
		payoutBps = DefaultPayoutBps
		if a.challengerPayoutBps >= 10_000 {
			payoutBps = a.challengerPayoutBps
		}
	}
	if payoutBps > MaxPayoutBps {
		panic("PayoutTooHigh")
	}
	maxCh := a.maxChallengers
	if maxCh <= 0 || maxCh > MaxChallengers {
		maxCh = MaxChallengers
	}
	claimCount++
	c := &Claim{
		ID: claimCount, Creator: caller(cur), Question: a.question,
		CreatorPosition: a.creatorPosition, CounterPosition: a.counterPosition,
		ResolutionURL: a.resolutionURL, Deadline: a.deadline, Category: orDefault(a.category, "custom"),
		ParentID: a.parentID, CreatedAt: now(), MarketType: orDefault(a.marketType, "binary"),
		OddsMode: "pool", ChallengerPayoutBps: payoutBps, HandicapLine: a.handicapLine,
		SettlementRule: a.settlementRule, MaxChallengers: maxCh, IsPrivate: a.isPrivate,
		Referrer: a.referrer,
	}
	if isFixed {
		c.OddsMode = "fixed"
	}
	net := takeEntry(cur, c, c.Creator, a.stakeAmount)
	roles.CheckCaps(net, net)
	c.CreatorStake = net
	claims.Set(key(c.ID), c)
	if a.referrer != "" {
		emit("ReferrerSet", "id", itoa(c.ID), "user", c.Creator.String(), "referrer", a.referrer.String())
	}
	emit("ClaimCreated", "id", itoa(c.ID), "creator", c.Creator.String(), "category", c.Category)
	return c.ID
}

func orDefault(s, d string) string {
	if s == "" {
		return d
	}
	return s
}

// SetInvited grants or revokes wallets on a private claim, up to
// MaxChallengers per call, as a comma-separated list. Revocation only blocks
// future entry. Rematches have their own empty list.
func SetInvited(cur realm, claimID int64, accounts string, allowed bool) {
	c := getClaim(claimID)
	list := strings.Split(accounts, ",")
	if caller(cur) != c.Creator || !c.IsPrivate || c.State > StActive || len(list) > MaxChallengers {
		panic("BadInvite")
	}
	for _, s := range list {
		a := address(strings.TrimSpace(s))
		if !a.IsValid() || a == c.Creator {
			panic("BadInvite")
		}
		c.invited.Set(a.String(), allowed)
		emit("InviteUpdated", "id", itoa(claimID), "account", a.String(), "allowed", boolStr(allowed))
	}
}

// ChallengeClaim takes the counter position with `stakeAmount` mUSD (less the entry fee).
func ChallengeClaim(cur realm, claimID, stakeAmount int64, referrer string) {
	roles.AssertNotPaused()
	c := getClaim(claimID)
	user := caller(cur)
	ref := mimir.ParseOptional(referrer)
	checkChallenge(c, user, stakeAmount)
	net := takeEntry(cur, c, user, stakeAmount)
	roles.CheckCaps(net, c.CreatorStake+c.TotalChallengerStake+net)
	if c.OddsMode == "fixed" {
		// The creator's unreserved stake must cover this challenger's profit.
		gross := grossPayout(net, c.ChallengerPayoutBps)
		profit := int64(0)
		if gross > net {
			profit = gross - net
		}
		if c.CreatorStake-c.ReservedCreatorLiability < profit {
			panic("CreatorHasInsufficientLiquidity")
		}
		c.ReservedCreatorLiability += profit
	} else if c.TotalChallengerStake+net > c.CreatorStake*MaxPoolMultiple {
		panic("PoolFull")
	}
	c.challengers = append(c.challengers, &Challenger{Addr: user, Stake: net, At: now(), Referrer: ref})
	c.joined.Set(user.String(), true)
	if ref != "" {
		emit("ReferrerSet", "id", itoa(claimID), "user", user.String(), "referrer", ref.String())
	}
	c.TotalChallengerStake += net
	c.State = StActive
	emit("ClaimChallenged", "id", itoa(claimID), "challenger", user.String(), "stake", itoa(net))
}

func checkChallenge(c *Claim, user address, stakeAmount int64) {
	if c.State != StOpen && c.State != StActive {
		panic("NotOpen")
	}
	if user == c.Creator {
		panic("SelfChallenge")
	}
	if c.hasJoined(user) {
		panic("AlreadyChallenged")
	}
	if len(c.challengers) >= c.MaxChallengers {
		panic("Full")
	}
	if stakeAmount < MinStake {
		panic("StakeTooSmall")
	}
	if now()+ChallengeLockSeconds > c.Deadline {
		panic("ChallengeWindowClosed")
	}
	if c.LockAt != 0 && now() >= c.LockAt {
		panic("Locked")
	}
	// Authorize the caller's wallet before calling the fee realm or pulling mUSD.
	if c.IsPrivate && !c.isInvited(user) {
		panic("NotInvited")
	}
}

// SetLockAt closes a claim to new challengers early, by its creator or the
// owner. Only ever earlier.
func SetLockAt(cur realm, claimID, at int64) {
	c := getClaim(claimID)
	u := caller(cur)
	if u != c.Creator && u != roles.Owner {
		panic("BadLock")
	}
	if c.State > StActive || at < now() || at+ChallengeLockSeconds > c.Deadline {
		panic("BadLock")
	}
	if c.LockAt != 0 && at > c.LockAt {
		panic("BadLock")
	}
	c.LockAt = at
	emit("LockSet", "id", itoa(claimID), "lockAt", itoa(at))
}

// CancelClaim refunds the creator of a claim nobody has challenged yet.
func CancelClaim(cur realm, claimID int64) {
	c := getClaim(claimID)
	if caller(cur) != c.Creator {
		panic("NotCreator")
	}
	if c.State != StOpen {
		panic("NotOpen")
	}
	c.State = StCancelled
	push(cur, c.Creator, c.CreatorStake)
	emit("ClaimCancelled", "id", itoa(claimID), "refunded", itoa(c.CreatorStake))
}

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

gnomod.toml

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

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

render.gno

package vs

import (
	"strconv"
	"strings"
	"time"

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

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

func sideName(c *Claim, s int) string {
	switch s {
	case SideCreator:
		return "Creator: " + mimir.Escape(c.CreatorPosition)
	case SideChallengers:
		return "Challengers: " + mimir.Escape(c.CounterPosition)
	case SideDraw:
		return "Draw (refund)"
	case SideUnresolvable:
		return "Unresolvable (refund)"
	}
	return "-"
}

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 > claimCount {
		return "# Not found\n\n[All duels](:)\n"
	}
	return renderClaim(getClaim(id))
}

func renderHome() string {
	var b strings.Builder
	b.WriteString("# Mimir VS\n\n")
	b.WriteString("Personal duels. A creator stakes mUSD on a position; challengers take the other side. ")
	b.WriteString("An AI oracle proposes the result after the deadline and pays everyone in one transaction.\n\n")
	b.WriteString(ufmt.Sprintf("%d duels · %d resolved · minimum stake %s mUSD · dispute bond %s mUSD\n\n",
		claimCount, totalResolved, mimir.FormatUSD(MinStake), mimir.FormatUSD(DisputeBond)))
	if claimCount == 0 {
		b.WriteString("No duels yet.\n")
		return b.String()
	}
	b.WriteString("| # | Question | Creator stake | Challengers | Odds | State | Closes |\n|---|---|---|---|---|---|---|\n")
	claims.ReverseIterateByOffset(0, 50, func(_ string, v any) bool {
		c := v.(*Claim)
		b.WriteString(ufmt.Sprintf("| [%d](:%d) | %s | %s | %d · %s | %s | %s | %s |\n",
			c.ID, c.ID, mimir.Escape(c.Question), mimir.FormatUSD(c.CreatorStake),
			len(c.challengers), mimir.FormatUSD(c.TotalChallengerStake), c.OddsMode,
			stateNames[c.State], when(c.Deadline)))
		return false
	})
	return b.String()
}

func renderClaim(c *Claim) string {
	var b strings.Builder
	b.WriteString(ufmt.Sprintf("# %s\n\n", mimir.Escape(c.Question)))
	b.WriteString(ufmt.Sprintf("Duel #%d · %s · %s · %s odds", c.ID, mimir.Escape(c.Category), stateNames[c.State], c.OddsMode))
	if c.OddsMode == "fixed" {
		b.WriteString(ufmt.Sprintf(" (pays %s)", bpsX(c.ChallengerPayoutBps)))
	}
	if c.IsPrivate {
		b.WriteString(" · private")
	}
	b.WriteString("\n\n")
	b.WriteString(ufmt.Sprintf("| Side | Position | Stake (mUSD) |\n|---|---|---|\n| Creator | %s | %s |\n| Challengers (%d/%d) | %s | %s |\n\n",
		mimir.Escape(c.CreatorPosition), mimir.FormatUSD(c.CreatorStake),
		len(c.challengers), c.MaxChallengers, mimir.Escape(c.CounterPosition), mimir.FormatUSD(c.TotalChallengerStake)))
	b.WriteString(ufmt.Sprintf("- Closes: %s\n- Source: %s\n- Creator: %s\n",
		when(c.Deadline), mimir.Escape(c.ResolutionURL), c.Creator.String()))
	if c.SettlementRule != "" {
		b.WriteString("- Rule: " + mimir.Escape(c.SettlementRule) + "\n")
	}
	p := c.Proposal
	switch c.State {
	case StProposed:
		b.WriteString(ufmt.Sprintf("\n## Proposed: %s (%d%% confidence)\n\nDisputable until %s.\n\n> %s\n\nEvidence: %s\n",
			sideName(c, p.WinnerSide), p.Confidence, when(p.ProposedAt+disputeWindow), mimir.Escape(p.Summary), hashOrNone(p.EvidenceHash)))
	case StDisputed:
		b.WriteString(ufmt.Sprintf("\n## Disputed\n\nThe oracle proposed %s; the arbiter rules.\n", sideName(c, p.WinnerSide)))
	case StResolved:
		b.WriteString(ufmt.Sprintf("\n## Result: %s (%d%% confidence)\n\n> %s\n\nEvidence: %s\n",
			sideName(c, c.WinnerSide), c.Confidence, mimir.Escape(c.ResolutionSummary), hashOrNone(c.EvidenceHash)))
	}
	b.WriteString(ufmt.Sprintf("\n## Act\n\nApprove this realm on mUSD first, then: [Challenge]($help&func=ChallengeClaim&claimID=%d) · [Finalize]($help&func=FinalizeResolution&claimID=%d) · [Dispute]($help&func=DisputeResolution&claimID=%d)\n\n[All duels](:)\n",
		c.ID, c.ID, c.ID))
	return b.String()
}

func bpsX(bps int64) string {
	cents := (bps % 10_000) / 100
	pad := ""
	if cents < 10 {
		pad = "0"
	}
	return ufmt.Sprintf("%d.%s%dx", bps/10_000, pad, cents)
}

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

settle.gno

package vs

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

func validVerdict(side int) {
	if side < SideCreator || side > SideUnresolvable {
		panic("InvalidVerdict")
	}
}

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

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

// refundAt is when RefundExpired opens: grace counted from the deadline, or
// from the proposal or dispute if later. From then on new verdicts are refused.
func refundAt(c *Claim) int64 {
	start := c.Deadline
	if c.Proposal.ProposedAt > start {
		start = c.Proposal.ProposedAt
	}
	if c.Proposal.DisputedAt > start {
		start = c.Proposal.DisputedAt
	}
	return start + ResolutionGraceSeconds
}

// ResolveClaimWithCutoff is the oracle's verdict on an active claim. With a
// dispute window it is a proposal; only stakes made strictly before `cutoff`
// (0 = all) compete, later ones are refunded.
func ResolveClaimWithCutoff(cur realm, claimID int64, winnerSide int, summary string,
	confidence int, evidenceHash string, cutoff int64) {
	roles.AssertOracle(caller(cur))
	roles.AssertNotPaused()
	c := getClaim(claimID)
	if c.State != StActive {
		panic("NotActive")
	}
	if now() < c.Deadline {
		panic("NotYetExpired")
	}
	if now() >= refundAt(c) {
		panic("GraceOver")
	}
	validVerdict(winnerSide)
	validHash(evidenceHash)
	if confidence < 0 || confidence > 100 {
		panic("BadConfidence")
	}
	setCutoff(c, cutoff)
	if disputeWindow == 0 {
		settle(cur, c, winnerSide, summary, confidence, evidenceHash)
		return
	}
	c.State = StProposed
	c.Proposal = Proposal{WinnerSide: winnerSide, Confidence: confidence, ProposedAt: now(),
		EvidenceHash: evidenceHash, Summary: summary}
	emit("ResolutionProposed", "id", itoa(claimID), "winnerSide", itoa(int64(winnerSide)),
		"confidence", itoa(int64(confidence)), "evidenceHash", evidenceHash,
		"disputableUntil", itoa(now()+disputeWindow))
}

// DisputeResolution escalates a proposed verdict to the arbiter by posting
// DisputeBond. The bond comes back if the arbiter changes the verdict and is
// forfeited otherwise. Open to the creator, challengers, the audit agent and
// the arbiter.
func DisputeResolution(cur realm, claimID int64) {
	c := getClaim(claimID)
	if c.State != StProposed {
		panic("NothingToDispute")
	}
	if now() >= c.Proposal.ProposedAt+disputeWindow {
		panic("DisputeWindowClosed")
	}
	u := caller(cur)
	if !(u == c.Creator || c.hasJoined(u) || (roles.AuditAgent != "" && u == roles.AuditAgent) || u == roles.Arbiter) {
		panic("NotAParticipant")
	}
	// The bond is not a position: no entry fee.
	pull(cur, u, DisputeBond)
	c.State = StDisputed
	c.Proposal.Disputer = u
	c.Proposal.DisputedAt = now()
	c.Proposal.Bond = DisputeBond
	emit("ResolutionDisputed", "id", itoa(claimID), "disputer", u.String(), "bond", itoa(DisputeBond))
}

// VetoProposal sends a proposal the owner believes wrong to the arbiter, inside
// the window. No bond; if the arbiter never rules, RefundExpired refunds.
func VetoProposal(cur realm, claimID int64) {
	roles.AssertOwner(caller(cur))
	c := getClaim(claimID)
	if c.State != StProposed {
		panic("NotProposed")
	}
	if now() >= c.Proposal.ProposedAt+disputeWindow {
		panic("WindowClosed")
	}
	c.State = StDisputed
	c.Proposal.DisputedAt = now()
	emit("ResolutionDisputed", "id", itoa(claimID), "disputer", "", "bond", "0")
}

// FinalizeResolution settles an undisputed proposal once its window has closed. Anyone may call it.
func FinalizeResolution(cur realm, claimID int64) {
	roles.AssertNotPaused()
	c := getClaim(claimID)
	if c.State != StProposed {
		panic("NotProposed")
	}
	if now() < c.Proposal.ProposedAt+disputeWindow {
		panic("DisputeWindowOpen")
	}
	p := c.Proposal
	settle(cur, c, p.WinnerSide, p.Summary, p.Confidence, p.EvidenceHash)
}

// ResolveDisputeWithCutoff is the arbiter's final word on a disputed claim.
func ResolveDisputeWithCutoff(cur realm, claimID int64, winnerSide int, summary string,
	confidence int, evidenceHash string, cutoff int64) {
	roles.AssertNotPaused()
	roles.AssertArbiter(caller(cur))
	c := getClaim(claimID)
	if c.State != StDisputed {
		panic("NotDisputed")
	}
	if now() >= refundAt(c) {
		panic("GraceOver")
	}
	validVerdict(winnerSide)
	validHash(evidenceHash)
	disputerRight := winnerSide != c.Proposal.WinnerSide || cutoff != c.SettlementCutoff
	setCutoff(c, cutoff)
	emit("DisputeResolved", "id", itoa(claimID), "winnerSide", itoa(int64(winnerSide)), "disputerRight", boolStr(disputerRight))
	// Settle first: the claim is resolved before any value leaves, bond included.
	settle(cur, c, winnerSide, summary, confidence, evidenceHash)
	settleBond(cur, c, disputerRight)
}

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

// RefundExpired is the escape hatch, open to anyone once the grace has passed:
//   - an active claim the oracle never resolved refunds every stake;
//   - a disputed claim the arbiter never ruled on settles to the proposal and
//     the bond is forfeited, unless the owner vetoed it or the realm is
//     paused: then every stake is refunded and the bond goes back;
//   - a paused, undisputed proposal refunds after the grace from its proposal.
func RefundExpired(cur realm, claimID int64) {
	c := getClaim(claimID)
	disputed := c.State == StDisputed
	if !(disputed || c.State == StActive || (roles.Paused && c.State == StProposed)) {
		panic("NotActive")
	}
	if now() < refundAt(c) {
		panic("OracleGraceNotOver")
	}
	p := c.Proposal
	switch {
	case disputed && !roles.Paused && p.Disputer != "":
		emit("DisputeResolved", "id", itoa(claimID), "winnerSide", itoa(int64(p.WinnerSide)), "disputerRight", "false")
		settle(cur, c, p.WinnerSide, p.Summary, p.Confidence, p.EvidenceHash)
		settleBond(cur, c, false)
	case disputed:
		emit("DisputeResolved", "id", itoa(claimID), "winnerSide", itoa(SideUnresolvable), "disputerRight", "true")
		settle(cur, c, SideUnresolvable, "Refunded: vetoed or paused", 0, "")
		settleBond(cur, c, true)
	default:
		emit("ClaimExpiredRefund", "id", itoa(claimID), "caller", caller(cur).String())
		settle(cur, c, SideUnresolvable, "Refunded: not resolved within the grace period", 0, "")
	}
}

// EligibleTotals are the creator's and the challengers' stakes that compete
// under the settlement cutoff.
func EligibleTotals(claimID int64) (int64, int64) { return eligibleTotals(getClaim(claimID)) }

func eligibleTotals(c *Claim) (int64, int64) {
	if c.SettlementCutoff == 0 {
		return c.CreatorStake, c.TotalChallengerStake
	}
	if c.CreatedAt >= c.SettlementCutoff {
		return 0, 0
	}
	b := int64(0)
	for _, ch := range c.challengers {
		if ch.At < c.SettlementCutoff {
			b += ch.Stake
		}
	}
	return c.CreatorStake, b
}

func settle(cur realm, c *Claim, winnerSide int, summary string, confidence int, evidenceHash string) {
	c.State = StResolved
	c.WinnerSide = winnerSide
	c.ResolutionSummary = summary
	c.Confidence = confidence
	c.EvidenceHash = evidenceHash
	totalResolved++
	paid, taken := distribute(cur, c, winnerSide)
	emit("ClaimResolved", "id", itoa(c.ID), "winnerSide", itoa(int64(winnerSide)), "summary", summary,
		"confidence", itoa(int64(confidence)), "evidenceHash", evidenceHash)
	emit("MarketSettled", "id", itoa(c.ID), "totalPaid", itoa(paid), "totalFees", itoa(taken))
}

// distribute pays only eligible risk; late principal is refunded as on a draw.
func distribute(cur realm, c *Claim, outcome int) (totalPaid, totalFees int64) {
	_, eligible := eligibleTotals(c)
	// A late creator also gives zero eligible challenger liquidity.
	if eligible == 0 {
		outcome = SideUnresolvable
	}
	remainder := c.CreatorStake
	atRisk := eligible * MaxPoolMultiple
	if atRisk > remainder {
		atRisk = remainder
	}
	if outcome == SideCreator {
		totalPaid, totalFees = payWinner(cur, c.ID, c.Creator, remainder+eligible, remainder, c.Referrer)
		remainder = 0
		bump(&wins, c.Creator)
	} else if outcome == SideChallengers {
		bump(&losses, c.Creator)
	}
	for _, ch := range c.challengers {
		early := c.SettlementCutoff == 0 || ch.At < c.SettlementCutoff
		switch {
		case early && outcome == SideCreator:
			bump(&losses, ch.Addr)
		case early && outcome == SideChallengers:
			var payout int64
			if c.OddsMode == "fixed" {
				payout = grossPayout(ch.Stake, c.ChallengerPayoutBps)
				if payout > ch.Stake {
					// Admission reserved every fixed profit; excluding late positions only reduces it.
					remainder -= payout - ch.Stake
				}
			} else {
				share := mimir.MulDiv(ch.Stake, atRisk, eligible)
				remainder -= share
				payout = ch.Stake + share
			}
			paid, taken := payWinner(cur, c.ID, ch.Addr, payout, ch.Stake, ch.Referrer)
			totalPaid += paid
			totalFees += taken
			bump(&wins, ch.Addr)
		default:
			push(cur, ch.Addr, ch.Stake)
			totalPaid += ch.Stake
		}
	}
	push(cur, c.Creator, remainder)
	totalPaid += remainder
	return totalPaid, totalFees
}

views.gno

package vs

import (
	"strings"

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

func ClaimCount() int64                      { return claimCount }
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 counter(&accruedFees, a) }
func UserStats(a address) (int64, int64)     { return counter(&wins, a), counter(&losses, a) }
func HasChallenged(id int64, a address) bool { return getClaim(id).hasJoined(a) }
func Invited(id int64, a address) bool       { return getClaim(id).isInvited(a) }

// PlatformStats: claims opened, claims resolved.
func PlatformStats() (int64, int64) { return claimCount, totalResolved }

// FeeStats: accrued, claimed and outstanding fees. Outstanding is always covered by the realm's balance.
func FeeStats() (int64, int64, int64) {
	return lifetimeFeesAccrued, lifetimeFeesClaimed, lifetimeFeesAccrued - lifetimeFeesClaimed
}

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(ChallengeLockSeconds)),
		kv("graceSeconds", itoa(ResolutionGraceSeconds)),
		kv("maxPoolMultiple", itoa(MaxPoolMultiple)),
		kv("maxMarketStake", itoa(roles.MaxMarketStake)),
		kv("maxAccountStake", itoa(roles.MaxAccountStake)),
		kv("claimCount", itoa(claimCount)),
		kv("totalResolved", itoa(totalResolved)),
		kv("lifetimeFeesAccrued", itoa(lifetimeFeesAccrued)),
		kv("lifetimeFeesClaimed", itoa(lifetimeFeesClaimed)),
		kv("now", itoa(now())),
	}, ",") + "}"
}

func ClaimJSON(id int64) string { return claimJSON(getClaim(id)) }

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

// ChallengersJSON lists a claim's challengers in the order they joined.
func ChallengersJSON(id int64) string {
	c := getClaim(id)
	out := make([]string, 0, len(c.challengers))
	for _, ch := range c.challengers {
		out = append(out, "{"+strings.Join([]string{
			kv("address", mimir.Quote(ch.Addr.String())),
			kv("stake", itoa(ch.Stake)),
			kv("at", itoa(ch.At)),
			kv("referrer", mimir.Quote(ch.Referrer.String())),
		}, ",")+"}")
	}
	return "[" + strings.Join(out, ",") + "]"
}

func claimJSON(c *Claim) string {
	ea, eb := eligibleTotals(c)
	p := c.Proposal
	return "{" + strings.Join([]string{
		kv("id", itoa(c.ID)),
		kv("creator", mimir.Quote(c.Creator.String())),
		kv("question", mimir.Quote(c.Question)),
		kv("creatorPosition", mimir.Quote(c.CreatorPosition)),
		kv("counterPosition", mimir.Quote(c.CounterPosition)),
		kv("resolutionUrl", mimir.Quote(c.ResolutionURL)),
		kv("creatorStake", itoa(c.CreatorStake)),
		kv("totalChallengerStake", itoa(c.TotalChallengerStake)),
		kv("reservedCreatorLiability", itoa(c.ReservedCreatorLiability)),
		kv("eligibleCreator", itoa(ea)),
		kv("eligibleChallengers", itoa(eb)),
		kv("deadline", itoa(c.Deadline)),
		kv("state", itoa(int64(c.State))),
		kv("winnerSide", itoa(int64(c.WinnerSide))),
		kv("resolutionSummary", mimir.Quote(c.ResolutionSummary)),
		kv("confidence", itoa(int64(c.Confidence))),
		kv("category", mimir.Quote(c.Category)),
		kv("parentId", itoa(c.ParentID)),
		kv("challengerCount", itoa(int64(len(c.challengers)))),
		kv("createdAt", itoa(c.CreatedAt)),
		kv("marketType", mimir.Quote(c.MarketType)),
		kv("oddsMode", mimir.Quote(c.OddsMode)),
		kv("challengerPayoutBps", itoa(c.ChallengerPayoutBps)),
		kv("handicapLine", mimir.Quote(c.HandicapLine)),
		kv("settlementRule", mimir.Quote(c.SettlementRule)),
		kv("maxChallengers", itoa(int64(c.MaxChallengers))),
		kv("isPrivate", boolStr(c.IsPrivate)),
		kv("evidenceHash", mimir.Quote(c.EvidenceHash)),
		kv("referrer", mimir.Quote(c.Referrer.String())),
		kv("entryFees", itoa(c.EntryFees)),
		kv("settlementCutoff", itoa(c.SettlementCutoff)),
		kv("lockAt", itoa(c.LockAt)),
		kv("proposal", "{"+strings.Join([]string{
			kv("winnerSide", itoa(int64(p.WinnerSide))),
			kv("confidence", itoa(int64(p.Confidence))),
			kv("proposedAt", itoa(p.ProposedAt)),
			kv("disputedAt", itoa(p.DisputedAt)),
			kv("disputer", mimir.Quote(p.Disputer.String())),
			kv("bond", itoa(p.Bond)),
			kv("evidenceHash", mimir.Quote(p.EvidenceHash)),
			kv("summary", mimir.Quote(p.Summary)),
		}, ",")+"}"),
	}, ",") + "}"
}

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

vs.gno

// Package vs is Mimir's VS (duel) market, settled by an AI oracle: the
// gno.land port of contracts/MimirV3Erc20.sol. Stakes are mUSD.
//
// A creator opens a claim with a stake on their position. Challengers take the
// other side, each once, up to the claim's maxChallengers (at most 100):
//   - pool odds: challengers share the creator's stake pro rata, and together
//     may stake at most MaxPoolMultiple times the creator's stake;
//   - fixed odds: each challenger is paid challengerPayoutBps of their stake
//     (2x by default, at most 10x), and the creator's unreserved stake must
//     cover every challenger's profit when they join.
//
// After the deadline the oracle proposes CREATOR, CHALLENGERS, DRAW or
// UNRESOLVABLE with a confidence and the hash of its evidence. A participant
// may dispute within the dispute window by posting DisputeBond; the arbiter
// rules. An undisputed proposal is finalized by anyone. Settlement pays every
// participant in the same transaction. Draws, unresolvable questions and
// claims nobody challenged before the cutoff refund every stake.
//
// Fees: an entry fee on every stake that opens or joins a claim
// (fees.EntryBps, 0.5% by default), kept on refunds. No fee on winnings,
// except copy trades: ReferrerFeeBps of the profit to the referrer and
// CopyFeeBps to the platform.
//
// Private claims: only wallets the creator invites may challenge. Market data
// and transactions stay public.
//
// Differences from the EVM contract come from the transport, as in the pool
// realm: mUSD with an approve in the same transaction (no permit variants),
// payouts sent directly (mUSD cannot refuse or re-enter), block-time seconds.
// SetInvited takes a comma-separated address list.
package vs

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"
)

// Claim states.
const (
	StOpen      = 0
	StActive    = 1
	StResolved  = 2
	StCancelled = 3
	StProposed  = 4 // the oracle has proposed a verdict; disputable until the window closes
	StDisputed  = 5 // a participant disputed; the arbiter decides
)

// Winner sides.
const (
	SideNone         = 0
	SideCreator      = 1
	SideChallengers  = 2
	SideDraw         = 3
	SideUnresolvable = 4
)

const (
	MaxChallengers  = 100
	MaxPoolMultiple = int64(5)
	// MinStake is the smallest gross stake that opens or joins a claim: 0.1 mUSD.
	MinStake         = int64(100_000)
	DisputeBond      = int64(2_000_000)
	DefaultPayoutBps = int64(20_000) // 2x
	// Fixed odds pay at most 10x.
	MaxPayoutBps     = int64(100_000)
	MaxDeadlineAhead = int64(365 * 24 * 60 * 60)
	MaxEntryBps      = int64(100)
	// Anti-sniping: no new challenges in the final seconds before the deadline.
	ChallengeLockSeconds   = int64(60)
	ReferrerFeeBps         = int64(100)
	CopyFeeBps             = int64(100)
	ResolutionGraceSeconds = int64(7 * 24 * 60 * 60)
	MinLiveDisputeWindow   = int64(24 * 60 * 60)
	TestnetDisputeWindow   = int64(10 * 60)
)

const (
	Deployer       = address("g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz")
	InitialOracle  = address("g18pnec3atge4msr5hhanm790tljtdyd87s0wguh")
	InitialArbiter = address("g1af78r3tuv84mf3cd0kxrssmw6g2v2mvvc6phpv")
)

type Challenger struct {
	Addr     address
	Stake    int64 // net
	At       int64
	Referrer address
}

type Proposal struct {
	WinnerSide   int
	Confidence   int
	ProposedAt   int64
	DisputedAt   int64
	Disputer     address
	Bond         int64
	EvidenceHash string
	Summary      string
}

type Claim struct {
	ID                       int64
	Creator                  address
	Question                 string
	CreatorPosition          string
	CounterPosition          string
	ResolutionURL            string
	CreatorStake             int64
	TotalChallengerStake     int64
	ReservedCreatorLiability int64
	Deadline                 int64
	State                    int
	WinnerSide               int
	ResolutionSummary        string
	Confidence               int
	Category                 string
	ParentID                 int64
	CreatedAt                int64
	MarketType               string // binary | moneyline | spread | total | prop | custom
	OddsMode                 string // pool | fixed
	ChallengerPayoutBps      int64  // fixed odds, e.g. 20000 = 2x
	HandicapLine             string
	SettlementRule           string
	MaxChallengers           int
	IsPrivate                bool
	EvidenceHash             string
	Referrer                 address // the creator's referrer
	EntryFees                int64
	SettlementCutoff         int64
	LockAt                   int64
	Proposal                 Proposal

	challengers []*Challenger
	joined      avl.Tree // address -> true
	invited     avl.Tree // address -> bool
}

var (
	claims        avl.Tree // padded id -> *Claim
	claimCount    int64
	totalResolved int64

	wins   avl.Tree // address -> int64
	losses avl.Tree

	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 caller(cur realm) address         { return cur.Previous().Address() }

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

func getClaim(id int64) *Claim {
	v := claims.Get(key(id))
	if v == nil {
		panic("ClaimNotFound")
	}
	return v.(*Claim)
}

func (c *Claim) hasJoined(a address) bool { return c.joined.Has(a.String()) }

func (c *Claim) isInvited(a address) bool {
	v := c.invited.Get(a.String())
	return v != nil && v.(bool)
}

func counter(t *avl.Tree, a address) int64 {
	if v := t.Get(a.String()); v != nil {
		return v.(int64)
	}
	return 0
}

func bump(t *avl.Tree, a address) { t.Set(a.String(), counter(t, a)+1) }

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

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)
}

// takeEntry pulls `amount` from the caller, keeps the caller's entry fee and
// returns the rest: the stake that is recorded and can be won or refunded.
func takeEntry(cur realm, c *Claim, user address, amount int64) int64 {
	pull(cur, user, amount)
	bps := fees.EntryBps(user)
	if bps > MaxEntryBps {
		panic("EntryFeeTooHigh")
	}
	fee := mimir.MulDiv(amount, bps, 10_000)
	if fee != 0 {
		accrue(c.ID, roles.FeeRecipient, fee)
		c.EntryFees += fee
	}
	return amount - fee
}

func grossPayout(stake, bps int64) int64 { return mimir.MulDiv(stake, bps, 10_000) }

// payWinner pays a winner. Only a copy trade pays a fee on winnings:
// ReferrerFeeBps of the profit to the referrer and CopyFeeBps to the platform.
// Profit is gross - principal floored at zero, so a refund and a break-even
// win are free. Nobody pays themselves.
func payWinner(cur realm, id int64, to address, gross, principal int64, referrer address) (paid, taken int64) {
	profit := int64(0)
	if gross > principal {
		profit = gross - principal
	}
	if profit != 0 && referrer != "" && referrer != to {
		refFee := mimir.MulDiv(profit, ReferrerFeeBps, 10_000)
		if refFee != 0 {
			accrue(id, referrer, refFee)
		}
		copyFee := int64(0)
		if roles.FeeRecipient != to {
			copyFee = mimir.MulDiv(profit, CopyFeeBps, 10_000)
		}
		if copyFee != 0 {
			accrue(id, roles.FeeRecipient, copyFee)
		}
		taken = refFee + copyFee
	}
	paid = gross - taken
	push(cur, to, paid)
	return paid, taken
}

vs_test.gno

package vs

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)
)

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

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), vsAt, musd.Allowance(user, vsAt)+amount)
}

func open(cur realm, user address, amount, closesIn int64, odds string, payoutBps int64, private bool) int64 {
	fund(cur, user, amount)
	testing.SetRealm(testing.NewUserRealm(user))
	return CreateClaim(cross(cur), "BTC above 100k on Friday?", "Yes", "No", "https://example.com",
		now()+closesIn, amount, "Crypto", 0, "binary", odds, payoutBps, "", "", 0, private, "")
}

func challenge(cur realm, user address, id, amount int64, referrer string) {
	fund(cur, user, amount)
	testing.SetRealm(testing.NewUserRealm(user))
	ChallengeClaim(cross(cur), id, amount, referrer)
}

func propose(cur realm, id int64, side int) {
	testing.SetRealm(testing.NewUserRealm(InitialOracle))
	ResolveClaimWithCutoff(cross(cur), id, side, "verdict", 90, "", 0)
}

func finalize(cur realm, id int64) {
	skip(DisputeWindow())
	testing.SetRealm(testing.NewUserRealm(dave))
	FinalizeResolution(cross(cur), id)
}

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

func TestPoolOddsChallengersWin(cur realm, t *testing.T) {
	id := open(cur, alice, 100*usd, 3600, "pool", 0, false)
	challenge(cur, bob, id, 20*usd, "")
	challenge(cur, carol, id, 20*usd, "")
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsContains(t, cur, "AlreadyChallenged", func() { ChallengeClaim(cross(cur), id, usd, "") })
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "SelfChallenge", func() { ChallengeClaim(cross(cur), id, usd, "") })
	uassert.AbortsContains(t, cur, "NotOpen", func() { CancelClaim(cross(cur), id) })

	skip(3600)
	propose(cur, id, SideChallengers)
	b0, c0, a0 := musd.BalanceOf(bob), musd.BalanceOf(carol), musd.BalanceOf(alice)
	finalize(cur, id)
	// Creator 99.5 net; challengers 19.9 each; at risk = min(39.8*5, 99.5) = 99.5, split evenly.
	uassert.Equal(t, int64(19_900_000+49_750_000), musd.BalanceOf(bob)-b0)
	uassert.Equal(t, int64(19_900_000+49_750_000), musd.BalanceOf(carol)-c0)
	uassert.Equal(t, int64(0), musd.BalanceOf(alice)-a0)
	w, l := UserStats(bob)
	uassert.Equal(t, int64(1), w)
	uassert.Equal(t, int64(0), l)
}

func TestPoolOddsCreatorWinsAndPoolCap(cur realm, t *testing.T) {
	id := open(cur, alice, 10*usd, 3600, "pool", 0, false)
	fund(cur, bob, 60*usd)
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsContains(t, cur, "PoolFull", func() { ChallengeClaim(cross(cur), id, 60*usd, "") })
	challenge(cur, carol, id, 10*usd, "")
	skip(3600)
	propose(cur, id, SideCreator)
	a0 := musd.BalanceOf(alice)
	finalize(cur, id)
	uassert.Equal(t, int64(19_900_000), musd.BalanceOf(alice)-a0)
}

func TestFixedOddsReservesLiquidity(cur realm, t *testing.T) {
	id := open(cur, alice, 10*usd, 3600, "fixed", 30_000, false) // 3x
	fund(cur, bob, 10*usd)
	testing.SetRealm(testing.NewUserRealm(bob))
	// 3x on 9.95 net needs 19.9 of creator liquidity; only 9.95 exists.
	uassert.AbortsContains(t, cur, "CreatorHasInsufficientLiquidity", func() { ChallengeClaim(cross(cur), id, 10*usd, "") })
	challenge(cur, carol, id, 2*usd, "")
	skip(3600)
	propose(cur, id, SideChallengers)
	c0, a0 := musd.BalanceOf(carol), musd.BalanceOf(alice)
	finalize(cur, id)
	uassert.Equal(t, int64(5_970_000), musd.BalanceOf(carol)-c0)           // 1.99 * 3
	uassert.Equal(t, int64(9_950_000-3_980_000), musd.BalanceOf(alice)-a0) // unreserved remainder
}

func TestCancelAndUnchallengedRefund(cur realm, t *testing.T) {
	id := open(cur, alice, 5*usd, 3600, "pool", 0, false)
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsContains(t, cur, "NotCreator", func() { CancelClaim(cross(cur), id) })
	a0 := musd.BalanceOf(alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	CancelClaim(cross(cur), id)
	uassert.Equal(t, int64(4_975_000), musd.BalanceOf(alice)-a0) // the entry fee stays earned
}

func TestPrivateInvites(cur realm, t *testing.T) {
	id := open(cur, alice, 5*usd, 3600, "pool", 0, true)
	fund(cur, bob, usd)
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsContains(t, cur, "NotInvited", func() { ChallengeClaim(cross(cur), id, usd, "") })
	uassert.AbortsContains(t, cur, "BadInvite", func() { SetInvited(cross(cur), id, bob.String(), true) })
	testing.SetRealm(testing.NewUserRealm(alice))
	SetInvited(cross(cur), id, bob.String()+", "+carol.String(), true)
	uassert.True(t, Invited(id, carol))
	testing.SetRealm(testing.NewUserRealm(bob))
	ChallengeClaim(cross(cur), id, usd, "")
	uassert.True(t, HasChallenged(id, bob))
}

func TestDisputeAndRuling(cur realm, t *testing.T) {
	id := open(cur, alice, 10*usd, 3600, "pool", 0, false)
	challenge(cur, bob, id, 10*usd, "")
	skip(3600)
	propose(cur, id, SideCreator)
	testing.SetRealm(testing.NewUserRealm(carol))
	uassert.AbortsContains(t, cur, "NotAParticipant", func() { DisputeResolution(cross(cur), id) })
	fund(cur, bob, DisputeBond)
	testing.SetRealm(testing.NewUserRealm(bob))
	DisputeResolution(cross(cur), id)
	b0 := musd.BalanceOf(bob)
	testing.SetRealm(testing.NewUserRealm(InitialArbiter))
	ResolveDisputeWithCutoff(cross(cur), id, SideChallengers, "overturned", 80, "", 0)
	uassert.Equal(t, int64(19_900_000)+DisputeBond, musd.BalanceOf(bob)-b0)
}

func TestCutoffRefundsLateChallenger(cur realm, t *testing.T) {
	id := open(cur, alice, 10*usd, 3600, "pool", 0, false)
	challenge(cur, bob, id, 10*usd, "")
	skip(600)
	cutoff := now()
	skip(60)
	challenge(cur, carol, id, 10*usd, "")
	skip(3600)
	testing.SetRealm(testing.NewUserRealm(InitialOracle))
	ResolveClaimWithCutoff(cross(cur), id, SideChallengers, "late entry excluded", 95, "", cutoff)
	_, eb := EligibleTotals(id)
	uassert.Equal(t, int64(9_950_000), eb)
	b0, c0 := musd.BalanceOf(bob), musd.BalanceOf(carol)
	finalize(cur, id)
	uassert.Equal(t, int64(19_900_000), musd.BalanceOf(bob)-b0)
	uassert.Equal(t, int64(9_950_000), musd.BalanceOf(carol)-c0)
}

func TestRefundExpiredAndCopyFees(cur realm, t *testing.T) {
	id := open(cur, alice, 10*usd, 3600, "pool", 0, false)
	challenge(cur, bob, id, 10*usd, "")
	skip(3600 + ResolutionGraceSeconds)
	a0, b0 := musd.BalanceOf(alice), musd.BalanceOf(bob)
	testing.SetRealm(testing.NewUserRealm(carol))
	RefundExpired(cross(cur), id)
	uassert.Equal(t, int64(9_950_000), musd.BalanceOf(alice)-a0)
	uassert.Equal(t, int64(9_950_000), musd.BalanceOf(bob)-b0)

	// A copied winner pays 1% of profit to the referrer and 1% to the platform.
	id = open(cur, alice, 100*usd, 3600, "pool", 0, false)
	challenge(cur, bob, id, 100*usd, dave.String())
	skip(3600)
	propose(cur, id, SideChallengers)
	b0 = musd.BalanceOf(bob)
	r0 := AccruedFees(dave)
	finalize(cur, id)
	uassert.Equal(t, int64(199_000_000-1_990_000), musd.BalanceOf(bob)-b0)
	uassert.Equal(t, int64(995_000), AccruedFees(dave)-r0)
	testing.SetRealm(testing.NewUserRealm(dave))
	ClaimFees(cross(cur))
}

func TestRematchAndGuards(cur realm, t *testing.T) {
	parent := open(cur, alice, 5*usd, 3600, "fixed", 15_000, false)
	fund(cur, bob, 5*usd)
	testing.SetRealm(testing.NewUserRealm(bob))
	id := CreateRematch(cross(cur), parent, now()+7200, 5*usd)
	uassert.True(t, len(ClaimJSON(id)) > 0)
	uassert.True(t, len(ChallengersJSON(id)) >= 2)
	uassert.True(t, len(ClaimsJSON(0, 5)) > 2)
	uassert.True(t, len(Render("")) > 0)
	uassert.True(t, len(Render("1")) > 0)

	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsContains(t, cur, "PayoutTooHigh", func() {
		CreateClaim(cross(cur), "q", "a", "b", "", now()+3600, MinStake, "", 0, "", "fixed", 200_000, "", "", 0, false, "")
	})
	uassert.AbortsContains(t, cur, "DeadlineInPast", func() {
		CreateClaim(cross(cur), "q", "a", "b", "", now(), MinStake, "", 0, "", "", 0, "", "", 0, false, "")
	})
	testing.SetRealm(testing.NewUserRealm(Deployer))
	SetPaused(cross(cur), true)
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsContains(t, cur, "IsPaused", func() { ChallengeClaim(cross(cur), parent, MinStake, "") })
	testing.SetRealm(testing.NewUserRealm(Deployer))
	SetPaused(cross(cur), false)
	skip(mimir.TimelockSeconds)
}