Skip to content

Commit

Permalink
Merge branch 'main' into trading-ban
Browse files Browse the repository at this point in the history
  • Loading branch information
SirSaltyy authored Sep 18, 2024
2 parents 810b211 + c03264f commit 074f23b
Show file tree
Hide file tree
Showing 89 changed files with 3,130 additions and 2,889 deletions.
43 changes: 30 additions & 13 deletions backend/api/src/create-comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ import { millisToTs } from 'common/supabase/utils'
import { convertBet } from 'common/supabase/bets'
import { Bet } from 'common/bet'
import { runTxn } from 'shared/txn/run-txn'
import { DisplayUser } from 'common/api/user-types'
import { broadcastNewComment } from 'shared/websockets/helpers'
import { buildArray } from 'common/util/array'
import { type Contract } from 'common/contract'

export const MAX_COMMENT_JSON_LENGTH = 20000

Expand Down Expand Up @@ -80,8 +81,6 @@ export const createCommentOnContractInternal = async (
.then(convertBet)
: undefined

const bettor = bet && (await getUser(bet.userId))

const isApi = auth.creds.kind === 'key'

const comment = removeUndefinedProps({
Expand All @@ -103,7 +102,8 @@ export const createCommentOnContractInternal = async (
answerOutcome: replyToAnswerId,
visibility: contract.visibility,

...denormalizeBet(bet, bettor),
...denormalizeBet(bet, contract),

isApi,
isRepost,
} as ContractComment)
Expand Down Expand Up @@ -137,14 +137,14 @@ export const createCommentOnContractInternal = async (
}
if (replyToBetId) return

console.log('finding most recent bet')
const bet = await getMostRecentCommentableBet(
pg,
contract.id,
buildArray([contract.id, contract.siblingContractId]),
creator.id,
now,
replyToAnswerId
)
const bettor = bet && (await getUser(bet.userId))

const position = await getLargestPosition(pg, contract.id, creator.id)

Expand All @@ -157,7 +157,7 @@ export const createCommentOnContractInternal = async (
position && contract.mechanism === 'cpmm-1'
? contract.prob
: undefined,
...denormalizeBet(bet, bettor),
...denormalizeBet(bet, contract),
})
await pg.none(
`update contract_comments set data = $1 where comment_id = $2`,
Expand All @@ -175,16 +175,27 @@ export const createCommentOnContractInternal = async (
}
const denormalizeBet = (
bet: Bet | undefined,
bettor: DisplayUser | undefined | null
contract: Contract | undefined
) => {
return {
betAmount: bet?.amount,
betOutcome: bet?.outcome,
betAnswerId: bet?.answerId,
bettorId: bettor?.id,
bettorId: bet?.userId,
betOrderAmount: bet?.orderAmount,
betLimitProb: bet?.limitProb,
betId: bet?.id,

betToken:
!bet || !contract
? undefined
: bet.contractId === contract.id
? contract.token
: bet.contractId === contract.siblingContractId
? contract.token === 'MANA'
? 'CASH'
: 'MANA'
: undefined,
}
}

Expand All @@ -204,6 +215,12 @@ export const validateComment = async (
if (you.userDeleted) throw new APIError(403, 'Your account is deleted')

if (!contract) throw new APIError(404, 'Contract not found')
if (contract.token !== 'MANA') {
throw new APIError(
400,
`Can't comment on cash contract. Please do comment on the sibling mana contract ${contract.siblingContractId}`
)
}

const contentJson = content || anythingToRichText({ html, markdown })

Expand All @@ -222,7 +239,7 @@ export const validateComment = async (

async function getMostRecentCommentableBet(
pg: SupabaseDirectClient,
contractId: string,
contractIds: string[],
userId: string,
commentCreatedTime: number,
answerOutcome?: string
Expand All @@ -232,7 +249,7 @@ async function getMostRecentCommentableBet(
.map(
`with prior_user_comments_with_bets as (
select created_time, data->>'betId' as bet_id from contract_comments
where contract_id = $1 and user_id = $2
where contract_id in ($1:list) and user_id = $2
and created_time < millis_to_ts($3)
and data ->> 'betId' is not null
and created_time > millis_to_ts($3) - interval $5
Expand All @@ -246,7 +263,7 @@ async function getMostRecentCommentableBet(
as cutoff
)
select * from contract_bets
where contract_id = $1
where contract_id in ($1:list)
and user_id = $2
and ($4 is null or answer_id = $4)
and created_time < millis_to_ts($3)
Expand All @@ -255,7 +272,7 @@ async function getMostRecentCommentableBet(
order by created_time desc
limit 1
`,
[contractId, userId, commentCreatedTime, answerOutcome, maxAge],
[contractIds, userId, commentCreatedTime, answerOutcome, maxAge],
convertBet
)
.catch((e) => console.error('Failed to get bet: ' + e))
Expand Down
42 changes: 27 additions & 15 deletions backend/api/src/get-balance-changes.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { APIHandler } from 'api/helpers/endpoint'
import { createSupabaseDirectClient } from 'shared/supabase/init'
import { Bet } from 'common/bet'
import { Contract } from 'common/contract'
import { orderBy } from 'lodash'
import { BetBalanceChange, TxnBalanceChange } from 'common/balance-change'
import { Txn } from 'common/txn'
Expand Down Expand Up @@ -119,24 +118,37 @@ const getBetBalanceChanges = async (after: number, userId: string) => {
const pg = createSupabaseDirectClient()
const contractToBets: {
[contractId: string]: {
bets: Bet[]
contract: Contract
bets: (Bet & { answerText?: string | undefined })[]
contract: BetBalanceChange['contract']
}
} = {}
await pg.map(
`
select json_agg(cb.data) as bets, c.data as contract
`select
json_agg(cb.data || jsonb_build_object('answerText', a.text)) as bets,
c.id,
c.question,
c.slug,
c.visibility,
c.data->>'creatorUsername' as creator_username,
c.token
from contract_bets cb
join contracts c on cb.contract_id = c.id
join contracts c on cb.contract_id = c.id
left join answers a on a.id = cb.answer_id
where cb.updated_time > millis_to_ts($1)
and cb.user_id = $2
group by c.id;
`,
[after, userId],
(row) => {
contractToBets[row.contract.id] = {
bets: orderBy(row.bets as Bet[], (bet) => bet.createdTime, 'asc'),
contract: row.contract as Contract,
contractToBets[row.id] = {
bets: orderBy(row.bets, (bet) => bet.createdTime, 'asc'),
contract: {
question: row.question,
slug: row.slug,
visibility: row.visibility,
creatorUsername: row.creator_username,
token: row.token,
},
}
}
)
Expand All @@ -156,11 +168,7 @@ const getBetBalanceChanges = async (after: number, userId: string) => {
if (isRedemption && nextBetIsRedemption) continue
if (isRedemption && amount === 0) continue

const { question, visibility, creatorUsername, slug } = contract
const text =
contract.mechanism === 'cpmm-multi-1' && bet.answerId
? contract.answers.find((a) => a.id === bet.answerId)?.text
: undefined
const { question, visibility, creatorUsername, slug, token } = contract
const balanceChangeProps = {
key: bet.id,
bet: {
Expand All @@ -172,8 +180,12 @@ const getBetBalanceChanges = async (after: number, userId: string) => {
slug: visibility === 'public' ? slug : '',
visibility,
creatorUsername,
token,
},
answer: text && bet.answerId ? { text, id: bet.answerId } : undefined,
answer:
bet.answerText && bet.answerId
? { text: bet.answerText, id: bet.answerId }
: undefined,
}
if (bet.limitProb !== undefined && bet.fills) {
const fillsInTimeframe = bet.fills.filter(
Expand Down
2 changes: 1 addition & 1 deletion backend/api/src/gidx/complete-checkout-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ export const completeCheckoutSession: APIHandler<
await sendCoins(
userId,
paymentAmount,
CompletedPaymentAmount,
CompletedPaymentAmount * 100,
MerchantTransactionID,
SessionID,
user.sweepstakesVerified ?? false
Expand Down
18 changes: 17 additions & 1 deletion backend/api/src/place-bet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,20 @@ import {
import { removeUndefinedProps } from 'common/util/object'
import { Bet, LimitBet, maker } from 'common/bet'
import { floatingEqual } from 'common/util/math'
import { contractColumnsToSelect, log, metrics } from 'shared/utils'
import { contractColumnsToSelect, isProd, log, metrics } from 'shared/utils'
import { Answer } from 'common/answer'
import { CpmmState, getCpmmProbability } from 'common/calculate-cpmm'
import { ValidatedAPIParams } from 'common/api/schema'
import { onCreateBets } from 'api/on-create-bet'
<<<<<<< trading-ban
import { isAdminId, TWOMBA_ENABLED } from 'common/envs/constants'
=======
import {
BANNED_TRADING_USER_IDS,
isAdminId,
TWOMBA_ENABLED,
} from 'common/envs/constants'
>>>>>>> main
import * as crypto from 'crypto'
import { formatMoneyWithDecimals } from 'common/util/format'
import {
Expand Down Expand Up @@ -311,8 +319,16 @@ export const fetchContractBetDataAndValidate = async (
'You must be kyc verified to trade on sweepstakes markets.'
)
}
<<<<<<< trading-ban
if (user.userDeleted) {
throw new APIError(403, 'You are banned or deleted.')
=======
if (isAdminId(user.id) && contract.token === 'CASH' && isProd()) {
throw new APIError(403, 'Admins cannot trade on sweepstakes markets.')
}
if (BANNED_TRADING_USER_IDS.includes(user.id) || user.userDeleted) {
throw new APIError(403, 'You are banned or deleted. And not #blessed.')
>>>>>>> main
}
log(
`Loaded user ${user.username} with id ${user.id} betting on slug ${contract.slug} with contract id: ${contract.id}.`
Expand Down
5 changes: 5 additions & 0 deletions backend/api/src/stripe-endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { APIError } from 'common/api/utils'
import { runTxn } from 'shared/txn/run-txn'
import { createSupabaseDirectClient } from 'shared/supabase/init'
import { updateUser } from 'shared/supabase/users'
import { TWOMBA_ENABLED } from 'common/envs/constants'

export type StripeSession = Stripe.Event.Data.Object & {
id: string
Expand Down Expand Up @@ -54,6 +55,10 @@ const mappedDollarAmounts = {
} as { [key: string]: number }

export const createcheckoutsession = async (req: Request, res: Response) => {
if (TWOMBA_ENABLED) {
res.status(400).send('Stripe purchases are disabled')
return
}
const userId = req.query.userId?.toString()

const manticDollarQuantity = req.query.manticDollarQuantity?.toString()
Expand Down
27 changes: 16 additions & 11 deletions backend/scripts/calculate-kyc-bonus-rewards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,33 @@ import { runScript } from './run-script'
import { type SupabaseDirectClient } from 'shared/supabase/init'
import { bulkUpsert } from 'shared/supabase/utils'

const TIMESTAMP = '2023-08-26 09:00:00'
const TIMESTAMP = '2024-09-17 09:50:00-07'

async function calculateKycBonusRewards(pg: SupabaseDirectClient) {
const allBalances = await pg.manyOrNone<{
user_id: string
reward_amount: number
}>(
`with last_entries as (
select distinct on (user_id)
select
user_id,
investment_value,
balance,
spice_balance,
loan_total,
ts
from user_portfolio_history
where ts <= $1
order by user_id, ts desc
uph.investment_value,
uph.balance,
uph.spice_balance,
uph.loan_total,
uph.ts
from
users u left join lateral (
select * from user_portfolio_history
where user_id = u.id
and ts <= $1
order by ts desc
limit 1
) uph on true
)
select
user_id,
(investment_value + balance + spice_balance - loan_total) / 1000 as reward_amount
(investment_value + balance + spice_balance) / 1000 as reward_amount
from last_entries`,
[TIMESTAMP]
)
Expand Down
50 changes: 50 additions & 0 deletions backend/scripts/send-sweepcash.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { HOUSE_LIQUIDITY_PROVIDER_ID } from 'common/antes'
import { runScript } from 'run-script'
import { runTxn } from 'shared/txn/run-txn'

// Change these to insert different txns
const groupId = 'additional-kyc-gift'
const amounts = [
{ id: '5LZ4LgYuySdL1huCWe7bti02ghx2', amount: 290.6006599286618 }, // James
{ id: 'Rcnau899SsWFEuL0ukY1hMGkath2', amount: 24.300307345553185 }, // Alex Miller
// { id: 'tlmGNz9kjXc2EteizMORes4qvWl2', amount: 1048.4065420277594 }, // SG
{ id: 'eBUNDUcrRMYeoRqfFsEcA0UonV33', amount: 0.00941605912381928 }, // jan
{ id: 'XtJuqIcTwEa5WnmBtmypEKyjlfu1', amount: 112.2789688018984 }, // Henri Thunberg 🔸
// { id: 'AJwLWoo3xue32XIiAVrL5SyR1WB2', amount: 32.866559589740005 }, // Ian Philips
{ id: 'tNQuBL6vsShm46bi4ciIWxcMTmR2', amount: 21.85886754045586 }, // Dan Wahl
{ id: 'zNIw5HrrF9QygZZhTiciun5GEef2', amount: 0.02294625926951672 }, // bob henry
{ id: 'd9vxoU9czxR8HkgfMdwwTmVBQ3y2', amount: 0.8558657801231295 }, // Bence
]

if (require.main === module) {
const message = process.argv[2]
if (!message) {
console.error('Please provide a message as the first argument')
process.exit(1)
}

runScript(async ({ pg }) => {
await pg.tx(async (tx) => {
for (const { id, amount } of amounts) {
await runTxn(tx, {
fromType: 'USER',
fromId: HOUSE_LIQUIDITY_PROVIDER_ID,
toType: 'USER',
toId: id,
amount,
token: 'CASH',
category: 'MANA_PAYMENT',
data: {
message,
groupId,
visibility: 'public',
},
description: message,
})
console.log(`Sent $${amount} in sweepstakes cash to ${id}`)
}
})

console.log('complete')
})
}
Loading

0 comments on commit 074f23b

Please sign in to comment.