Branch data Line data Source code
1 : : ;; Title: BME024 CPMM Scalar Market Predictions
2 : : ;; Synopsis:
3 : : ;; Implements CPMM scalar prediciton markets with pyth oracle resolution and DAO.
4 : : ;; Description:
5 : : ;; Scalar markets differ from binary/categorical markets (see bme024-0-market-predicting)
6 : : ;; in the type of categories and the mechanism for resolution:
7 : : ;; Firstly, the categories are contiguous ranges of numbers with a min and max value. The winning
8 : : ;; category is decided by the range that the outcome selects. Secondly, scalar market outcomes
9 : : ;; are determined by on-chain oracles. This contract uses the Pyth oracle for selecting from possible outcomes.
10 : : ;; Market creation can be gated via market proof and a market creator can
11 : : ;; set their own fee up to a max fee amount determined by the DAO.
12 : : ;; Anyone with the required token can buy shares. Resolution process begins via a call gated
13 : : ;; to the DAO controlled resolution agent address. The resolution can be challenged by anyone with a stake in the market
14 : : ;; If a challenge is made the dispute resolution process begins which requires a DAO vote
15 : : ;; to resolve - the outcome of the vote resolve the market and sets the outcome.
16 : : ;; If the dispute window passes without challenge or once the vote concludes the market is fully
17 : : ;; resolved and claims can then be made.
18 : : ;; Optional hedge strategy - the execute-hedge strategy can be run during market cool down period. The execute-hedge
19 : : ;; function will call the market specific hedge strategy if supplied or the default startegy otherwise.
20 : : ;; The hedge strategy can be switched off by the dao.
21 : :
22 : : (use-trait ft-token 'SP2AKWJYC7BNY18W1XXKPGP0YVEK63QJG4793Z2D4.sip-010-trait-ft-standard.sip-010-trait)
23 : : (impl-trait .prediction-market-trait.prediction-market-trait)
24 : : (use-trait hedge-trait .hedge-trait.hedge-trait)
25 : : (use-trait ft-velar-token 'SP2AKWJYC7BNY18W1XXKPGP0YVEK63QJG4793Z2D4.sip-010-trait-ft-standard.sip-010-trait)
26 : :
27 : : ;; ---------------- CONSTANTS & TYPES ----------------
28 : : ;; Market Types (2 => range based markets)
29 : : (define-constant MARKET_TYPE u2)
30 : :
31 : : ;; TODO Update resolve-market to reference correct pyth contract and remove local pyth from deployment
32 : : ;; PYTH_ORACLE 'STR738QQX1PVTM6WTDF833Z18T8R0ZB791TCNEFM.pyth-storage-v4
33 : : ;; PYTH_ORACLE 'SP1CGXWEAMG6P6FT04W66NVGJ7PQWMDAC19R7PJ0Y.pyth-oracle-v4
34 : :
35 : : (define-constant DEFAULT_MARKET_DURATION u144) ;; ~1 day in Bitcoin blocks
36 : : (define-constant DEFAULT_COOL_DOWN_PERIOD u144) ;; ~1 day in Bitcoin blocks
37 : : (define-constant SCALE u1000000)
38 : :
39 : : (define-constant RESOLUTION_OPEN u0)
40 : : (define-constant RESOLUTION_RESOLVING u1)
41 : : (define-constant RESOLUTION_DISPUTED u2)
42 : : (define-constant RESOLUTION_RESOLVED u3)
43 : :
44 : : (define-constant err-unauthorised (err u10000))
45 : : (define-constant err-invalid-market-type (err u10001))
46 : : (define-constant err-amount-too-low (err u10002))
47 : : (define-constant err-wrong-market-type (err u10003))
48 : : (define-constant err-already-concluded (err u10004))
49 : : (define-constant err-market-not-found (err u10005))
50 : : (define-constant err-user-not-winner-or-claimed (err u10006))
51 : : (define-constant err-user-not-staked (err u10008))
52 : : (define-constant err-market-not-concluded (err u10009))
53 : : (define-constant err-insufficient-balance (err u10011))
54 : : (define-constant err-insufficient-contract-balance (err u10012))
55 : : (define-constant err-user-share-is-zero (err u10013))
56 : : (define-constant err-disputer-must-have-stake (err u10015))
57 : : (define-constant err-dispute-window-elapsed (err u10016))
58 : : (define-constant err-market-not-resolving (err u10017))
59 : : (define-constant err-market-not-open (err u10018))
60 : : (define-constant err-dispute-window-not-elapsed (err u10019))
61 : : (define-constant err-market-wrong-state (err u10020))
62 : : (define-constant err-invalid-token (err u10021))
63 : : (define-constant err-max-market-fee-bips-exceeded (err u10022))
64 : : (define-constant err-category-not-found (err u10023))
65 : : (define-constant err-too-few-categories (err u10024))
66 : : (define-constant err-element-expected (err u10025))
67 : : (define-constant err-winning-stake-not-zero (err u10026))
68 : : (define-constant err-losing-stake-is-zero (err u10027))
69 : : (define-constant err-amount-too-high (err u10029))
70 : : (define-constant err-fee-too-high (err u10030))
71 : : (define-constant err-slippage-too-high (err u10031))
72 : : (define-constant err-seed-amount-not-divisible (err u10032))
73 : : (define-constant err-overbuy (err u10034))
74 : : (define-constant err-token-not-configured (err u10035))
75 : : (define-constant err-seed-too-small (err u10036))
76 : : (define-constant err-already-hedged (err u10037))
77 : : (define-constant err-hedging-disabled (err u10038))
78 : : (define-constant err-insufficient-liquidity (err u11041))
79 : : (define-constant err-arithmetic (err u11043))
80 : : (define-constant err-oracle-start-price (err u10039))
81 : : (define-constant err-band-not-set (err u10040))
82 : : (define-constant err-oracle-stale (err u10150))
83 : : (define-constant err-oracle-uncertain (err u10151))
84 : : (define-constant err-oracle-volatile (err u10152))
85 : : (define-constant err-oracle-no-fallback (err u10153))
86 : : (define-constant err-oracle-zero-price (err u10154))
87 : : (define-constant err-oracle-zero-delta (err u10155))
88 : : (define-constant err-invalid-param (err u10156))
89 : : (define-constant err-oracle-call-failed (err u10157))
90 : : (define-constant err-oracle-expo (err u10158))
91 : :
92 : : (define-constant marketplace .bme040-0-shares-marketplace)
93 : : (define-constant MIN_POOL u1)
94 : :
95 : : (define-data-var market-counter uint u0)
96 : : (define-data-var dispute-window-length uint u144)
97 : : (define-data-var dev-fee-bips uint u100)
98 : : (define-data-var market-fee-bips-max uint u1000)
99 : : (define-data-var dev-fund principal tx-sender)
100 : : (define-data-var resolution-agent principal tx-sender)
101 : : (define-data-var dao-treasury principal tx-sender)
102 : : (define-data-var creation-gated bool true)
103 : : (define-data-var resolution-timeout uint u1000) ;; 1000 blocks (~9 days)
104 : : (define-data-var default-hedge-executor principal .bme032-0-scalar-strategy-hedge)
105 : : (define-data-var hedging-enabled bool true)
106 : :
107 : : (define-data-var max-staleness-secs uint u900) ;; optional defense-in-depth
108 : : (define-data-var max-conf-bips uint u200) ;; 2%
109 : : (define-data-var max-move-bips uint u2000) ;; 20%
110 : :
111 : : ;; e.g. band-bips = 500 => 5.00%
112 : : (define-map price-band-widths {feed-id: (buff 32)} {band-bips: uint})
113 : : (define-map manual-fallback-price uint uint)
114 : :
115 : : ;; Data structure for each Market
116 : : ;; outcome: winning category
117 : : (define-map markets
118 : : uint
119 : : {
120 : : market-data-hash: (buff 32),
121 : : token: principal,
122 : : treasury: principal,
123 : : creator: principal,
124 : : market-fee-bips: uint,
125 : : resolution-state: uint, ;; "open", "resolving", "disputed", "concluded"
126 : : resolution-burn-height: uint,
127 : : categories: (list 6 {min: uint, max: uint}), ;; Min (inclusive) and Max (exclusive)
128 : : stakes: (list 10 uint), ;; Total staked per category - shares
129 : : stake-tokens: (list 10 uint), ;; Total staked per category - tokens
130 : : outcome: (optional uint),
131 : : concluded: bool,
132 : : market-start: uint,
133 : : market-duration: uint,
134 : : cool-down-period: uint,
135 : : hedge-executor: (optional principal),
136 : : hedged: bool,
137 : : price-feed-id: (buff 32), ;; Pyth price feed ID
138 : : price-outcome: (optional uint),
139 : : start-price: uint,
140 : : }
141 : : )
142 : : ;; defines the minimum liquidity a market creator needs to provide
143 : : (define-map token-minimum-seed {token: principal} uint)
144 : :
145 : : ;; tracks the amount of shares the user owns per market / category
146 : : (define-map stake-balances
147 : : { market-id: uint, user: principal }
148 : : (list 10 uint)
149 : : )
150 : : ;; tracks the cost of shares to the user per market / category
151 : : (define-map token-balances
152 : : { market-id: uint, user: principal }
153 : : (list 10 uint)
154 : : )
155 : : (define-map allowed-tokens principal bool)
156 : :
157 : : ;; ---------------- access control ----------------
158 : 300 : (define-public (is-dao-or-extension)
159 [ - ][ + - ]: 6303 : (ok (asserts! (or (is-eq tx-sender .bigmarket-dao) (contract-call? .bigmarket-dao is-extension contract-caller)) err-unauthorised))
160 : : )
161 : :
162 : : ;; ---------------- getters / setters ----------------
163 : 300 : (define-public (set-allowed-token (token principal) (enabled bool))
164 : 1200 : (begin
165 : 1200 : (try! (is-dao-or-extension))
166 : 1200 : (print {event: "allowed-token", token: token, enabled: enabled})
167 : 1200 : (ok (map-set allowed-tokens token enabled))
168 : : )
169 : : )
170 : 9 : (define-read-only (is-allowed-token (token principal))
171 : 13 : (default-to false (map-get? allowed-tokens token))
172 : : )
173 : :
174 : 300 : (define-public (set-dispute-window-length (length uint))
175 : 300 : (begin
176 : 300 : (try! (is-dao-or-extension))
177 : 300 : (var-set dispute-window-length length)
178 : 300 : (ok true)
179 : : )
180 : : )
181 : :
182 : 300 : (define-public (set-default-hedge-executor (p principal))
183 : 300 : (begin
184 : 300 : (try! (is-dao-or-extension))
185 : 300 : (var-set default-hedge-executor p)
186 : 300 : (print {event: "default-hedge-executor", default-hedge-executor: p})
187 : 300 : (ok true)
188 : : )
189 : : )
190 : :
191 : 0 : (define-public (set-hedging-enabled (enabled bool))
192 : 0 : (begin
193 : 0 : (try! (is-dao-or-extension))
194 : 0 : (var-set hedging-enabled enabled)
195 : 0 : (ok enabled)
196 : : )
197 : : )
198 : 0 : (define-read-only (is-hedging-enabled) (var-get hedging-enabled))
199 : :
200 : 300 : (define-public (set-price-band-width (feed-id (buff 32)) (band-bips uint))
201 : 1200 : (begin
202 : 1200 : (try! (is-dao-or-extension))
203 : 1200 : (map-set price-band-widths {feed-id: feed-id} {band-bips: band-bips})
204 : 1200 : (print {event: "price-band-width", feed-id: feed-id, precent: band-bips})
205 : 1200 : (ok true)
206 : : )
207 : : )
208 : 1 : (define-read-only (get-price-band-width (feed-id (buff 32)))
209 : 1 : (ok (map-get? price-band-widths {feed-id: feed-id}))
210 : : )
211 : :
212 : 300 : (define-public (set-creation-gated (gated bool))
213 : 300 : (begin
214 : 300 : (try! (is-dao-or-extension))
215 : 300 : (var-set creation-gated gated)
216 : 300 : (ok true)
217 : : )
218 : : )
219 : :
220 : 300 : (define-public (set-resolution-agent (new-agent principal))
221 : 300 : (begin
222 : 300 : (try! (is-dao-or-extension))
223 : 300 : (var-set resolution-agent new-agent)
224 : 300 : (ok true)
225 : : )
226 : : )
227 : :
228 : 300 : (define-public (set-dev-fee-bips (new-fee uint))
229 : 300 : (begin
230 [ - ]: 300 : (asserts! (<= new-fee u1000) err-max-market-fee-bips-exceeded)
231 : 300 : (try! (is-dao-or-extension))
232 : 300 : (var-set dev-fee-bips new-fee)
233 : 300 : (ok true)
234 : : )
235 : : )
236 : :
237 : 300 : (define-public (set-market-fee-bips-max (new-fee uint))
238 : 300 : (begin
239 [ - ]: 300 : (asserts! (<= new-fee u1000) err-max-market-fee-bips-exceeded)
240 : 300 : (try! (is-dao-or-extension))
241 : 300 : (var-set market-fee-bips-max new-fee)
242 : 300 : (ok true)
243 : : )
244 : : )
245 : :
246 : 300 : (define-public (set-token-minimum-seed (token principal) (min uint))
247 : 1200 : (begin
248 : 1200 : (try! (is-dao-or-extension))
249 : 1200 : (map-set token-minimum-seed {token: token} min)
250 : 1200 : (ok true)
251 : : )
252 : : )
253 : :
254 : 0 : (define-read-only (get-token-minimum-seed (seed-token principal))
255 : 0 : (ok (map-get? token-minimum-seed {token: seed-token}))
256 : : )
257 : :
258 : 300 : (define-public (set-dev-fund (new-dev-fund principal))
259 : 300 : (begin
260 : 300 : (try! (is-dao-or-extension))
261 : 300 : (var-set dev-fund new-dev-fund)
262 : 300 : (ok true)
263 : : )
264 : : )
265 : :
266 : 300 : (define-public (set-dao-treasury (new-dao-treasury principal))
267 : 300 : (begin
268 : 300 : (try! (is-dao-or-extension))
269 : 300 : (var-set dao-treasury new-dao-treasury)
270 : 300 : (ok true)
271 : : )
272 : : )
273 : :
274 : 300 : (define-public (set-max-staleness (secs uint))
275 : 300 : (begin
276 : 300 : (try! (is-dao-or-extension))
277 [ - ][ + + ]: 300 : (asserts! (and (> secs u60) (< secs u86400000)) err-invalid-param)
278 : 300 : (var-set max-staleness-secs secs)
279 : 300 : (ok true)
280 : : )
281 : : )
282 : :
283 : 0 : (define-public (set-max-conf-bips (bips uint))
284 : 0 : (begin
285 : 0 : (try! (is-dao-or-extension))
286 [ - ]: 0 : (asserts! (<= bips u1000) err-invalid-param)
287 : 0 : (var-set max-conf-bips bips)
288 : 0 : (ok true)
289 : : )
290 : : )
291 : :
292 : 0 : (define-public (set-max-move-bips (bips uint))
293 : 0 : (begin
294 : 0 : (try! (is-dao-or-extension))
295 [ - ]: 0 : (asserts! (<= bips u10000) err-invalid-param)
296 : 0 : (var-set max-move-bips bips)
297 : 0 : (ok true)
298 : : )
299 : : )
300 : :
301 : 0 : (define-read-only (get-market-data (market-id uint))
302 : 0 : (map-get? markets market-id)
303 : : )
304 : :
305 : 0 : (define-read-only (get-stake-balances (market-id uint) (user principal))
306 : 0 : (ok (default-to (list u0 u0 u0 u0 u0 u0 u0 u0 u0 u0) (map-get? stake-balances {market-id: market-id, user: user})))
307 : : )
308 : :
309 : 0 : (define-read-only (get-token-balances (market-id uint) (user principal))
310 : 0 : (ok (default-to (list u0 u0 u0 u0 u0 u0 u0 u0 u0 u0) (map-get? token-balances {market-id: market-id, user: user})))
311 : : )
312 : :
313 : : ;; ---------------- public functions ----------------
314 : :
315 : 9 : (define-public (create-market
316 : : (fee-bips (optional uint))
317 : : (token <ft-token>)
318 : : (market-data-hash (buff 32))
319 : : (proof (list 10 (tuple (position bool) (hash (buff 32)))))
320 : : (treasury principal)
321 : : (market-duration (optional uint))
322 : : (cool-down-period (optional uint))
323 : : (price-feed-id (buff 32))
324 : : (seed-amount uint)
325 : : (hedge-executor (optional principal))
326 : : )
327 : 13 : (let (
328 : 13 : (creator tx-sender)
329 : 13 : (new-id (var-get market-counter))
330 : 13 : (market-fee-bips (default-to u0 fee-bips))
331 : 13 : (market-duration-final (default-to DEFAULT_MARKET_DURATION market-duration))
332 : 13 : (cool-down-final (default-to DEFAULT_COOL_DOWN_PERIOD cool-down-period))
333 : 13 : (current-block burn-block-height)
334 : 13 : (start-price (try! (get-current-price-safe price-feed-id)))
335 : : ;;(start-price (match start-price-wrapped price price price u0))
336 : 13 : (band-bips (get band-bips (unwrap! (map-get? price-band-widths {feed-id: price-feed-id}) err-band-not-set)))
337 : :
338 : 13 : (delta (/ (* start-price band-bips) u10000))
339 : 13 : (categories (category-bands start-price delta))
340 : 13 : (num-categories (len categories))
341 : : ;; NOTE: seed is evenly divided with rounding error discarded
342 : 13 : (seed (/ (* seed-amount SCALE) (* num-categories SCALE)))
343 : 13 : (user-stake-list (list seed seed seed seed seed seed seed seed seed seed))
344 : 13 : (share-list (zero-after-n user-stake-list num-categories))
345 : : )
346 [ - ]: 13 : (asserts! (> start-price u0) err-oracle-zero-price)
347 [ - ]: 13 : (asserts! (> band-bips u0) err-band-not-set)
348 [ - ]: 13 : (asserts! (> delta u0) err-oracle-zero-delta)
349 [ - ]: 13 : (asserts! (> market-duration-final u10) err-market-not-found)
350 [ - ]: 13 : (asserts! (> cool-down-final u10) err-market-not-found)
351 : :
352 [ - ]: 13 : (asserts! (> (len categories) u1) err-too-few-categories)
353 [ - ]: 13 : (asserts! (<= market-fee-bips (var-get market-fee-bips-max)) err-max-market-fee-bips-exceeded)
354 : : ;; ensure the trading token is allowed
355 [ - ]: 13 : (asserts! (is-allowed-token (contract-of token)) err-invalid-token)
356 : :
357 : : ;; ensure enough liquidity
358 [ - ]: 13 : (asserts! (>= seed-amount (unwrap! (map-get? token-minimum-seed {token: (contract-of token)}) err-token-not-configured)) err-seed-too-small)
359 : : ;; liquidity floor guards (for CPMM safety)
360 [ - ]: 13 : (asserts! (>= seed MIN_POOL) err-insufficient-liquidity)
361 [ - ]: 13 : (asserts! (>= seed-amount (* num-categories MIN_POOL)) err-insufficient-liquidity) ;; avoid rounding below floor
362 : :
363 : : ;; Transfer single winning portion of seed to market contract to fund claims
364 : 13 : (try! (contract-call? token transfer seed-amount tx-sender (as-contract tx-sender) none))
365 : :
366 : : ;; ensure the user is allowed to create if gating by merkle proof is required
367 [ + - ]: 13 : (if (var-get creation-gated) (try! (as-contract (contract-call? .bme022-0-market-gating can-access-by-account creator proof))) true)
368 : :
369 : : ;; dao is assigned the seed liquidity - share and tokens 1:1 at kick off
370 : 13 : (map-set stake-balances {market-id: new-id, user: (var-get dao-treasury)} share-list)
371 : 13 : (map-set token-balances {market-id: new-id, user: (var-get dao-treasury)} share-list)
372 : :
373 : 13 : (map-set markets
374 : 13 : new-id
375 : : {
376 : 13 : market-data-hash: market-data-hash,
377 : 13 : token: (contract-of token),
378 : 13 : treasury: treasury,
379 : 13 : creator: creator,
380 : 13 : market-fee-bips: market-fee-bips,
381 : 13 : resolution-state: RESOLUTION_OPEN,
382 : 13 : resolution-burn-height: u0,
383 : 13 : categories: categories,
384 : 13 : stakes: share-list,
385 : 13 : stake-tokens: share-list, ;; they start out the same
386 : 13 : outcome: none,
387 : 13 : concluded: false,
388 : 13 : market-start: current-block,
389 : 13 : market-duration: market-duration-final,
390 : 13 : cool-down-period: cool-down-final,
391 : 13 : hedge-executor: hedge-executor,
392 : 13 : hedged: false,
393 : 13 : price-feed-id: price-feed-id,
394 : 13 : price-outcome: none,
395 : 13 : start-price: start-price
396 : : }
397 : : )
398 : 13 : (var-set market-counter (+ new-id u1))
399 : 13 : (try! (contract-call? .bme030-0-reputation-token mint tx-sender u2 u8))
400 : 13 : (print {event: "create-market", market-id: new-id, categories: categories, market-fee-bips: market-fee-bips, token: token, market-data-hash: market-data-hash, creator: tx-sender, seed-amount: seed-amount, start-price: start-price })
401 : 13 : (ok new-id)
402 : : )
403 : : )
404 : :
405 : : ;; Read-only: get current price to buy `amount` shares in a category
406 : 0 : (define-read-only (get-share-cost (market-id uint) (index uint) (amount-shares uint))
407 : 0 : (let (
408 : 0 : (market-data (unwrap-panic (map-get? markets market-id)))
409 : 0 : (stake-list (get stakes market-data))
410 : 0 : (selected-pool (unwrap-panic (element-at? stake-list index)))
411 : 0 : (total-pool (fold + stake-list u0))
412 : 0 : (other-pool (- total-pool selected-pool))
413 [ - - ]: 0 : (max-purchase (if (> other-pool MIN_POOL) (- other-pool MIN_POOL) u0))
414 : 0 : (cost (unwrap! (cpmm-cost selected-pool other-pool amount-shares) err-arithmetic))
415 : : )
416 : 0 : (ok { cost: cost, max-purchase: max-purchase })
417 : : )
418 : : )
419 : :
420 : : ;; Compute the token cost to buy `amount-shares` from `selected-pool`,
421 : : ;; given the rest-of-market liquidity `other-pool`.
422 : 4 : (define-private (cpmm-cost (selected-pool uint) (other-pool uint) (amount-shares uint))
423 : 8 : (begin
424 : : ;; Both pools must have liquidity
425 [ - ]: 8 : (asserts! (> selected-pool u0) err-insufficient-liquidity)
426 [ - ]: 8 : (asserts! (> other-pool u0) err-insufficient-liquidity)
427 : :
428 : : ;; You cannot buy so much that the counter-pool hits 0 or below MIN_POOL
429 : 8 : (let (
430 [ + - ]: 8 : (max-purchase (if (> other-pool MIN_POOL) (- other-pool MIN_POOL) u0))
431 : : )
432 [ - ]: 8 : (asserts! (<= amount-shares max-purchase) err-overbuy)
433 : :
434 : 8 : (let (
435 : 8 : (new-y (- other-pool amount-shares))
436 : 8 : (numerator (* selected-pool other-pool))
437 : 8 : (new-x (/ (* numerator SCALE) new-y))
438 : 8 : (cost (/ (- new-x (* selected-pool SCALE)) SCALE))
439 : : )
440 : 8 : (ok cost)
441 : : )
442 : : )
443 : : )
444 : : )
445 : :
446 : : ;; Read-only: get current price to buy `amount` shares in a category
447 : 0 : (define-read-only (get-max-shares (market-id uint) (index uint) (total-cost uint))
448 : 0 : (let (
449 : 0 : (fee-scaled (/ (* (* total-cost (var-get dev-fee-bips)) SCALE) u10000))
450 : 0 : (fee (/ fee-scaled SCALE))
451 [ - - ]: 0 : (cost-of-shares (if (> total-cost fee) (- total-cost fee) u0))
452 : 0 : (market-data (unwrap-panic (map-get? markets market-id)))
453 : 0 : (stake-list (get stakes market-data))
454 : 0 : (selected-pool (unwrap-panic (element-at? stake-list index)))
455 : 0 : (total-pool (fold + stake-list u0))
456 : 0 : (other-pool (- total-pool selected-pool))
457 [ - - ]: 0 : (max-by-floor (if (> other-pool MIN_POOL) (- other-pool MIN_POOL) u0))
458 : 0 : (shares (unwrap! (cpmm-shares selected-pool other-pool cost-of-shares) err-arithmetic))
459 [ - - ]: 0 : (shares-clamped (if (> shares max-by-floor) max-by-floor shares))
460 : : )
461 : 0 : (ok { shares: shares-clamped, fee: fee, cost-of-shares: cost-of-shares })
462 : : )
463 : : )
464 : : ;; Inverse: given a token `cost`, how many shares can be bought safely?
465 : 4 : (define-private (cpmm-shares (selected-pool uint) (other-pool uint) (cost uint))
466 : 8 : (begin
467 [ - ]: 8 : (asserts! (> selected-pool u0) err-insufficient-liquidity)
468 [ - ]: 8 : (asserts! (> other-pool u0) err-insufficient-liquidity)
469 : :
470 : 8 : (if (is-eq cost u0)
471 [ - ]: 0 : (ok u0)
472 [ + ]: 8 : (let (
473 : 8 : (denom (+ selected-pool cost)) ;; > selected-pool, non-zero
474 : 8 : (numerator (* selected-pool other-pool))
475 : 8 : (new-y (/ (* numerator SCALE) denom))
476 : 8 : (raw-shares (if (> (* other-pool SCALE) new-y)
477 [ + ]: 8 : (/ (- (* other-pool SCALE) new-y) SCALE)
478 [ - ]: 0 : u0))
479 : : ;; Enforce floor: clamp to keep MIN_POOL on the other side
480 [ + - ]: 8 : (max-by-floor (if (> other-pool MIN_POOL) (- other-pool MIN_POOL) u0))
481 [ - + ]: 8 : (shares (if (> raw-shares max-by-floor) max-by-floor raw-shares))
482 : : )
483 : 8 : (ok shares)
484 : : )
485 : : )
486 : : )
487 : : )
488 : : ;; Predict category with CPMM pricing
489 : 5 : (define-public (predict-category (market-id uint) (min-shares uint) (index uint) (token <ft-token>) (max-cost uint))
490 : 9 : (let (
491 : 9 : (md (unwrap! (map-get? markets market-id) err-market-not-found))
492 : 9 : (categories (get categories md))
493 : 9 : (stake-tokens-list (get stake-tokens md))
494 : 9 : (selected-token-pool (unwrap! (element-at? stake-tokens-list index) err-category-not-found))
495 : 8 : (stake-list (get stakes md))
496 : 8 : (selected-pool (unwrap! (element-at? stake-list index) err-category-not-found))
497 : 8 : (total-pool (fold + stake-list u0))
498 : 8 : (other-pool (- total-pool selected-pool))
499 : 8 : (sender-balance (unwrap! (contract-call? token get-balance tx-sender) err-insufficient-balance))
500 : 8 : (fee (/ (* max-cost (var-get dev-fee-bips)) u10000))
501 [ + - ]: 8 : (cost-of-shares (if (> max-cost fee) (- max-cost fee) u0))
502 [ + - ]: 8 : (max-by-floor (if (> other-pool MIN_POOL) (- other-pool MIN_POOL) u0))
503 : 8 : (amount-shares (unwrap! (cpmm-shares selected-pool other-pool cost-of-shares) err-insufficient-balance))
504 : 8 : (max-cost-of-shares (unwrap! (cpmm-cost selected-pool other-pool max-by-floor) err-overbuy))
505 [ + - ]: 8 : (max-purchase (if (> other-pool u0) (- other-pool u1) u0))
506 : 8 : (market-end (+ (get market-start md) (get market-duration md)))
507 : : )
508 : : ;; Validate token and market state
509 [ - ]: 8 : (asserts! (< index (len categories)) err-category-not-found)
510 [ - ]: 8 : (asserts! (is-eq (get token md) (contract-of token)) err-invalid-token)
511 [ - ]: 8 : (asserts! (not (get concluded md)) err-market-not-concluded)
512 [ - ]: 8 : (asserts! (is-eq (get resolution-state md) RESOLUTION_OPEN) err-market-not-open)
513 [ - ]: 8 : (asserts! (>= max-cost u100) err-amount-too-low)
514 [ - ]: 8 : (asserts! (>= sender-balance max-cost) err-insufficient-balance)
515 [ - ]: 8 : (asserts! (<= max-cost u50000000000000) err-amount-too-high)
516 [ - ]: 8 : (asserts! (< burn-block-height market-end) err-market-not-open)
517 : : ;; ensure the user cannot overpay for shares - this can skew liquidity in other pools
518 [ - ]: 8 : (asserts! (<= cost-of-shares max-cost-of-shares) err-overbuy)
519 [ - ]: 8 : (asserts! (< amount-shares other-pool) err-overbuy)
520 [ - ]: 8 : (asserts! (>= amount-shares min-shares) err-slippage-too-high)
521 [ - ]: 8 : (asserts! (> other-pool u0) err-insufficient-liquidity)
522 [ - ]: 8 : (asserts! (<= amount-shares max-by-floor) err-overbuy)
523 : :
524 : : ;; --- Token Transfers ---
525 : 8 : (try! (contract-call? token transfer cost-of-shares tx-sender (as-contract tx-sender) none))
526 : 8 : (if (> fee u0)
527 [ + ]: 8 : (try! (contract-call? token transfer fee tx-sender (var-get dev-fund) none))
528 [ - ]: 0 : true
529 : : )
530 : :
531 : : ;; --- Update Market State ---
532 : 7 : (let (
533 : 7 : (updated-stakes (unwrap! (replace-at? stake-list index (+ selected-pool amount-shares)) err-category-not-found))
534 : 7 : (updated-token-stakes (unwrap! (replace-at? stake-tokens-list index (+ selected-token-pool cost-of-shares)) err-category-not-found))
535 : : )
536 : 7 : (map-set markets market-id (merge md {stakes: updated-stakes, stake-tokens: updated-token-stakes}))
537 : : )
538 : :
539 : : ;; --- Update User Balances ---
540 : 7 : (let (
541 : 7 : (current-token-balances (default-to (list u0 u0 u0 u0 u0 u0 u0 u0 u0 u0) (map-get? token-balances {market-id: market-id, user: tx-sender})))
542 : 7 : (token-current (unwrap! (element-at? current-token-balances index) err-category-not-found))
543 : 7 : (user-token-updated (unwrap! (replace-at? current-token-balances index (+ token-current cost-of-shares)) err-category-not-found))
544 : :
545 : 7 : (current-stake-balances (default-to (list u0 u0 u0 u0 u0 u0 u0 u0 u0 u0) (map-get? stake-balances {market-id: market-id, user: tx-sender})))
546 : 7 : (user-current (unwrap! (element-at? current-stake-balances index) err-category-not-found))
547 : 7 : (user-stake-updated (unwrap! (replace-at? current-stake-balances index (+ user-current amount-shares)) err-category-not-found))
548 : : )
549 : 7 : (map-set stake-balances {market-id: market-id, user: tx-sender} user-stake-updated)
550 : 7 : (map-set token-balances {market-id: market-id, user: tx-sender} user-token-updated)
551 : 7 : (print {event: "market-stake", market-id: market-id, index: index, amount: amount-shares, cost: cost-of-shares, fee: fee, voter: tx-sender, max-cost: max-cost})
552 : 7 : (ok index)
553 : : )
554 : : )
555 : : )
556 : :
557 : : ;; Resolve a market invoked by ai-agent.
558 : 1 : (define-public (resolve-market (market-id uint))
559 : 3 : (let (
560 : 3 : (md (unwrap! (map-get? markets market-id) err-market-not-found))
561 : 3 : (market-end (+ (get market-start md) (get market-duration md)))
562 : 3 : (market-close (+ market-end (get cool-down-period md)))
563 : 3 : (feed-id (get price-feed-id md))
564 : 3 : (start (get start-price md))
565 : 3 : (price-oracle (get-current-price-safe feed-id)) ;; uses v4 now
566 : :
567 : 0 : (price-final
568 : 3 : (unwrap!
569 : 3 : (match price-oracle
570 : : ;; OK branch from oracle
571 : : p
572 [ + ]: 3 : (let (
573 [ - + ]: 3 : (delta (if (> p start) (- p start) (- start p)))
574 [ + - ]: 3 : (move-bips (if (> start u0) (/ (* delta u10000) start) u10000))
575 : : )
576 : 3 : (if (<= move-bips (var-get max-move-bips))
577 [ + ]: 3 : (ok p) ;; accept oracle price
578 [ - ]: 0 : (get-manual-fallback market-id) ;; too volatile -> fallback
579 : : )
580 : : )
581 : : ;; ERR branch from oracle
582 : : e
583 [ - ]: 0 : (get-manual-fallback market-id) ;; oracle failed -> fallback
584 : : )
585 : 3 : err-oracle-no-fallback ;; unwrap! error if no manual fallback set
586 : : )
587 : : )
588 : :
589 : :
590 : 3 : (categories (get categories md))
591 : 3 : (first-category (unwrap! (element-at? categories u0) err-category-not-found))
592 : 0 : (winning-category-index
593 : 3 : (get winning-index
594 : 3 : (fold select-winner-pyth categories
595 : 3 : {current-index: u0, winning-index: none, price: price-final})))
596 : 0 : (final-index
597 : 3 : (if (is-some winning-category-index)
598 [ + ]: 3 : winning-category-index
599 [ - ]: 0 : (if (< price-final (get min first-category))
600 [ - ]: 0 : (some u0)
601 [ - ]: 0 : (some (- (len categories) u1)))))
602 : : )
603 [ - ][ + - ]: 3 : (asserts! (or (is-eq tx-sender (var-get resolution-agent)) (is-eq tx-sender (get creator md))) err-unauthorised)
604 [ - ]: 3 : (asserts! (>= burn-block-height market-close) err-market-wrong-state)
605 [ + ]: 3 : (asserts! (is-eq (get resolution-state md) RESOLUTION_OPEN) err-market-wrong-state)
606 [ - ]: 1 : (asserts! (is-some final-index) err-category-not-found)
607 : :
608 : 1 : (map-set markets market-id
609 : 1 : (merge md
610 : 1 : { outcome: final-index, price-outcome: (some price-final), resolution-state: RESOLUTION_RESOLVING, resolution-burn-height: burn-block-height }))
611 : 1 : (print {event: "resolve-market", market-id: market-id, outcome: final-index, price: price-final})
612 : 1 : (ok final-index)
613 : : )
614 : : )
615 : :
616 : 0 : (define-public (execute-hedge (market-id uint) (hedge-executor <hedge-trait>) (token0 <ft-velar-token>) (token1 <ft-velar-token>) (token-in <ft-velar-token>) (token-out <ft-velar-token>) )
617 : 0 : (let (
618 : 0 : (md (unwrap! (map-get? markets market-id) err-market-not-found))
619 : 0 : (feed-id (get price-feed-id md))
620 : 0 : (hedged (get hedged md))
621 : 0 : (market-end (+ (get market-start md) (get market-duration md)))
622 : 0 : (stored-hedge-executor (default-to (var-get default-hedge-executor) (get hedge-executor md)))
623 : 0 : (predicted (get-biggest-pool-index (get stakes md)))
624 : : )
625 : : ;; check hedging allowed
626 [ - ]: 0 : (asserts! (var-get hedging-enabled) err-hedging-disabled)
627 : : ;; Ensure caller is the same contract that's stored
628 [ - ]: 0 : (asserts! (not hedged) err-already-hedged)
629 [ - ]: 0 : (asserts! (is-eq (contract-of hedge-executor) stored-hedge-executor) err-unauthorised)
630 : :
631 : : ;; Time window check
632 [ - ]: 0 : (asserts! (>= burn-block-height market-end) err-market-wrong-state)
633 [ - ]: 0 : (asserts! (< burn-block-height (+ market-end (get cool-down-period md))) err-market-wrong-state)
634 : :
635 : : ;; Compute crowd-predicted outcome
636 : 0 : (try! (contract-call? hedge-executor perform-swap-hedge market-id predicted feed-id token0 token1 token-in token-out))
637 : 0 : (map-set markets market-id (merge md {hedged: true}))
638 : 0 : (print {event: "hedge-action", market-id: market-id, predicted: predicted})
639 : 0 : (ok predicted)
640 : : )
641 : : )
642 : :
643 : 0 : (define-public (resolve-market-undisputed (market-id uint))
644 : 0 : (let (
645 : 0 : (md (unwrap! (map-get? markets market-id) err-market-not-found))
646 : : )
647 [ - ]: 0 : (asserts! (> burn-block-height (+ (get resolution-burn-height md) (var-get dispute-window-length))) err-dispute-window-not-elapsed)
648 [ - ]: 0 : (asserts! (is-eq (get resolution-state md) RESOLUTION_RESOLVING) err-market-not-open)
649 : :
650 : 0 : (map-set markets market-id
651 : 0 : (merge md
652 : 0 : { concluded: true, resolution-state: RESOLUTION_RESOLVED, resolution-burn-height: burn-block-height }
653 : : )
654 : : )
655 : 0 : (print {event: "resolve-market-undisputed", market-id: market-id, resolution-burn-height: burn-block-height, resolution-state: RESOLUTION_RESOLVED})
656 : 0 : (ok true)
657 : : )
658 : : )
659 : :
660 : : ;; concludes a market that has been disputed. This method has to be called at least
661 : : ;; dispute-window-length blocks after the dispute was raised - the voting window.
662 : : ;; a proposal with 0 votes will close the market with the outcome false
663 : 0 : (define-public (resolve-market-vote (market-id uint) (outcome uint))
664 : 0 : (let (
665 : 0 : (md (unwrap! (map-get? markets market-id) err-market-not-found))
666 : : )
667 : 0 : (try! (is-dao-or-extension))
668 [ - ]: 0 : (asserts! (< outcome (len (get categories md))) err-market-not-found)
669 [ - ][ - - ]: 0 : (asserts! (or (is-eq (get resolution-state md) RESOLUTION_DISPUTED) (is-eq (get resolution-state md) RESOLUTION_RESOLVING)) err-market-wrong-state)
670 : :
671 : 0 : (map-set markets market-id
672 : 0 : (merge md
673 : 0 : { concluded: true, outcome: (some outcome), resolution-state: RESOLUTION_RESOLVED }
674 : : )
675 : : )
676 : 0 : (print {event: "resolve-market-vote", market-id: market-id, resolver: contract-caller, outcome: outcome, resolution-state: RESOLUTION_RESOLVED})
677 : 0 : (ok true)
678 : : )
679 : : )
680 : :
681 : : ;; Allows a user with a stake in market to contest the resolution
682 : : ;; the call is made via the voting contract 'create-market-vote' function
683 : 0 : (define-public (dispute-resolution (market-id uint) (disputer principal) (num-categories uint))
684 : 0 : (let (
685 : 0 : (md (unwrap! (map-get? markets market-id) err-market-not-found))
686 : : ;; ensure user has a stake
687 : 0 : (stake-data (unwrap! (map-get? stake-balances { market-id: market-id, user: disputer }) err-disputer-must-have-stake))
688 : : )
689 : : ;; user call create-market-vote in the voting contract to start a dispute
690 : 0 : (try! (is-dao-or-extension))
691 : :
692 [ - ]: 0 : (asserts! (is-eq num-categories (len (get categories md))) err-too-few-categories)
693 : : ;; prevent market getting locked in unresolved state
694 [ - ]: 0 : (asserts! (<= burn-block-height (+ (get resolution-burn-height md) (var-get dispute-window-length))) err-dispute-window-elapsed)
695 : :
696 [ - ]: 0 : (asserts! (is-eq (get resolution-state md) RESOLUTION_RESOLVING) err-market-not-resolving)
697 : :
698 : 0 : (map-set markets market-id
699 : 0 : (merge md { resolution-state: RESOLUTION_DISPUTED }))
700 : 0 : (print {event: "dispute-resolution", market-id: market-id, disputer: disputer, resolution-state: RESOLUTION_DISPUTED})
701 : 0 : (ok true)
702 : : )
703 : : )
704 : 0 : (define-public (force-resolve-market (market-id uint))
705 : 0 : (let (
706 : 0 : (md (unwrap! (map-get? markets market-id) err-market-not-found))
707 : 0 : (elapsed (- burn-block-height (get resolution-burn-height md)))
708 : : )
709 : 0 : (begin
710 [ - ]: 0 : (asserts! (> elapsed (var-get resolution-timeout)) err-market-wrong-state)
711 [ - ]: 0 : (asserts! (is-eq (get resolution-state md) RESOLUTION_DISPUTED) err-market-wrong-state)
712 : :
713 : 0 : (map-set markets market-id
714 : 0 : (merge md { resolution-state: RESOLUTION_RESOLVED, concluded: true })
715 : : )
716 : 0 : (print {event: "force-resolve", market-id: market-id, resolution-state: RESOLUTION_RESOLVED})
717 : 0 : (ok true)
718 : : ))
719 : : )
720 : :
721 : : ;; Proportional payout with market fee only
722 : 0 : (define-public (claim-winnings (market-id uint) (token <ft-token>))
723 : 0 : (let (
724 : 0 : (md (unwrap! (map-get? markets market-id) err-market-not-found))
725 : 0 : (index-won (unwrap! (get outcome md) err-market-not-concluded))
726 : 0 : (marketfee-bips (get market-fee-bips md))
727 : 0 : (treasury (get treasury md))
728 : 0 : (original-sender tx-sender)
729 : :
730 : : ;; user may have acquired shares via p2p and so have no entry under token-balances
731 : 0 : (user-token-list (default-to (list u0 u0 u0 u0 u0 u0 u0 u0 u0 u0) (map-get? token-balances {market-id: market-id, user: tx-sender})))
732 : 0 : (user-tokens (unwrap! (element-at? user-token-list index-won) err-user-not-staked))
733 : :
734 : 0 : (user-stake-list (unwrap! (map-get? stake-balances {market-id: market-id, user: tx-sender}) err-user-not-staked))
735 : 0 : (user-shares (unwrap! (element-at? user-stake-list index-won) err-user-not-staked))
736 : :
737 : 0 : (stake-list (get stakes md))
738 : 0 : (winning-pool (unwrap! (element-at? stake-list index-won) err-market-not-concluded))
739 : 0 : (total-share-pool (fold + stake-list u0))
740 : :
741 : 0 : (staked-tokens (get stake-tokens md))
742 : 0 : (total-token-pool (fold + staked-tokens u0))
743 : :
744 : : ;; CPMM Payout: the proportion of the total tokens staked to the shares won
745 : 0 : (gross-refund-scaled (if (> winning-pool u0)
746 [ - ]: 0 : (/ (* (* user-shares total-token-pool) SCALE) winning-pool)
747 [ - ]: 0 : u0))
748 : 0 : (gross-refund (/ gross-refund-scaled SCALE))
749 : :
750 : 0 : (marketfee (/ (* gross-refund marketfee-bips) u10000))
751 : 0 : (net-refund (- gross-refund marketfee))
752 : : )
753 : : ;; Check resolved and non zero payout
754 [ - ]: 0 : (asserts! (is-eq (get resolution-state md) RESOLUTION_RESOLVED) err-market-not-concluded)
755 [ - ]: 0 : (asserts! (get concluded md) err-market-not-concluded)
756 [ - ]: 0 : (asserts! (> user-shares u0) err-user-not-winner-or-claimed)
757 [ - ]: 0 : (asserts! (> winning-pool u0) err-amount-too-low)
758 [ - ]: 0 : (asserts! (> net-refund u0) err-user-share-is-zero)
759 : :
760 : : ;; Transfer winnings and market fee
761 : 0 : (as-contract
762 : 0 : (begin
763 : 0 : (if (> marketfee u0)
764 [ - ]: 0 : (try! (contract-call? token transfer marketfee tx-sender treasury none))
765 [ - ]: 0 : true
766 : : )
767 : 0 : (try! (contract-call? token transfer net-refund tx-sender original-sender none))
768 : : )
769 : : )
770 : :
771 : : ;; Zero out stake
772 : 0 : (map-set token-balances {market-id: market-id, user: tx-sender} (list u0 u0 u0 u0 u0 u0 u0 u0 u0 u0))
773 : 0 : (map-set stake-balances {market-id: market-id, user: tx-sender} (list u0 u0 u0 u0 u0 u0 u0 u0 u0 u0))
774 : 0 : (try! (contract-call? .bme030-0-reputation-token mint tx-sender u1 u10))
775 : 0 : (print {event: "claim-winnings", market-id: market-id, index-won: index-won, claimer: tx-sender, user-tokens: user-tokens, user-shares: user-shares, refund: net-refund, marketfee: marketfee, winning-pool: winning-pool, total-pool: total-share-pool})
776 : 0 : (ok net-refund)
777 : : )
778 : : )
779 : :
780 : 0 : (define-read-only (get-expected-payout (market-id uint) (index uint) (user principal))
781 : 0 : (let (
782 : 0 : (md (unwrap-panic (map-get? markets market-id)))
783 : :
784 : 0 : (token-pool (fold + (get stake-tokens md) u0))
785 : :
786 : 0 : (user-shares-list (unwrap-panic (map-get? stake-balances {market-id: market-id, user: user})))
787 : 0 : (user-shares (unwrap-panic (element-at? user-shares-list index)))
788 : :
789 : 0 : (winning-shares-pool (unwrap-panic (element-at? (get stakes md) index)))
790 : :
791 : 0 : (marketfee-bips (get market-fee-bips md))
792 [ - - ]: 0 : (gross-refund (if (> winning-shares-pool u0) (/ (* user-shares token-pool) winning-shares-pool) u0))
793 : 0 : (marketfee (/ (* gross-refund marketfee-bips) u10000))
794 : 0 : (net-refund (- gross-refund marketfee))
795 : : )
796 [ - - - ]: 0 : (if (and (> user-shares u0) (> winning-shares-pool u0) (> net-refund u0))
797 [ - ]: 0 : (ok { net-refund: net-refund, marketfee: marketfee-bips })
798 [ - ]: 0 : (err u1) ;; not eligible or payout = 0
799 : : )
800 : : )
801 : : )
802 : :
803 : : ;; marketplace transfer function to move shares - dao extension callable
804 : : ;; note - an automated dao function that fulfils orders functions as a 'sell-shares' feature
805 : 0 : (define-public (transfer-shares
806 : : (market-id uint)
807 : : (outcome uint)
808 : : (seller principal)
809 : : (buyer principal)
810 : : (amount uint)
811 : : (token <ft-token>)
812 : : )
813 : 0 : (let (
814 : 0 : (md (unwrap! (map-get? markets market-id) err-market-not-found))
815 : 0 : (stake-list (get stakes md))
816 : 0 : (market-token (get token md))
817 : 0 : (selected-pool (unwrap! (element-at? stake-list outcome) err-category-not-found))
818 : 0 : (other-pools (- (fold + stake-list u0) selected-pool))
819 : :
820 : : ;; Pricing
821 : 0 : (price (unwrap! (cpmm-cost selected-pool other-pools amount) err-overbuy))
822 : 0 : (marketfee-bips (get market-fee-bips md))
823 : 0 : (treasury (get treasury md))
824 : 0 : (fee (/ (* price marketfee-bips) u10000))
825 : 0 : (net-price (- price fee))
826 : 0 : (reduced-fee (/ fee u2))
827 : :
828 : : ;; Share balances
829 : 0 : (seller-balances (unwrap! (map-get? stake-balances {market-id: market-id, user: seller}) err-user-not-staked))
830 : 0 : (seller-shares (unwrap! (element-at? seller-balances outcome) err-user-not-staked))
831 : 0 : (buyer-balances (default-to (list u0 u0 u0 u0 u0 u0 u0 u0 u0 u0) (map-get? stake-balances {market-id: market-id, user: buyer})))
832 : 0 : (buyer-shares (unwrap! (element-at? buyer-balances outcome) err-category-not-found))
833 : : )
834 : : ;; dao extension callable only
835 : 0 : (try! (is-dao-or-extension))
836 : : ;; Ensure seller has enough shares
837 [ - ]: 0 : (asserts! (>= seller-shares amount) err-user-share-is-zero)
838 [ - ]: 0 : (asserts! (is-eq market-token (contract-of token)) err-invalid-token)
839 [ - ]: 0 : (asserts! (is-eq (get resolution-state md) RESOLUTION_OPEN) err-market-wrong-state)
840 : :
841 : : ;; Perform share transfer
842 : : ;; Note: we do not update `stakes` here because total pool liquidity remains unchanged.
843 : 0 : (let (
844 : 0 : (buyer-updated (unwrap! (replace-at? buyer-balances outcome (+ buyer-shares amount)) err-category-not-found))
845 : 0 : (seller-updated (unwrap! (replace-at? seller-balances outcome (- seller-shares amount)) err-category-not-found))
846 : : )
847 : : ;; Update state
848 : 0 : (map-set stake-balances {market-id: market-id, user: buyer} buyer-updated)
849 : 0 : (map-set stake-balances {market-id: market-id, user: seller} seller-updated)
850 : :
851 : : ;; Transfer cost and fee from buyer to seller
852 : 0 : (begin
853 : 0 : (if (> reduced-fee u0)
854 : : ;; buyer pays reduced fee as p2p incentive
855 [ - ]: 0 : (try! (contract-call? token transfer reduced-fee buyer treasury none))
856 [ - ]: 0 : true
857 : : )
858 : 0 : (try! (contract-call? token transfer net-price buyer seller none))
859 : : )
860 : 0 : (print {event: "transfer-shares", market-id: market-id, outcome: outcome, buyer: buyer, seller: seller, amount: amount, price: net-price, fee: fee })
861 : 0 : (ok price)
862 : : )
863 : : )
864 : : )
865 : :
866 : : ;; Helper function to create a list with zeros after index N
867 : 9 : (define-private (zero-after-n (original-list (list 10 uint)) (n uint))
868 : 13 : (let (
869 [ + - ]: 13 : (element-0 (if (<= u0 n) (unwrap-panic (element-at? original-list u0)) u0))
870 [ + - ]: 13 : (element-1 (if (< u1 n) (unwrap-panic (element-at? original-list u1)) u0))
871 [ + - ]: 13 : (element-2 (if (< u2 n) (unwrap-panic (element-at? original-list u2)) u0))
872 [ + - ]: 13 : (element-3 (if (< u3 n) (unwrap-panic (element-at? original-list u3)) u0))
873 [ + - ]: 13 : (element-4 (if (< u4 n) (unwrap-panic (element-at? original-list u4)) u0))
874 [ + - ]: 13 : (element-5 (if (< u5 n) (unwrap-panic (element-at? original-list u5)) u0))
875 [ - + ]: 13 : (element-6 (if (< u6 n) (unwrap-panic (element-at? original-list u6)) u0))
876 [ - + ]: 13 : (element-7 (if (< u7 n) (unwrap-panic (element-at? original-list u7)) u0))
877 [ - + ]: 13 : (element-8 (if (< u8 n) (unwrap-panic (element-at? original-list u8)) u0))
878 [ - + ]: 13 : (element-9 (if (< u9 n) (unwrap-panic (element-at? original-list u9)) u0))
879 : : )
880 : 13 : (list element-0 element-1 element-2 element-3 element-4 element-5 element-6 element-7 element-8 element-9)
881 : : )
882 : : )
883 : :
884 : 0 : (define-private (get-biggest-pool-index (lst (list 10 uint)))
885 : 0 : (get index
886 : 0 : (fold find-max-helper
887 : 0 : lst
888 : 0 : { max-val: u0, index: u0, current-index: u0 }))
889 : : )
890 : :
891 : 0 : (define-private (find-max-helper (val uint) (state { max-val: uint, index: uint, current-index: uint }))
892 : : {
893 [ - - ]: 0 : max-val: (if (> val (get max-val state)) val (get max-val state)),
894 [ - - ]: 0 : index: (if (> val (get max-val state)) (get current-index state) (get index state)),
895 : 0 : current-index: (+ (get current-index state) u1)
896 : : }
897 : : )
898 : :
899 : 9 : (define-private (category-bands (start-price uint) (delta uint))
900 : 13 : (let (
901 : : ;; Symmetric bands around start-price
902 : 13 : (element-0 {min: u0, max: (- start-price (* delta u2))}) ;; big loss
903 : 13 : (element-1 {min: (- start-price (* delta u2)), max: (- start-price delta)}) ;; small loss
904 : 13 : (element-2 {min: (- start-price delta), max: start-price}) ;; slight loss
905 : 13 : (element-3 {min: start-price, max: (+ start-price delta)}) ;; slight gain
906 : 13 : (element-4 {min: (+ start-price delta), max: (+ start-price (* delta u2))}) ;; small gain
907 : 13 : (element-5 {min: (+ start-price (* delta u2)), max: u4294967295}) ;; big gain
908 : : )
909 : 13 : (list element-0 element-1 element-2 element-3 element-4 element-5)
910 : : )
911 : : )
912 : :
913 : 9 : (define-private (get-current-price-safe (feed-id (buff 32)))
914 : 16 : (let (
915 : 16 : (d (unwrap! (contract-call? .pyth-oracle-v4 get-price feed-id .pyth-storage-v4) err-oracle-call-failed))
916 : 16 : (raw-price (to-uint (abs-int (get price d))))
917 : 16 : (raw-conf (get conf d)) ;; uint
918 : 16 : (expo (get expo d)) ;; int
919 : 16 : (ts (get publish-time d)) ;; uint (not optional)
920 : 16 : (price (scale-pyth raw-price expo)) ;; -> uint
921 : 16 : (conf (scale-pyth raw-conf expo)) ;; -> uint
922 [ + - ]: 16 : (conf-bips (if (> price u0) (/ (* conf u10000) price) u10000))
923 : 16 : (now (now-seconds))
924 : : )
925 : 16 : (begin
926 [ - ]: 16 : (asserts! (> price u0) err-oracle-zero-price)
927 [ - ]: 16 : (asserts! (< (abs-int expo) 20) err-oracle-expo)
928 : : ;; confidence bound
929 [ - ]: 16 : (asserts! (<= conf-bips (var-get max-conf-bips)) err-oracle-uncertain)
930 : : ;; freshness check in seconds
931 : : ;;(asserts! (<= (- now ts) (var-get max-staleness-secs)) err-oracle-stale)
932 : 16 : (ok price)
933 : : )
934 : : )
935 : : )
936 : :
937 : 1 : (define-private (select-winner-pyth
938 : : (category (tuple (min uint) (max uint)))
939 : : (acc {current-index: uint, winning-index: (optional uint), price: uint}))
940 : 18 : (let (
941 : 18 : (price (get price acc))
942 : 18 : (min-price (get min category))
943 : 18 : (max-price (get max category))
944 : 18 : (current-index (get current-index acc))
945 : : )
946 : : ;; Check if the price falls within this category's range
947 [ + + + ]: 18 : (if (and (>= price min-price) (< price max-price) (is-none (get winning-index acc)))
948 : 3 : {current-index: (+ current-index u1), winning-index: (some current-index), price: price}
949 : 15 : {current-index: (+ current-index u1), winning-index: (get winning-index acc), price: price}
950 : : )
951 : : )
952 : : )
953 : :
954 : 1 : (define-public (set-manual-price (market-id uint) (price uint))
955 : 3 : (begin
956 : 3 : (try! (is-dao-or-extension))
957 : 3 : (map-set manual-fallback-price market-id price)
958 : 3 : (ok true)
959 : : )
960 : : )
961 : :
962 : : ;; Pyth v4 and audit updates
963 : :
964 : 9 : (define-read-only (abs-int (x int))
965 [ + + ]: 96 : (if (< x 0) (- 0 x) x)
966 : : )
967 : :
968 : 9 : (define-private (scale-pyth (val uint) (expo int)) ;; -> uint
969 : 32 : (let ((v-abs (abs-int (to-int val))))
970 : 32 : (if (< expo 0)
971 : : ;; multiply for negative exponent
972 [ + ]: 32 : (to-uint (* v-abs (to-int (pow u10 (to-uint (abs-int expo))))))
973 : : ;; divide for positive exponent
974 [ - ]: 0 : (to-uint (/ v-abs (to-int (pow u10 (to-uint expo))))))
975 : : )
976 : : )
977 : :
978 : 9 : (define-read-only (now-seconds)
979 : 16 : (unwrap-panic (get-stacks-block-info? time (- stacks-block-height u1)))
980 : : )
981 : :
982 : 0 : (define-private (get-manual-fallback (market-id uint))
983 : 0 : (match (map-get? manual-fallback-price market-id)
984 [ - ]: 0 : price (ok price)
985 [ - ]: 0 : (err err-oracle-no-fallback)
986 : : )
987 : : )
988 : :
|