pool.gno
7.53 Kb · 233 lines
1// Package pool is Mimir's two-sided pool prediction market, settled by an AI
2// oracle: the gno.land port of contracts/MimirPoolErc20.sol. Stakes are mUSD
3// (gno.land/r/.../musd, 6 decimals).
4//
5// Model
6// - A market has two sides, A and B (YES / NO). The creator opens it with a
7// stake on one side. Anyone, the creator included, can then stake on either
8// side until LockSeconds before the deadline. Stakes by the same address
9// add up per side.
10// - After the deadline the oracle proposes A, B, DRAW or UNRESOLVABLE. A
11// participant can dispute within the dispute window by posting
12// DisputeBond; the arbiter then rules. The bond comes back if the ruling
13// changes the verdict and goes to the platform otherwise. An undisputed
14// proposal is finalized by anyone.
15// - Escape hatch: ResolutionGraceSeconds after the deadline (or after the
16// proposal or dispute), anyone can refund the market in full. From that
17// moment the oracle and the arbiter can no longer rule.
18// - Fees: every stake pays an entry fee, fees.EntryBps(caller) of the amount
19// (0.5% by default, less with a signed ticket); the rest is staked. The
20// entry fee is kept on refunds. Winnings pay no fee, except copy trades: a
21// stake made with a referrer pays ReferrerFeeBps of its net profit to the
22// referrer and CopyFeeBps to the platform.
23// - Payout: a winner gets their stake back plus a pro-rata share of the
24// losing side, rounded down (dust stays in the realm). If either side is
25// empty, or on DRAW / UNRESOLVABLE, everyone gets their stake back.
26// - Settlement only records the outcome. Each staker is then paid by
27// Claim(id), or by anyone through ClaimFor(id, user).
28// - Roles: owner, arbiter (rules disputes), oracle (may never also be owner,
29// arbiter or fee recipient), fee recipient, and an optional audit agent
30// that may dispute. Ownership, oracle and fee-recipient changes are
31// timelocked; the owner can revoke the oracle at once, veto a proposal to
32// the arbiter, cap stakes, set an early lock and pause.
33// - Pause stops new markets and stakes AND settlement and winners' payouts;
34// refunds are still paid, and RefundExpired while paused refunds instead of
35// honouring a proposal.
36//
37// Differences from the EVM contract, all from the transport:
38// - Amounts are mUSD units in int64; MinStake, DisputeBond and caps are in
39// those units. The caller approves this realm on mUSD first; Adena sends
40// the approve and the call in one transaction, so there are no *WithPermit
41// variants.
42// - mUSD has no blacklist and no callbacks, so a payout cannot be refused and
43// cannot re-enter: payouts are sent directly (no parked withdrawals, no
44// gas stipend, no reentrancy lock).
45// - Times are block-time unix seconds.
46package pool
47
48import (
49 "chain"
50 "chain/runtime"
51 "strconv"
52 "time"
53
54 mimir "gno.land/p/g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz/mimir"
55 "gno.land/p/nt/avl/v0"
56 "gno.land/r/g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz/fees"
57 "gno.land/r/g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz/musd"
58)
59
60// Market states.
61const (
62 StOpen = 0
63 StProposed = 1
64 StDisputed = 2
65 StResolved = 3
66)
67
68// Sides and outcomes.
69const (
70 SideA = 1
71 SideB = 2
72 Draw = 3
73 Unresolvable = 4
74)
75
76const (
77 // MinStake is the smallest gross stake: 0.1 mUSD.
78 MinStake = int64(100_000)
79 // DisputeBond is 2 mUSD, independent of the stake minimum so disputes stay costly to spam.
80 DisputeBond = int64(2_000_000)
81 // No new stakes in the final LockSeconds before the deadline (anti-sniping).
82 LockSeconds = int64(60)
83 MaxDeadlineAhead = int64(365 * 24 * 60 * 60)
84 // Entry fees above 1% are refused, whatever the fee realm answers.
85 MaxEntryBps = int64(100)
86 ReferrerFeeBps = int64(100)
87 CopyFeeBps = int64(100)
88 ResolutionGraceSeconds = int64(7 * 24 * 60 * 60)
89 MaxDisputeWindow = int64(7 * 24 * 60 * 60)
90 // On mainnet a proposal stays disputable at least this long.
91 MinLiveDisputeWindow = int64(24 * 60 * 60)
92 // TestnetDisputeWindow lets a testnet show the whole flow in minutes.
93 TestnetDisputeWindow = int64(10 * 60)
94)
95
96// Initial roles. The owner can change each one afterwards.
97const (
98 Deployer = address("g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz")
99 InitialOracle = address("g18pnec3atge4msr5hhanm790tljtdyd87s0wguh")
100 InitialArbiter = address("g1af78r3tuv84mf3cd0kxrssmw6g2v2mvvc6phpv")
101)
102
103type Market struct {
104 ID int64
105 Creator address
106 Deadline int64
107 CreatedAt int64
108 State int
109 Outcome int // final, once resolved
110 Proposed int // the oracle's proposal
111 ProposedAt int64
112 DisputedAt int64
113 Disputer address
114 Bond int64
115 TotalA int64
116 TotalB int64
117 EvidenceHash string // hex sha256 of the oracle's evidence
118 Question string
119 LabelA string
120 LabelB string
121 ResolutionURL string
122 Category string
123 Summary string
124 // 0 includes all deposits; otherwise only deposits strictly before it compete.
125 SettlementCutoff int64
126 // Optional early close: stakes stop at LockAt instead of LockSeconds before the deadline.
127 LockAt int64
128 EntryFees int64
129
130 history mimir.History // market totals over time
131 positions avl.Tree // address -> *Position
132}
133
134type Position struct {
135 A, B int64 // net stakes
136 CopyA, CopyB int64 // the copied part of each
137 Referrer address
138 Claimed bool
139 history mimir.History
140}
141
142var (
143 markets avl.Tree // padded id -> *Market
144 marketCount int64
145
146 accruedFees avl.Tree // address -> int64
147 lifetimeFeesAccrued int64
148 lifetimeFeesClaimed int64
149
150 roles *mimir.Roles
151 disputeWindow int64
152)
153
154func init(cur realm) {
155 roles = mimir.NewRoles(Deployer, InitialArbiter, InitialOracle, Deployer)
156 disputeWindow = TestnetDisputeWindow
157 if runtime.ChainID() == "gnoland-1" {
158 disputeWindow = MinLiveDisputeWindow
159 }
160}
161
162func now() int64 { return time.Now().Unix() }
163
164func emit(typ string, attrs ...string) { chain.Emit(typ, attrs...) }
165
166func itoa(n int64) string { return strconv.FormatInt(n, 10) }
167
168func key(id int64) string {
169 s := itoa(id)
170 for len(s) < 12 {
171 s = "0" + s
172 }
173 return s
174}
175
176func getMarket(id int64) *Market {
177 v := markets.Get(key(id))
178 if v == nil {
179 panic("NoMarket")
180 }
181 return v.(*Market)
182}
183
184func (m *Market) position(user address) *Position {
185 if v := m.positions.Get(user.String()); v != nil {
186 return v.(*Position)
187 }
188 return nil
189}
190
191func (m *Market) mustPosition(user address) *Position {
192 p := m.position(user)
193 if p == nil {
194 p = &Position{}
195 m.positions.Set(user.String(), p)
196 }
197 return p
198}
199
200func feesOf(a address) int64 {
201 if v := accruedFees.Get(a.String()); v != nil {
202 return v.(int64)
203 }
204 return 0
205}
206
207func accrue(id int64, to address, amount int64) {
208 accruedFees.Set(to.String(), mimir.Add(feesOf(to), amount))
209 lifetimeFeesAccrued = mimir.Add(lifetimeFeesAccrued, amount)
210 emit("FeeAccrued", "id", itoa(id), "recipient", to.String(), "amount", itoa(amount))
211}
212
213// pull moves exactly amount mUSD from the caller into this realm (needs an allowance).
214func pull(cur realm, from address, amount int64) {
215 musd.TransferFrom(cross(cur), from, cur.Address(), amount)
216}
217
218func push(cur realm, to address, amount int64) {
219 if amount == 0 {
220 return
221 }
222 musd.Transfer(cross(cur), to, amount)
223}
224
225func caller(cur realm) address { return cur.Previous().Address() }
226
227func assertOwner(cur realm) { roles.AssertOwner(caller(cur)) }
228
229func assertNotPaused() { roles.AssertNotPaused() }
230
231func parseReferrer(s string) address { return mimir.ParseOptional(s) }
232
233func entryBps(a address) int64 { return fees.EntryBps(a) }