manifold/functions/src/emails.ts

525 lines
13 KiB
TypeScript
Raw Normal View History

import { DOMAIN } from '../../common/envs/constants'
import { Answer } from '../../common/answer'
import { Bet } from '../../common/bet'
import { getProbability } from '../../common/calculate'
import { Comment } from '../../common/comment'
import { Contract } from '../../common/contract'
import { PrivateUser, User } from '../../common/user'
import {
formatLargeNumber,
formatMoney,
formatPercent,
} from '../../common/util/format'
Numeric range markets!! (#146) * Numeric contract type * Create market numeric type * Add numeric graph (coded without testing) * Outline of numeric bet panel * Update bet panel logic * create numeric contracts * remove batching for antes for numeric markets * Remove focus * numeric market range [1, 100] * Zoom graph * Hide bet panels * getNumericBets * Add numeric resolution panel * Use getNumericBets in bet panel calc * Switch bucket count to 100 * Parallelize ante creation * placeBet for numeric markets * halve std of numeric bets * Update resolveMarket with numeric type * Set min and max for contract * lower std for numeric bets * calculateNumericDpmShares: use sorted order * Use min and max to map the input * Fix probability calc * normpdf variance mislabeled * range input * merge * change numeric graph color * fix getNewContract params * bet panel labels * validation * number input * fix bucketing * bucket input, numeric resolution panel * outcome label * merge * numeric bet panel on mobile * Make text underneath filled green answer bar selectable * Default to 'all' feed category when loading page. * fix numeric resolution panel * fix numeric bet panel calculations * display numeric resolution * don't render NumericBetPanel for non numeric markets * numeric bets: store shares, bet amounts across buckets in each bet object * restore your bets for numeric markets * numeric pnl calculations * remove hasUserHitManaLimit * contrain contract type * handle undefined allOutcomeShares * numeric ante bet amount * use correct amount for numeric dpm payouts * change numeric graph/outcome color * numeric constants * hack to show correct numeric payout in calculateDpmPayoutAfterCorrectBet * remove comment * fix ante display in bet list * halve bucket count * cast to NumericContract * fix merge imports * OUTCOME_TYPES * typo * lower bucket count to 200 * store raw numeric value with bet * store raw numeric resolution value * number input max length * create page: min, max to undefined if not numeric market * numeric resolution formatting * expected value for numeric markets * expected value for numeric markets * rearrange lines for readability * move normalpdf to util/math * show bets tab * check if outcomeMode is undefined * remove extraneous auto-merge cruft * hide comment status for numeric markets * import Co-authored-by: mantikoros <sgrugett@gmail.com>
2022-05-19 17:42:03 +00:00
import { getValueFromBucket } from '../../common/calculate-dpm'
import { formatNumericProbability } from '../../common/pseudo-numeric'
Numeric range markets!! (#146) * Numeric contract type * Create market numeric type * Add numeric graph (coded without testing) * Outline of numeric bet panel * Update bet panel logic * create numeric contracts * remove batching for antes for numeric markets * Remove focus * numeric market range [1, 100] * Zoom graph * Hide bet panels * getNumericBets * Add numeric resolution panel * Use getNumericBets in bet panel calc * Switch bucket count to 100 * Parallelize ante creation * placeBet for numeric markets * halve std of numeric bets * Update resolveMarket with numeric type * Set min and max for contract * lower std for numeric bets * calculateNumericDpmShares: use sorted order * Use min and max to map the input * Fix probability calc * normpdf variance mislabeled * range input * merge * change numeric graph color * fix getNewContract params * bet panel labels * validation * number input * fix bucketing * bucket input, numeric resolution panel * outcome label * merge * numeric bet panel on mobile * Make text underneath filled green answer bar selectable * Default to 'all' feed category when loading page. * fix numeric resolution panel * fix numeric bet panel calculations * display numeric resolution * don't render NumericBetPanel for non numeric markets * numeric bets: store shares, bet amounts across buckets in each bet object * restore your bets for numeric markets * numeric pnl calculations * remove hasUserHitManaLimit * contrain contract type * handle undefined allOutcomeShares * numeric ante bet amount * use correct amount for numeric dpm payouts * change numeric graph/outcome color * numeric constants * hack to show correct numeric payout in calculateDpmPayoutAfterCorrectBet * remove comment * fix ante display in bet list * halve bucket count * cast to NumericContract * fix merge imports * OUTCOME_TYPES * typo * lower bucket count to 200 * store raw numeric value with bet * store raw numeric resolution value * number input max length * create page: min, max to undefined if not numeric market * numeric resolution formatting * expected value for numeric markets * expected value for numeric markets * rearrange lines for readability * move normalpdf to util/math * show bets tab * check if outcomeMode is undefined * remove extraneous auto-merge cruft * hide comment status for numeric markets * import Co-authored-by: mantikoros <sgrugett@gmail.com>
2022-05-19 17:42:03 +00:00
2022-08-16 16:43:51 +00:00
import { sendTemplateEmail, sendTextEmail } from './send-email'
import { getPrivateUser, getUser } from './utils'
import { getFunctionUrl } from '../../common/api'
import { richTextToString } from '../../common/util/parse'
import { buildCardUrl, getOpenGraphProps } from '../../common/contract-details'
const UNSUBSCRIBE_ENDPOINT = getFunctionUrl('unsubscribe')
export const sendMarketResolutionEmail = async (
userId: string,
investment: number,
payout: number,
creator: User,
creatorPayout: number,
contract: Contract,
resolution: string,
resolutionProbability?: number,
resolutions?: { [outcome: string]: number }
) => {
const privateUser = await getPrivateUser(userId)
if (
!privateUser ||
privateUser.unsubscribedFromResolutionEmails ||
!privateUser.email
)
return
const user = await getUser(userId)
if (!user) return
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
const outcome = toDisplayResolution(
contract,
resolution,
resolutionProbability,
resolutions
)
2022-01-10 22:07:44 +00:00
const subject = `Resolved ${outcome}: ${contract.question}`
const creatorPayoutText =
creatorPayout >= 1 && userId === creator.id
? ` (plus ${formatMoney(creatorPayout)} in commissions)`
: ''
const emailType = 'market-resolved'
const unsubscribeUrl = `${UNSUBSCRIBE_ENDPOINT}?id=${userId}&type=${emailType}`
const displayedInvestment =
Number.isNaN(investment) || investment < 0
? formatMoney(0)
: formatMoney(investment)
const displayedPayout = formatMoney(payout)
2022-01-10 22:07:44 +00:00
const templateData: market_resolved_template = {
userId: user.id,
2022-01-10 22:07:44 +00:00
name: user.name,
creatorName: creator.name,
question: contract.question,
outcome,
investment: displayedInvestment,
payout: displayedPayout + creatorPayoutText,
url: `https://${DOMAIN}/${creator.username}/${contract.slug}`,
unsubscribeUrl,
2022-01-10 22:07:44 +00:00
}
2022-01-10 22:07:44 +00:00
// Modify template here:
// https://app.mailgun.com/app/sending/domains/mg.manifold.markets/templates/edit/market-resolved/initial
return await sendTemplateEmail(
privateUser.email,
subject,
'market-resolved',
templateData
)
}
2022-02-08 11:26:33 +00:00
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
type market_resolved_template = {
userId: string
name: string
creatorName: string
question: string
outcome: string
investment: string
payout: string
url: string
unsubscribeUrl: string
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
}
const toDisplayResolution = (
contract: Contract,
resolution: string,
resolutionProbability?: number,
resolutions?: { [outcome: string]: number }
) => {
if (contract.outcomeType === 'BINARY') {
const prob = resolutionProbability ?? getProbability(contract)
const display = {
YES: 'YES',
NO: 'NO',
CANCEL: 'N/A',
MKT: formatPercent(prob ?? 0),
}[resolution]
return display || resolution
}
if (contract.outcomeType === 'PSEUDO_NUMERIC') {
const { resolution, resolutionValue } = contract
if (resolution === 'CANCEL') return 'N/A'
return resolutionValue
? formatLargeNumber(resolutionValue)
: formatNumericProbability(
resolutionProbability ?? getProbability(contract),
contract
)
}
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
if (resolution === 'MKT' && resolutions) return 'MULTI'
if (resolution === 'CANCEL') return 'N/A'
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
Numeric range markets!! (#146) * Numeric contract type * Create market numeric type * Add numeric graph (coded without testing) * Outline of numeric bet panel * Update bet panel logic * create numeric contracts * remove batching for antes for numeric markets * Remove focus * numeric market range [1, 100] * Zoom graph * Hide bet panels * getNumericBets * Add numeric resolution panel * Use getNumericBets in bet panel calc * Switch bucket count to 100 * Parallelize ante creation * placeBet for numeric markets * halve std of numeric bets * Update resolveMarket with numeric type * Set min and max for contract * lower std for numeric bets * calculateNumericDpmShares: use sorted order * Use min and max to map the input * Fix probability calc * normpdf variance mislabeled * range input * merge * change numeric graph color * fix getNewContract params * bet panel labels * validation * number input * fix bucketing * bucket input, numeric resolution panel * outcome label * merge * numeric bet panel on mobile * Make text underneath filled green answer bar selectable * Default to 'all' feed category when loading page. * fix numeric resolution panel * fix numeric bet panel calculations * display numeric resolution * don't render NumericBetPanel for non numeric markets * numeric bets: store shares, bet amounts across buckets in each bet object * restore your bets for numeric markets * numeric pnl calculations * remove hasUserHitManaLimit * contrain contract type * handle undefined allOutcomeShares * numeric ante bet amount * use correct amount for numeric dpm payouts * change numeric graph/outcome color * numeric constants * hack to show correct numeric payout in calculateDpmPayoutAfterCorrectBet * remove comment * fix ante display in bet list * halve bucket count * cast to NumericContract * fix merge imports * OUTCOME_TYPES * typo * lower bucket count to 200 * store raw numeric value with bet * store raw numeric resolution value * number input max length * create page: min, max to undefined if not numeric market * numeric resolution formatting * expected value for numeric markets * expected value for numeric markets * rearrange lines for readability * move normalpdf to util/math * show bets tab * check if outcomeMode is undefined * remove extraneous auto-merge cruft * hide comment status for numeric markets * import Co-authored-by: mantikoros <sgrugett@gmail.com>
2022-05-19 17:42:03 +00:00
if (contract.outcomeType === 'NUMERIC' && contract.mechanism === 'dpm-2')
return (
contract.resolutionValue?.toString() ??
getValueFromBucket(resolution, contract).toString()
)
2022-06-01 03:40:08 +00:00
const answer = contract.answers.find((a) => a.id === resolution)
if (answer) return answer.text
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
return `#${resolution}`
}
2022-02-08 11:26:33 +00:00
export const sendWelcomeEmail = async (
user: User,
privateUser: PrivateUser
) => {
if (!privateUser || !privateUser.email) return
const { name, id: userId } = user
const firstName = name.split(' ')[0]
2022-02-08 11:26:33 +00:00
const emailType = 'generic'
const unsubscribeLink = `${UNSUBSCRIBE_ENDPOINT}?id=${userId}&type=${emailType}`
return await sendTemplateEmail(
privateUser.email,
2022-02-08 11:26:33 +00:00
'Welcome to Manifold Markets!',
'welcome',
{
name: firstName,
unsubscribeLink,
},
{
from: 'David from Manifold <david@manifold.markets>',
}
)
}
2022-02-08 11:26:33 +00:00
2022-08-16 16:43:51 +00:00
export const sendPersonalFollowupEmail = async (
user: User,
privateUser: PrivateUser,
sendTime: string
2022-08-16 16:43:51 +00:00
) => {
if (!privateUser || !privateUser.email) return
const { name } = user
const firstName = name.split(' ')[0]
const emailBody = `Hi ${firstName},
2022-09-02 21:20:04 +00:00
Thanks for signing up! I'm one of the cofounders of Manifold Markets, and was wondering how you've found your experience on the platform so far?
2022-08-16 16:43:51 +00:00
If you haven't already, I encourage you to try creating your own prediction market (https://manifold.markets/create) and joining our Discord chat (https://discord.com/invite/eHQBNBqXuh).
Feel free to reply to this email with any questions or concerns you have.
Cheers,
James
Cofounder of Manifold Markets
https://manifold.markets
`
await sendTextEmail(
privateUser.email,
'How are you finding Manifold?',
emailBody,
{
from: 'James from Manifold <james@manifold.markets>',
'o:deliverytime': sendTime,
}
)
}
export const sendOneWeekBonusEmail = async (
user: User,
privateUser: PrivateUser
) => {
if (
!privateUser ||
!privateUser.email ||
privateUser.unsubscribedFromGenericEmails
)
return
2022-02-22 22:35:53 +00:00
const { name, id: userId } = user
const firstName = name.split(' ')[0]
2022-02-22 22:35:53 +00:00
const emailType = 'generic'
const unsubscribeLink = `${UNSUBSCRIBE_ENDPOINT}?id=${userId}&type=${emailType}`
2022-02-08 11:26:33 +00:00
return await sendTemplateEmail(
privateUser.email,
'Manifold Markets one week anniversary gift',
'one-week',
{
name: firstName,
unsubscribeLink,
manalink: 'https://manifold.markets/link/lj4JbBvE',
},
{
from: 'David from Manifold <david@manifold.markets>',
}
)
}
2022-08-17 22:36:52 +00:00
export const sendCreatorGuideEmail = async (
user: User,
2022-08-20 20:34:22 +00:00
privateUser: PrivateUser,
sendTime: string
2022-08-17 22:36:52 +00:00
) => {
if (
!privateUser ||
!privateUser.email ||
privateUser.unsubscribedFromGenericEmails
)
return
const { name, id: userId } = user
const firstName = name.split(' ')[0]
const emailType = 'generic'
const unsubscribeLink = `${UNSUBSCRIBE_ENDPOINT}?id=${userId}&type=${emailType}`
return await sendTemplateEmail(
privateUser.email,
2022-08-20 20:34:22 +00:00
'Create your own prediction market',
2022-08-17 22:36:52 +00:00
'creating-market',
{
name: firstName,
unsubscribeLink,
},
{
from: 'David from Manifold <david@manifold.markets>',
2022-08-20 20:34:22 +00:00
'o:deliverytime': sendTime,
2022-08-17 22:36:52 +00:00
}
)
}
export const sendThankYouEmail = async (
user: User,
privateUser: PrivateUser
) => {
if (
!privateUser ||
!privateUser.email ||
privateUser.unsubscribedFromGenericEmails
)
return
const { name, id: userId } = user
const firstName = name.split(' ')[0]
const emailType = 'generic'
const unsubscribeLink = `${UNSUBSCRIBE_ENDPOINT}?id=${userId}&type=${emailType}`
return await sendTemplateEmail(
privateUser.email,
'Thanks for your Manifold purchase',
'thank-you',
{
name: firstName,
unsubscribeLink,
},
{
from: 'David from Manifold <david@manifold.markets>',
}
2022-02-08 11:26:33 +00:00
)
}
export const sendMarketCloseEmail = async (
user: User,
privateUser: PrivateUser,
contract: Contract
) => {
if (
!privateUser ||
privateUser.unsubscribedFromResolutionEmails ||
!privateUser.email
)
return
const { username, name, id: userId } = user
const firstName = name.split(' ')[0]
2022-09-01 04:00:37 +00:00
const { question, slug, volume } = contract
const url = `https://${DOMAIN}/${username}/${slug}`
const emailType = 'market-resolve'
const unsubscribeUrl = `${UNSUBSCRIBE_ENDPOINT}?id=${userId}&type=${emailType}`
return await sendTemplateEmail(
privateUser.email,
'Your market has closed',
'market-close',
{
question,
url,
unsubscribeUrl,
userId,
name: firstName,
volume: formatMoney(volume),
}
)
}
export const sendNewCommentEmail = async (
userId: string,
commentCreator: User,
contract: Contract,
comment: Comment,
bet?: Bet,
answerText?: string,
answerId?: string
) => {
const privateUser = await getPrivateUser(userId)
if (
!privateUser ||
!privateUser.email ||
privateUser.unsubscribedFromCommentEmails
)
return
const { question, creatorUsername, slug } = contract
const marketUrl = `https://${DOMAIN}/${creatorUsername}/${slug}#${comment.id}`
const emailType = 'market-comment'
const unsubscribeUrl = `${UNSUBSCRIBE_ENDPOINT}?id=${userId}&type=${emailType}`
const { name: commentorName, avatarUrl: commentorAvatarUrl } = commentCreator
const { content } = comment
const text = richTextToString(content)
let betDescription = ''
if (bet) {
const { amount, sale } = bet
betDescription = `${sale || amount < 0 ? 'sold' : 'bought'} ${formatMoney(
2022-04-28 03:34:50 +00:00
Math.abs(amount)
)}`
}
const subject = `Comment on ${question}`
const from = `${commentorName} on Manifold <no-reply@manifold.markets>`
if (contract.outcomeType === 'FREE_RESPONSE' && answerId && answerText) {
const answerNumber = `#${answerId}`
return await sendTemplateEmail(
privateUser.email,
subject,
'market-answer-comment',
{
answer: answerText,
answerNumber,
commentorName,
commentorAvatarUrl: commentorAvatarUrl ?? '',
comment: text,
marketUrl,
unsubscribeUrl,
betDescription,
},
{ from }
)
} else {
if (bet) {
betDescription = `${betDescription} of ${toDisplayResolution(
contract,
bet.outcome
)}`
}
return await sendTemplateEmail(
privateUser.email,
subject,
'market-comment',
{
commentorName,
commentorAvatarUrl: commentorAvatarUrl ?? '',
comment: text,
marketUrl,
unsubscribeUrl,
betDescription,
},
{ from }
)
}
}
export const sendNewAnswerEmail = async (
answer: Answer,
contract: Contract
) => {
// Send to just the creator for now.
const { creatorId: userId } = contract
// Don't send the creator's own answers.
if (answer.userId === userId) return
const privateUser = await getPrivateUser(userId)
if (
!privateUser ||
!privateUser.email ||
privateUser.unsubscribedFromAnswerEmails
)
return
const { question, creatorUsername, slug } = contract
const { name, avatarUrl, text } = answer
const marketUrl = `https://${DOMAIN}/${creatorUsername}/${slug}`
const emailType = 'market-answer'
const unsubscribeUrl = `${UNSUBSCRIBE_ENDPOINT}?id=${userId}&type=${emailType}`
const subject = `New answer on ${question}`
const from = `${name} <info@manifold.markets>`
return await sendTemplateEmail(
privateUser.email,
subject,
'market-answer',
{
name,
avatarUrl: avatarUrl ?? '',
answer: text,
marketUrl,
unsubscribeUrl,
},
{ from }
)
}
export const sendInterestingMarketsEmail = async (
user: User,
privateUser: PrivateUser,
contractsToSend: Contract[],
deliveryTime?: string
) => {
if (
!privateUser ||
!privateUser.email ||
privateUser?.unsubscribedFromWeeklyTrendingEmails
)
return
const emailType = 'weekly-trending'
const unsubscribeUrl = `${UNSUBSCRIBE_ENDPOINT}?id=${privateUser.id}&type=${emailType}`
const { name } = user
const firstName = name.split(' ')[0]
await sendTemplateEmail(
privateUser.email,
`${contractsToSend[0].question} & 5 more interesting markets on Manifold`,
'interesting-markets',
{
name: firstName,
unsubscribeLink: unsubscribeUrl,
question1Title: contractsToSend[0].question,
question1Link: contractUrl(contractsToSend[0]),
question1ImgSrc: imageSourceUrl(contractsToSend[0]),
question2Title: contractsToSend[1].question,
question2Link: contractUrl(contractsToSend[1]),
question2ImgSrc: imageSourceUrl(contractsToSend[1]),
question3Title: contractsToSend[2].question,
question3Link: contractUrl(contractsToSend[2]),
question3ImgSrc: imageSourceUrl(contractsToSend[2]),
question4Title: contractsToSend[3].question,
question4Link: contractUrl(contractsToSend[3]),
question4ImgSrc: imageSourceUrl(contractsToSend[3]),
question5Title: contractsToSend[4].question,
question5Link: contractUrl(contractsToSend[4]),
question5ImgSrc: imageSourceUrl(contractsToSend[4]),
question6Title: contractsToSend[5].question,
question6Link: contractUrl(contractsToSend[5]),
question6ImgSrc: imageSourceUrl(contractsToSend[5]),
},
deliveryTime ? { 'o:deliverytime': deliveryTime } : undefined
)
}
function contractUrl(contract: Contract) {
return `https://manifold.markets/${contract.creatorUsername}/${contract.slug}`
}
function imageSourceUrl(contract: Contract) {
return buildCardUrl(getOpenGraphProps(contract))
}