diff --git a/common/calculate.ts b/common/calculate.ts index da4ce13a..e4c9ed07 100644 --- a/common/calculate.ts +++ b/common/calculate.ts @@ -142,17 +142,20 @@ function getCpmmInvested(yourBets: Bet[]) { const { outcome, shares, amount } = bet if (floatingEqual(shares, 0)) continue + const spent = totalSpent[outcome] ?? 0 + const position = totalShares[outcome] ?? 0 + if (amount > 0) { - totalShares[outcome] = (totalShares[outcome] ?? 0) + shares - totalSpent[outcome] = (totalSpent[outcome] ?? 0) + amount + totalShares[outcome] = position + shares + totalSpent[outcome] = spent + amount } else if (amount < 0) { - const averagePrice = totalSpent[outcome] / totalShares[outcome] - totalShares[outcome] = totalShares[outcome] + shares - totalSpent[outcome] = totalSpent[outcome] + averagePrice * shares + const averagePrice = position === 0 ? 0 : spent / position + totalShares[outcome] = position + shares + totalSpent[outcome] = spent + averagePrice * shares } } - return sum(Object.values(totalSpent)) + return sum([0, ...Object.values(totalSpent)]) } function getDpmInvested(yourBets: Bet[]) { diff --git a/common/follow.ts b/common/follow.ts index 04ca6899..7ff6e7f2 100644 --- a/common/follow.ts +++ b/common/follow.ts @@ -2,3 +2,8 @@ export type Follow = { userId: string timestamp: number } + +export type ContractFollow = { + id: string // user id + createdTime: number +} diff --git a/common/notification.ts b/common/notification.ts index 2f03467d..804ec68e 100644 --- a/common/notification.ts +++ b/common/notification.ts @@ -248,3 +248,9 @@ export type BetFillData = { probability: number fillAmount: number } + +export type ContractResolutionData = { + outcome: string + userPayout: number + userInvestment: number +} diff --git a/common/user-notification-preferences.ts b/common/user-notification-preferences.ts index e2402ea9..f585f373 100644 --- a/common/user-notification-preferences.ts +++ b/common/user-notification-preferences.ts @@ -218,6 +218,7 @@ const notificationReasonToSubscriptionType: Partial< export const getNotificationDestinationsForUser = ( privateUser: PrivateUser, + // TODO: accept reasons array from most to least important and work backwards reason: notification_reason_types | notification_preference ) => { const notificationSettings = privateUser.notificationPreferences diff --git a/functions/src/create-notification.ts b/functions/src/create-notification.ts index 390a8cd8..ebd3f26c 100644 --- a/functions/src/create-notification.ts +++ b/functions/src/create-notification.ts @@ -2,6 +2,7 @@ import * as admin from 'firebase-admin' import { BetFillData, BettingStreakData, + ContractResolutionData, Notification, notification_reason_types, } from '../../common/notification' @@ -28,6 +29,7 @@ import { } from './emails' import { filterDefined } from '../../common/util/array' import { getNotificationDestinationsForUser } from '../../common/user-notification-preferences' +import { ContractFollow } from '../../common/follow' const firestore = admin.firestore() type recipients_to_reason_texts = { @@ -159,7 +161,7 @@ export type replied_users_info = { export const createCommentOrAnswerOrUpdatedContractNotification = async ( sourceId: string, sourceType: 'comment' | 'answer' | 'contract', - sourceUpdateType: 'created' | 'updated' | 'resolved', + sourceUpdateType: 'created' | 'updated', sourceUser: User, idempotencyKey: string, sourceText: string, @@ -167,17 +169,6 @@ export const createCommentOrAnswerOrUpdatedContractNotification = async ( miscData?: { repliedUsersInfo: replied_users_info taggedUserIds: string[] - }, - resolutionData?: { - bets: Bet[] - userInvestments: { [userId: string]: number } - userPayouts: { [userId: string]: number } - creator: User - creatorPayout: number - contract: Contract - outcome: string - resolutionProbability?: number - resolutions?: { [outcome: string]: number } } ) => { const { repliedUsersInfo, taggedUserIds } = miscData ?? {} @@ -230,11 +221,7 @@ export const createCommentOrAnswerOrUpdatedContractNotification = async ( userId: string, reason: notification_reason_types ) => { - if ( - !stillFollowingContract(sourceContract.creatorId) || - sourceUser.id == userId - ) - return + if (!stillFollowingContract(userId) || sourceUser.id == userId) return const privateUser = await getPrivateUser(userId) if (!privateUser) return const { sendToBrowser, sendToEmail } = getNotificationDestinationsForUser( @@ -276,24 +263,6 @@ export const createCommentOrAnswerOrUpdatedContractNotification = async ( sourceUser.avatarUrl ) emailRecipientIdsList.push(userId) - } else if ( - sourceType === 'contract' && - sourceUpdateType === 'resolved' && - resolutionData - ) { - await sendMarketResolutionEmail( - reason, - privateUser, - resolutionData.userInvestments[userId] ?? 0, - resolutionData.userPayouts[userId] ?? 0, - sourceUser, - resolutionData.creatorPayout, - sourceContract, - resolutionData.outcome, - resolutionData.resolutionProbability, - resolutionData.resolutions - ) - emailRecipientIdsList.push(userId) } } @@ -447,6 +416,8 @@ export const createCommentOrAnswerOrUpdatedContractNotification = async ( ) } + //TODO: store all possible reasons why the user might be getting the notification and choose the most lenient that they + // have enabled so they will unsubscribe from the least important notifications await notifyRepliedUser() await notifyTaggedUsers() await notifyContractCreator() @@ -943,3 +914,130 @@ export const createNewContractNotification = async ( await sendNotificationsIfSettingsAllow(mentionedUserId, 'tagged_user') } } + +export const createContractResolvedNotifications = async ( + contract: Contract, + creator: User, + outcome: string, + probabilityInt: number | undefined, + resolutionValue: number | undefined, + resolutionData: { + bets: Bet[] + userInvestments: { [userId: string]: number } + userPayouts: { [userId: string]: number } + creator: User + creatorPayout: number + contract: Contract + outcome: string + resolutionProbability?: number + resolutions?: { [outcome: string]: number } + } +) => { + let resolutionText = outcome ?? contract.question + if ( + contract.outcomeType === 'FREE_RESPONSE' || + contract.outcomeType === 'MULTIPLE_CHOICE' + ) { + const answerText = contract.answers.find( + (answer) => answer.id === outcome + )?.text + if (answerText) resolutionText = answerText + } else if (contract.outcomeType === 'BINARY') { + if (resolutionText === 'MKT' && probabilityInt) + resolutionText = `${probabilityInt}%` + else if (resolutionText === 'MKT') resolutionText = 'PROB' + } else if (contract.outcomeType === 'PSEUDO_NUMERIC') { + if (resolutionText === 'MKT' && resolutionValue) + resolutionText = `${resolutionValue}` + } + + const idempotencyKey = contract.id + '-resolved' + const createBrowserNotification = async ( + userId: string, + reason: notification_reason_types + ) => { + const notificationRef = firestore + .collection(`/users/${userId}/notifications`) + .doc(idempotencyKey) + const notification: Notification = { + id: idempotencyKey, + userId, + reason, + createdTime: Date.now(), + isSeen: false, + sourceId: contract.id, + sourceType: 'contract', + sourceUpdateType: 'resolved', + sourceContractId: contract.id, + sourceUserName: creator.name, + sourceUserUsername: creator.username, + sourceUserAvatarUrl: creator.avatarUrl, + sourceText: resolutionText, + sourceContractCreatorUsername: contract.creatorUsername, + sourceContractTitle: contract.question, + sourceContractSlug: contract.slug, + sourceSlug: contract.slug, + sourceTitle: contract.question, + data: { + outcome, + userInvestment: resolutionData.userInvestments[userId] ?? 0, + userPayout: resolutionData.userPayouts[userId] ?? 0, + } as ContractResolutionData, + } + return await notificationRef.set(removeUndefinedProps(notification)) + } + + const sendNotificationsIfSettingsPermit = async ( + userId: string, + reason: notification_reason_types + ) => { + if (!stillFollowingContract(userId) || creator.id == userId) return + const privateUser = await getPrivateUser(userId) + if (!privateUser) return + const { sendToBrowser, sendToEmail } = getNotificationDestinationsForUser( + privateUser, + reason + ) + + // Browser notifications + if (sendToBrowser) { + await createBrowserNotification(userId, reason) + } + + // Emails notifications + if (sendToEmail) + await sendMarketResolutionEmail( + reason, + privateUser, + resolutionData.userInvestments[userId] ?? 0, + resolutionData.userPayouts[userId] ?? 0, + creator, + resolutionData.creatorPayout, + contract, + resolutionData.outcome, + resolutionData.resolutionProbability, + resolutionData.resolutions + ) + } + + const contractFollowersIds = ( + await getValues( + firestore.collection(`contracts/${contract.id}/follows`) + ) + ).map((follow) => follow.id) + + const stillFollowingContract = (userId: string) => { + return contractFollowersIds.includes(userId) + } + + await Promise.all( + contractFollowersIds.map((id) => + sendNotificationsIfSettingsPermit( + id, + resolutionData.userInvestments[id] + ? 'resolution_on_contract_with_users_shares_in' + : 'resolution_on_contract_you_follow' + ) + ) + ) +} diff --git a/functions/src/resolve-market.ts b/functions/src/resolve-market.ts index b99b5c87..feddd67c 100644 --- a/functions/src/resolve-market.ts +++ b/functions/src/resolve-market.ts @@ -21,7 +21,7 @@ import { removeUndefinedProps } from '../../common/util/object' import { LiquidityProvision } from '../../common/liquidity-provision' import { APIError, newEndpoint, validate } from './api' import { getContractBetMetrics } from '../../common/calculate' -import { createCommentOrAnswerOrUpdatedContractNotification } from './create-notification' +import { createContractResolvedNotifications } from './create-notification' import { CancelUniqueBettorBonusTxn, Txn } from '../../common/txn' import { runTxn, TxnData } from './transact' import { @@ -177,33 +177,13 @@ export const resolvemarket = newEndpoint(opts, async (req, auth) => { groupBy(bets, (bet) => bet.userId), (bets) => getContractBetMetrics(contract, bets).invested ) - let resolutionText = outcome ?? contract.question - if ( - contract.outcomeType === 'FREE_RESPONSE' || - contract.outcomeType === 'MULTIPLE_CHOICE' - ) { - const answerText = contract.answers.find( - (answer) => answer.id === outcome - )?.text - if (answerText) resolutionText = answerText - } else if (contract.outcomeType === 'BINARY') { - if (resolutionText === 'MKT' && probabilityInt) - resolutionText = `${probabilityInt}%` - else if (resolutionText === 'MKT') resolutionText = 'PROB' - } else if (contract.outcomeType === 'PSEUDO_NUMERIC') { - if (resolutionText === 'MKT' && value) resolutionText = `${value}` - } - // TODO: this actually may be too slow to complete with a ton of users to notify? - await createCommentOrAnswerOrUpdatedContractNotification( - contract.id, - 'contract', - 'resolved', - creator, - contract.id + '-resolution', - resolutionText, + await createContractResolvedNotifications( contract, - undefined, + creator, + outcome, + probabilityInt, + value, { bets, userInvestments, diff --git a/functions/src/utils.ts b/functions/src/utils.ts index a0878e4f..23f7257a 100644 --- a/functions/src/utils.ts +++ b/functions/src/utils.ts @@ -4,7 +4,7 @@ import { chunk } from 'lodash' import { Contract } from '../../common/contract' import { PrivateUser, User } from '../../common/user' import { Group } from '../../common/group' -import { Post } from 'common/post' +import { Post } from '../../common/post' export const log = (...args: unknown[]) => { console.log(`[${new Date().toISOString()}]`, ...args) diff --git a/web/components/contract/contract-info-dialog.tsx b/web/components/contract/contract-info-dialog.tsx index 7277c4dd..26c18484 100644 --- a/web/components/contract/contract-info-dialog.tsx +++ b/web/components/contract/contract-info-dialog.tsx @@ -20,6 +20,7 @@ import { DuplicateContractButton } from '../copy-contract-button' import { Row } from '../layout/row' import { BETTORS } from 'common/user' import { Button } from '../button' +import { capitalize } from 'lodash' export const contractDetailsButtonClassName = 'group flex items-center rounded-md px-3 py-2 text-sm font-medium cursor-pointer hover:bg-gray-100 text-gray-400 hover:text-gray-500' @@ -139,7 +140,7 @@ export function ContractInfoDialog(props: { */} - {BETTORS} + {capitalize(BETTORS)} {bettorsCount} diff --git a/web/components/user-page.tsx b/web/components/user-page.tsx index 8dc7928a..2b24fa60 100644 --- a/web/components/user-page.tsx +++ b/web/components/user-page.tsx @@ -242,7 +242,7 @@ export function UserPage(props: { user: User }) { Earn {formatMoney(REFERRAL_AMOUNT)} when you refer a friend! {' '} - You've gotten + You've gotten{' '} ) + } else if (sourceType === 'contract' && sourceUpdateType === 'resolved') { + return ( + + ) } // TODO Add new notification components here @@ -810,7 +820,8 @@ function NotificationFrame(props: { sourceText, } = notification const questionNeedsResolution = sourceUpdateType == 'closed' - + const { width } = useWindowSize() + const isMobile = (width ?? 0) < 600 return (
{subtitle} {isChildOfGroup ? ( @@ -945,6 +956,83 @@ function BetFillNotification(props: { ) } +function ContractResolvedNotification(props: { + notification: Notification + highlighted: boolean + justSummary: boolean + isChildOfGroup?: boolean +}) { + const { notification, isChildOfGroup, highlighted, justSummary } = props + const { sourceText, data } = notification + const { userInvestment, userPayout } = (data as ContractResolutionData) ?? {} + const subtitle = 'resolved the market' + const resolutionDescription = () => { + if (!sourceText) return
+ if (sourceText === 'YES' || sourceText == 'NO') { + return + } + if (sourceText.includes('%')) + return + if (sourceText === 'CANCEL') return + if (sourceText === 'MKT' || sourceText === 'PROB') return + + // Numeric market + if (parseFloat(sourceText)) + return + + // Free response market + return ( +
+ +
+ ) + } + + const description = + userInvestment && userPayout !== undefined ? ( + + {resolutionDescription()} + Invested: + {formatMoney(userInvestment)} + Payout: + 0 ? 'text-primary' : 'text-red-500', + 'truncate' + )} + > + {formatMoney(userPayout)} + {` (${userPayout > 0 ? '+' : ''}${Math.round( + ((userPayout - userInvestment) / userInvestment) * 100 + )}%)`} + + + ) : ( + {resolutionDescription()} + ) + + if (justSummary) { + return ( + + {description} + + ) + } + + return ( + + + {description} + + + ) +} + export const setNotificationsAsSeen = async (notifications: Notification[]) => { const unseenNotifications = notifications.filter((n) => !n.isSeen) return await Promise.all( @@ -1064,30 +1152,7 @@ function NotificationTextLabel(props: { if (sourceType === 'contract') { if (justSummary || !sourceText) return
// Resolved contracts - if (sourceType === 'contract' && sourceUpdateType === 'resolved') { - { - if (sourceText === 'YES' || sourceText == 'NO') { - return - } - if (sourceText.includes('%')) - return ( - - ) - if (sourceText === 'CANCEL') return - if (sourceText === 'MKT' || sourceText === 'PROB') return - // Numeric market - if (parseFloat(sourceText)) - return - - // Free response market - return ( -
- -
- ) - } - } // Close date will be a number - it looks better without it if (sourceUpdateType === 'closed') { return
diff --git a/web/pages/tournaments/index.tsx b/web/pages/tournaments/index.tsx index e81c239f..8ce11284 100644 --- a/web/pages/tournaments/index.tsx +++ b/web/pages/tournaments/index.tsx @@ -76,6 +76,13 @@ const Salem = { } const tourneys: Tourney[] = [ + { + title: 'Clearer Thinking Regrant Project', + blurb: 'Which projects will Clearer Thinking give a grant to?', + award: '$13,000', + endTime: toDate('Sep 22, 2022'), + groupId: 'fhksfIgqyWf7OxsV9nkM', + }, { title: 'Manifold F2P Tournament', blurb: @@ -99,13 +106,6 @@ const tourneys: Tourney[] = [ endTime: toDate('Jan 6, 2023'), groupId: 'SxGRqXRpV3RAQKudbcNb', }, - // { - // title: 'Clearer Thinking Regrant Project', - // blurb: 'Something amazing', - // award: '$10,000', - // endTime: toDate('Sep 22, 2022'), - // groupId: '2VsVVFGhKtIdJnQRAXVb', - // }, // Tournaments without awards get featured belows {