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.

settle.gno

9.10 Kb · 286 lines
  1package vs
  2
  3import (
  4	mimir "gno.land/p/g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz/mimir"
  5)
  6
  7func validVerdict(side int) {
  8	if side < SideCreator || side > SideUnresolvable {
  9		panic("InvalidVerdict")
 10	}
 11}
 12
 13func validHash(h string) {
 14	if h == "" {
 15		return
 16	}
 17	if len(h) != 64 {
 18		panic("BadEvidenceHash")
 19	}
 20	for _, ch := range h {
 21		if !(ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'f') {
 22			panic("BadEvidenceHash")
 23		}
 24	}
 25}
 26
 27func setCutoff(c *Claim, cutoff int64) {
 28	if cutoff > now() || cutoff < 0 {
 29		panic("BadCutoff")
 30	}
 31	c.SettlementCutoff = cutoff
 32	emit("SettlementCutoffSet", "id", itoa(c.ID), "cutoff", itoa(cutoff))
 33}
 34
 35// refundAt is when RefundExpired opens: grace counted from the deadline, or
 36// from the proposal or dispute if later. From then on new verdicts are refused.
 37func refundAt(c *Claim) int64 {
 38	start := c.Deadline
 39	if c.Proposal.ProposedAt > start {
 40		start = c.Proposal.ProposedAt
 41	}
 42	if c.Proposal.DisputedAt > start {
 43		start = c.Proposal.DisputedAt
 44	}
 45	return start + ResolutionGraceSeconds
 46}
 47
 48// ResolveClaimWithCutoff is the oracle's verdict on an active claim. With a
 49// dispute window it is a proposal; only stakes made strictly before `cutoff`
 50// (0 = all) compete, later ones are refunded.
 51func ResolveClaimWithCutoff(cur realm, claimID int64, winnerSide int, summary string,
 52	confidence int, evidenceHash string, cutoff int64) {
 53	roles.AssertOracle(caller(cur))
 54	roles.AssertNotPaused()
 55	c := getClaim(claimID)
 56	if c.State != StActive {
 57		panic("NotActive")
 58	}
 59	if now() < c.Deadline {
 60		panic("NotYetExpired")
 61	}
 62	if now() >= refundAt(c) {
 63		panic("GraceOver")
 64	}
 65	validVerdict(winnerSide)
 66	validHash(evidenceHash)
 67	if confidence < 0 || confidence > 100 {
 68		panic("BadConfidence")
 69	}
 70	setCutoff(c, cutoff)
 71	if disputeWindow == 0 {
 72		settle(cur, c, winnerSide, summary, confidence, evidenceHash)
 73		return
 74	}
 75	c.State = StProposed
 76	c.Proposal = Proposal{WinnerSide: winnerSide, Confidence: confidence, ProposedAt: now(),
 77		EvidenceHash: evidenceHash, Summary: summary}
 78	emit("ResolutionProposed", "id", itoa(claimID), "winnerSide", itoa(int64(winnerSide)),
 79		"confidence", itoa(int64(confidence)), "evidenceHash", evidenceHash,
 80		"disputableUntil", itoa(now()+disputeWindow))
 81}
 82
 83// DisputeResolution escalates a proposed verdict to the arbiter by posting
 84// DisputeBond. The bond comes back if the arbiter changes the verdict and is
 85// forfeited otherwise. Open to the creator, challengers, the audit agent and
 86// the arbiter.
 87func DisputeResolution(cur realm, claimID int64) {
 88	c := getClaim(claimID)
 89	if c.State != StProposed {
 90		panic("NothingToDispute")
 91	}
 92	if now() >= c.Proposal.ProposedAt+disputeWindow {
 93		panic("DisputeWindowClosed")
 94	}
 95	u := caller(cur)
 96	if !(u == c.Creator || c.hasJoined(u) || (roles.AuditAgent != "" && u == roles.AuditAgent) || u == roles.Arbiter) {
 97		panic("NotAParticipant")
 98	}
 99	// The bond is not a position: no entry fee.
100	pull(cur, u, DisputeBond)
101	c.State = StDisputed
102	c.Proposal.Disputer = u
103	c.Proposal.DisputedAt = now()
104	c.Proposal.Bond = DisputeBond
105	emit("ResolutionDisputed", "id", itoa(claimID), "disputer", u.String(), "bond", itoa(DisputeBond))
106}
107
108// VetoProposal sends a proposal the owner believes wrong to the arbiter, inside
109// the window. No bond; if the arbiter never rules, RefundExpired refunds.
110func VetoProposal(cur realm, claimID int64) {
111	roles.AssertOwner(caller(cur))
112	c := getClaim(claimID)
113	if c.State != StProposed {
114		panic("NotProposed")
115	}
116	if now() >= c.Proposal.ProposedAt+disputeWindow {
117		panic("WindowClosed")
118	}
119	c.State = StDisputed
120	c.Proposal.DisputedAt = now()
121	emit("ResolutionDisputed", "id", itoa(claimID), "disputer", "", "bond", "0")
122}
123
124// FinalizeResolution settles an undisputed proposal once its window has closed. Anyone may call it.
125func FinalizeResolution(cur realm, claimID int64) {
126	roles.AssertNotPaused()
127	c := getClaim(claimID)
128	if c.State != StProposed {
129		panic("NotProposed")
130	}
131	if now() < c.Proposal.ProposedAt+disputeWindow {
132		panic("DisputeWindowOpen")
133	}
134	p := c.Proposal
135	settle(cur, c, p.WinnerSide, p.Summary, p.Confidence, p.EvidenceHash)
136}
137
138// ResolveDisputeWithCutoff is the arbiter's final word on a disputed claim.
139func ResolveDisputeWithCutoff(cur realm, claimID int64, winnerSide int, summary string,
140	confidence int, evidenceHash string, cutoff int64) {
141	roles.AssertNotPaused()
142	roles.AssertArbiter(caller(cur))
143	c := getClaim(claimID)
144	if c.State != StDisputed {
145		panic("NotDisputed")
146	}
147	if now() >= refundAt(c) {
148		panic("GraceOver")
149	}
150	validVerdict(winnerSide)
151	validHash(evidenceHash)
152	disputerRight := winnerSide != c.Proposal.WinnerSide || cutoff != c.SettlementCutoff
153	setCutoff(c, cutoff)
154	emit("DisputeResolved", "id", itoa(claimID), "winnerSide", itoa(int64(winnerSide)), "disputerRight", boolStr(disputerRight))
155	// Settle first: the claim is resolved before any value leaves, bond included.
156	settle(cur, c, winnerSide, summary, confidence, evidenceHash)
157	settleBond(cur, c, disputerRight)
158}
159
160func settleBond(cur realm, c *Claim, returnIt bool) {
161	bond := c.Proposal.Bond
162	if bond == 0 {
163		return
164	}
165	c.Proposal.Bond = 0
166	if returnIt {
167		push(cur, c.Proposal.Disputer, bond)
168	} else {
169		accrue(c.ID, roles.FeeRecipient, bond)
170	}
171}
172
173// RefundExpired is the escape hatch, open to anyone once the grace has passed:
174//   - an active claim the oracle never resolved refunds every stake;
175//   - a disputed claim the arbiter never ruled on settles to the proposal and
176//     the bond is forfeited, unless the owner vetoed it or the realm is
177//     paused: then every stake is refunded and the bond goes back;
178//   - a paused, undisputed proposal refunds after the grace from its proposal.
179func RefundExpired(cur realm, claimID int64) {
180	c := getClaim(claimID)
181	disputed := c.State == StDisputed
182	if !(disputed || c.State == StActive || (roles.Paused && c.State == StProposed)) {
183		panic("NotActive")
184	}
185	if now() < refundAt(c) {
186		panic("OracleGraceNotOver")
187	}
188	p := c.Proposal
189	switch {
190	case disputed && !roles.Paused && p.Disputer != "":
191		emit("DisputeResolved", "id", itoa(claimID), "winnerSide", itoa(int64(p.WinnerSide)), "disputerRight", "false")
192		settle(cur, c, p.WinnerSide, p.Summary, p.Confidence, p.EvidenceHash)
193		settleBond(cur, c, false)
194	case disputed:
195		emit("DisputeResolved", "id", itoa(claimID), "winnerSide", itoa(SideUnresolvable), "disputerRight", "true")
196		settle(cur, c, SideUnresolvable, "Refunded: vetoed or paused", 0, "")
197		settleBond(cur, c, true)
198	default:
199		emit("ClaimExpiredRefund", "id", itoa(claimID), "caller", caller(cur).String())
200		settle(cur, c, SideUnresolvable, "Refunded: not resolved within the grace period", 0, "")
201	}
202}
203
204// EligibleTotals are the creator's and the challengers' stakes that compete
205// under the settlement cutoff.
206func EligibleTotals(claimID int64) (int64, int64) { return eligibleTotals(getClaim(claimID)) }
207
208func eligibleTotals(c *Claim) (int64, int64) {
209	if c.SettlementCutoff == 0 {
210		return c.CreatorStake, c.TotalChallengerStake
211	}
212	if c.CreatedAt >= c.SettlementCutoff {
213		return 0, 0
214	}
215	b := int64(0)
216	for _, ch := range c.challengers {
217		if ch.At < c.SettlementCutoff {
218			b += ch.Stake
219		}
220	}
221	return c.CreatorStake, b
222}
223
224func settle(cur realm, c *Claim, winnerSide int, summary string, confidence int, evidenceHash string) {
225	c.State = StResolved
226	c.WinnerSide = winnerSide
227	c.ResolutionSummary = summary
228	c.Confidence = confidence
229	c.EvidenceHash = evidenceHash
230	totalResolved++
231	paid, taken := distribute(cur, c, winnerSide)
232	emit("ClaimResolved", "id", itoa(c.ID), "winnerSide", itoa(int64(winnerSide)), "summary", summary,
233		"confidence", itoa(int64(confidence)), "evidenceHash", evidenceHash)
234	emit("MarketSettled", "id", itoa(c.ID), "totalPaid", itoa(paid), "totalFees", itoa(taken))
235}
236
237// distribute pays only eligible risk; late principal is refunded as on a draw.
238func distribute(cur realm, c *Claim, outcome int) (totalPaid, totalFees int64) {
239	_, eligible := eligibleTotals(c)
240	// A late creator also gives zero eligible challenger liquidity.
241	if eligible == 0 {
242		outcome = SideUnresolvable
243	}
244	remainder := c.CreatorStake
245	atRisk := eligible * MaxPoolMultiple
246	if atRisk > remainder {
247		atRisk = remainder
248	}
249	if outcome == SideCreator {
250		totalPaid, totalFees = payWinner(cur, c.ID, c.Creator, remainder+eligible, remainder, c.Referrer)
251		remainder = 0
252		bump(&wins, c.Creator)
253	} else if outcome == SideChallengers {
254		bump(&losses, c.Creator)
255	}
256	for _, ch := range c.challengers {
257		early := c.SettlementCutoff == 0 || ch.At < c.SettlementCutoff
258		switch {
259		case early && outcome == SideCreator:
260			bump(&losses, ch.Addr)
261		case early && outcome == SideChallengers:
262			var payout int64
263			if c.OddsMode == "fixed" {
264				payout = grossPayout(ch.Stake, c.ChallengerPayoutBps)
265				if payout > ch.Stake {
266					// Admission reserved every fixed profit; excluding late positions only reduces it.
267					remainder -= payout - ch.Stake
268				}
269			} else {
270				share := mimir.MulDiv(ch.Stake, atRisk, eligible)
271				remainder -= share
272				payout = ch.Stake + share
273			}
274			paid, taken := payWinner(cur, c.ID, ch.Addr, payout, ch.Stake, ch.Referrer)
275			totalPaid += paid
276			totalFees += taken
277			bump(&wins, ch.Addr)
278		default:
279			push(cur, ch.Addr, ch.Stake)
280			totalPaid += ch.Stake
281		}
282	}
283	push(cur, c.Creator, remainder)
284	totalPaid += remainder
285	return totalPaid, totalFees
286}