/
create-market.ts
590 lines (526 loc) · 15.6 KB
/
create-market.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
import * as admin from 'firebase-admin'
import { FieldValue, Transaction } from 'firebase-admin/firestore'
import { getCpmmInitialLiquidityTxn } from 'common/antes'
import {
add_answers_mode,
Contract,
CPMMBinaryContract,
CPMMMultiContract,
CPMMNumericContract,
MULTI_NUMERIC_CREATION_ENABLED,
NO_CLOSE_TIME_TYPES,
OutcomeType,
} from 'common/contract'
import { getAnte } from 'common/economy'
import { getNewContract } from 'common/new-contract'
import { getPseudoProbability } from 'common/pseudo-numeric'
import { marketCreationCosts, User } from 'common/user'
import { randomString } from 'common/util/random'
import { slugify } from 'common/util/slugify'
import { getCloseDate } from 'shared/helpers/openai-utils'
import { log, getUser, getUserByUsername, htmlToRichText } from 'shared/utils'
import { APIError, AuthedUser, type APIHandler } from './helpers/endpoint'
import { STONK_INITIAL_PROB } from 'common/stonk'
import {
createSupabaseClient,
createSupabaseDirectClient,
} from 'shared/supabase/init'
import {
addGroupToContract,
canUserAddGroupToMarket,
} from 'shared/update-group-contracts-internal'
import { generateContractEmbeddings } from 'shared/supabase/contracts'
import { manifoldLoveUserId } from 'common/love/constants'
import { BTE_USER_ID } from 'common/envs/constants'
import { ValidatedAPIParams } from 'common/api/schema'
import {
createBinarySchema,
createBountySchema,
createMultiNumericSchema,
createMultiSchema,
createNumericSchema,
createPollSchema,
toLiteMarket,
} from 'common/api/market-types'
import { z } from 'zod'
import { anythingToRichText } from 'shared/tiptap'
import { runTxn, runTxnFromBank } from 'shared/txn/run-txn'
import { removeUndefinedProps } from 'common/util/object'
import { onCreateMarket } from 'api/helpers/on-create-contract'
import { getMultiNumericAnswerBucketRangeNames } from 'common/multi-numeric'
import { MAX_GROUPS_PER_MARKET } from 'common/group'
type Body = ValidatedAPIParams<'market'>
const firestore = admin.firestore()
export const createMarket: APIHandler<'market'> = async (body, auth) => {
const market = await createMarketHelper(body, auth)
return {
result: toLiteMarket(market),
continue: async () => {
await onCreateMarket(market, firestore)
},
}
}
export async function createMarketHelper(body: Body, auth: AuthedUser) {
const {
question,
description,
descriptionHtml,
descriptionMarkdown,
descriptionJson,
closeTime: closeTimeRaw,
outcomeType,
groupIds,
visibility,
extraLiquidity,
isTwitchContract,
utcOffset,
min,
max,
initialProb,
isLogScale,
answers,
addAnswersMode,
shouldAnswersSumToOne,
totalBounty,
loverUserId1,
loverUserId2,
matchCreatorId,
isLove,
specialLiquidityPerAnswer,
} = validateMarketBody(body)
const userId = auth.uid
const user = await getUser(userId)
if (!user) throw new APIError(401, 'Your account was not found')
if (loverUserId1 || loverUserId2) {
if (auth.uid !== manifoldLoveUserId) {
throw new Error('Only Manifold Love account can create love contracts.')
}
}
const groups = groupIds
? await Promise.all(
groupIds.map(async (gId) =>
getGroupCheckPermissions(gId, visibility, userId, { isLove })
)
)
: null
const contractRef = firestore.collection('contracts').doc()
const hasOtherAnswer = addAnswersMode !== 'DISABLED' && shouldAnswersSumToOne
const numAnswers = (answers?.length ?? 0) + (hasOtherAnswer ? 1 : 0)
const ante =
(specialLiquidityPerAnswer ??
totalBounty ??
getAnte(outcomeType, numAnswers)) + (extraLiquidity ?? 0)
if (ante < 1) throw new APIError(400, 'Ante must be at least 1')
const closeTime = await getCloseTimestamp(
closeTimeRaw,
question,
outcomeType,
utcOffset
)
const contract = await firestore.runTransaction(async (trans) => {
const userDoc = await trans.get(firestore.collection('users').doc(userId))
if (!userDoc.exists) throw new APIError(401, 'Your account was not found')
const user = userDoc.data() as User
if (user.isBannedFromPosting) throw new APIError(403, 'You are banned')
const { amountSuppliedByUser } = marketCreationCosts(
user,
ante,
!!specialLiquidityPerAnswer
)
if (amountSuppliedByUser > user.balance && user.id !== BTE_USER_ID)
throw new APIError(
403,
`Balance must be at least ${amountSuppliedByUser}.`
)
const slug = await getSlug(trans, question)
let answerLoverUserIds: string[] = []
if (isLove && answers) {
answerLoverUserIds = await getLoveAnswerUserIds(answers)
console.log('answerLoverUserIds', answerLoverUserIds)
}
const contract = getNewContract(
removeUndefinedProps({
id: contractRef.id,
slug,
creator: user,
question,
outcomeType,
description:
typeof description !== 'string' && description
? description
: anythingToRichText({
raw: description,
html: descriptionHtml,
markdown: descriptionMarkdown,
jsonString: descriptionJson,
// default: use a single empty space as the description
}) ?? htmlToRichText(`<p> </p>`),
initialProb: initialProb ?? 50,
ante,
closeTime,
visibility,
isTwitchContract,
min: min ?? 0,
max: max ?? 0,
isLogScale: isLogScale ?? false,
answers: answers ?? [],
addAnswersMode,
shouldAnswersSumToOne,
loverUserId1,
loverUserId2,
matchCreatorId,
isLove,
answerLoverUserIds,
specialLiquidityPerAnswer,
})
)
await runCreateMarketTxn(contractRef.id, ante, user, userDoc.ref, trans)
trans.create(contractRef, contract)
return contract
})
log('created contract ', {
userUserName: user.username,
userId: user.id,
question,
ante: ante || 0,
})
if (answers && contract.mechanism === 'cpmm-multi-1')
await createAnswers(contract)
const pg = createSupabaseDirectClient()
if (groups) {
await Promise.all(
groups.map(async (g) => {
await addGroupToContract(contract, g)
})
)
}
await generateAntes(userId, contract, outcomeType, ante)
await generateContractEmbeddings(contract, pg)
return contract
}
const runCreateMarketTxn = async (
contractId: string,
ante: number,
user: User,
userDocRef: admin.firestore.DocumentReference,
trans: Transaction
) => {
const { amountSuppliedByUser, amountSuppliedByHouse } = marketCreationCosts(
user,
ante
)
if (amountSuppliedByUser > 0) {
await runTxn(trans, {
fromId: user.id,
fromType: 'USER',
toId: contractId,
toType: 'CONTRACT',
amount: amountSuppliedByUser,
token: 'M$',
category: 'CREATE_CONTRACT_ANTE',
})
}
if (amountSuppliedByHouse > 0) {
await runTxnFromBank(trans, {
amount: amountSuppliedByHouse,
category: 'CREATE_CONTRACT_ANTE',
toId: contractId,
toType: 'CONTRACT',
fromType: 'BANK',
token: 'M$',
})
}
if (amountSuppliedByHouse > 0)
trans.update(userDocRef, {
freeQuestionsCreated: FieldValue.increment(1),
})
}
async function getCloseTimestamp(
closeTime: number | Date | undefined,
question: string,
outcomeType: OutcomeType,
utcOffset?: number
): Promise<number | undefined> {
return closeTime
? typeof closeTime === 'number'
? closeTime
: closeTime.getTime()
: NO_CLOSE_TIME_TYPES.includes(outcomeType)
? closeTime
: (await getCloseDate(question, utcOffset)) ??
Date.now() + 7 * 24 * 60 * 60 * 1000
}
const getSlug = async (trans: Transaction, question: string) => {
const proposedSlug = slugify(question)
const preexistingContract = await getContractFromSlug(trans, proposedSlug)
return preexistingContract
? proposedSlug + '-' + randomString()
: proposedSlug
}
async function getContractFromSlug(trans: Transaction, slug: string) {
const contractsRef = firestore.collection('contracts')
const query = contractsRef.where('slug', '==', slug)
const snap = await trans.get(query)
return snap.empty ? undefined : (snap.docs[0].data() as Contract)
}
function validateMarketBody(body: Body) {
const {
question,
description,
descriptionHtml,
descriptionMarkdown,
descriptionJson,
closeTime,
outcomeType,
groupIds,
visibility = 'public',
isTwitchContract,
utcOffset,
loverUserId1,
loverUserId2,
matchCreatorId,
isLove,
} = body
if (groupIds && groupIds.length > MAX_GROUPS_PER_MARKET)
throw new APIError(
400,
`You may only tag up to ${MAX_GROUPS_PER_MARKET} topics on a question`
)
let min: number | undefined,
max: number | undefined,
initialProb: number | undefined,
isLogScale: boolean | undefined,
answers: string[] | undefined,
addAnswersMode: add_answers_mode | undefined,
shouldAnswersSumToOne: boolean | undefined,
totalBounty: number | undefined,
extraLiquidity: number | undefined,
specialLiquidityPerAnswer: number | undefined
if (outcomeType === 'PSEUDO_NUMERIC') {
const parsed = validateMarketType(outcomeType, createNumericSchema, body)
;({ min, max, isLogScale, extraLiquidity } = parsed)
const { initialValue } = parsed
if (max - min <= 0.01)
throw new APIError(400, 'Max must be greater than min by more than 0.01')
if (initialValue <= min || initialValue >= max)
throw new APIError(400, 'Invalid range.')
initialProb = getPseudoProbability(initialValue, min, max, isLogScale) * 100
if (initialProb < 1 || initialProb > 99)
if (outcomeType === 'PSEUDO_NUMERIC')
throw new APIError(
400,
`Initial value is too ${initialProb < 1 ? 'low' : 'high'}`
)
else throw new APIError(400, 'Invalid initial probability.')
}
if (outcomeType === 'STONK') {
initialProb = STONK_INITIAL_PROB
}
if (outcomeType === 'BINARY') {
const parsed = validateMarketType(outcomeType, createBinarySchema, body)
;({ initialProb, extraLiquidity } = parsed)
}
if (outcomeType === 'NUMBER') {
if (!MULTI_NUMERIC_CREATION_ENABLED)
throw new APIError(
400,
'Creating numeric markets is not currently enabled.'
)
;({ min, max } = validateMarketType(
outcomeType,
createMultiNumericSchema,
body
))
if (min >= max)
throw new APIError(400, 'Numeric markets must have min < max.')
const { numberOfBuckets } = validateMarketType(
outcomeType,
createMultiNumericSchema,
body
)
answers = getMultiNumericAnswerBucketRangeNames(min, max, numberOfBuckets)
}
if (outcomeType === 'MULTIPLE_CHOICE') {
;({ answers, addAnswersMode, shouldAnswersSumToOne, extraLiquidity } =
validateMarketType(outcomeType, createMultiSchema, body))
if (answers.length < 2 && addAnswersMode === 'DISABLED' && !isLove)
throw new APIError(
400,
'Multiple choice markets must have at least 2 answers if adding answers is disabled.'
)
}
if (outcomeType === 'BOUNTIED_QUESTION') {
;({ totalBounty } = validateMarketType(
outcomeType,
createBountySchema,
body
))
}
if (outcomeType === 'POLL') {
;({ answers } = validateMarketType(outcomeType, createPollSchema, body))
}
if (body.specialLiquidityPerAnswer) {
if (outcomeType !== 'MULTIPLE_CHOICE' || body.shouldAnswersSumToOne)
throw new APIError(
400,
'specialLiquidityPerAnswer can only be used with independent MULTIPLE_CHOICE markets'
)
specialLiquidityPerAnswer = body.specialLiquidityPerAnswer
}
return {
question,
description,
descriptionHtml,
descriptionMarkdown,
descriptionJson,
closeTime,
outcomeType,
groupIds,
visibility,
extraLiquidity,
isTwitchContract,
utcOffset,
min,
max,
initialProb,
isLogScale,
answers,
addAnswersMode,
shouldAnswersSumToOne,
totalBounty,
loverUserId1,
loverUserId2,
matchCreatorId,
isLove,
specialLiquidityPerAnswer,
}
}
function validateMarketType<T extends z.ZodType>(
outcome: string,
schema: T,
val: unknown
) {
const result = schema.safeParse(val)
if (result.success) return result.data as z.infer<T>
throw new APIError(
400,
`Wrong props for ${outcome} question.`,
result.error.message
)
}
async function getGroupCheckPermissions(
groupId: string,
visibility: string,
userId: string,
options: { isLove?: boolean } = {}
) {
const { isLove } = options
const db = createSupabaseClient()
const groupQuery = await db.from('groups').select().eq('id', groupId).limit(1)
if (groupQuery.error) throw new APIError(500, groupQuery.error.message)
if (!groupQuery.data.length) {
throw new APIError(404, 'No group exists with the given group ID.')
}
const group = groupQuery.data[0]
const membershipQuery = await db
.from('group_members')
.select()
.eq('member_id', userId)
.eq('group_id', groupId)
.limit(1)
const membership = membershipQuery.data?.[0]
if (
(group.privacy_status == 'private' && visibility != 'private') ||
(group.privacy_status != 'private' && visibility == 'private')
) {
throw new APIError(
403,
`Both "${group.name}" and market must be of the same private visibility.`
)
}
if (
!canUserAddGroupToMarket({
userId,
group,
membership,
isLove,
})
) {
throw new APIError(
403,
`User does not have permission to add this market to group "${group.name}".`
)
}
return group
}
async function createAnswers(
contract: CPMMMultiContract | CPMMNumericContract
) {
const { isLove } = contract
let { answers } = contract
if (isLove) {
// Add loverUserId to the answer.
answers = await Promise.all(
answers.map(async (a) => {
// Parse username from answer text.
const matches = a.text.match(/@(\w+)/)
const loverUsername = matches ? matches[1] : null
if (!loverUsername) return a
const loverUserId = (await getUserByUsername(loverUsername))?.id
if (!loverUserId) return a
return {
...a,
loverUserId,
}
})
)
}
await Promise.all(
answers.map((answer) => {
return firestore
.collection(`contracts/${contract.id}/answersCpmm`)
.doc(answer.id)
.set(answer)
})
)
}
async function getLoveAnswerUserIds(answers: string[]) {
// Get the loverUserId from the answer text.
return await Promise.all(
answers.map(async (answerText) => {
// Parse username from answer text.
const matches = answerText.match(/@(\w+)/)
console.log('matches', matches)
const loverUsername = matches ? matches[1] : null
if (!loverUsername)
throw new APIError(500, 'No lover username found ' + answerText)
const user = await getUserByUsername(loverUsername)
if (!user)
throw new APIError(500, 'No user found with username ' + answerText)
return user.id
})
)
}
async function generateAntes(
providerId: string,
contract: Contract,
outcomeType: string,
ante: number
) {
if (
outcomeType === 'BINARY' ||
outcomeType === 'PSEUDO_NUMERIC' ||
outcomeType === 'STONK' ||
outcomeType === 'MULTIPLE_CHOICE' ||
outcomeType === 'NUMBER'
) {
const lp = getCpmmInitialLiquidityTxn(
providerId,
contract as CPMMBinaryContract | CPMMMultiContract,
ante
)
await firestore.runTransaction(async (transaction) => {
runTxn(transaction, lp)
})
}
}