Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reenable loans and store on contract metrics #3188

Merged
merged 21 commits into from
Dec 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 25 additions & 12 deletions backend/api/src/get-balance-changes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,29 +13,36 @@ import { convertContract } from 'common/supabase/contracts'
export const getBalanceChanges: APIHandler<'get-balance-changes'> = async (
props
) => {
const { after, userId } = props
const { userId, before, after } = props
const [betBalanceChanges, txnBalanceChanges] = await Promise.all([
getBetBalanceChanges(after, userId),
getTxnBalanceChanges(after, userId),
getBetBalanceChanges(before, after, userId),
getTxnBalanceChanges(before, after, userId),
])
return orderBy(
const allChanges = orderBy(
[...betBalanceChanges, ...txnBalanceChanges],
(change) => change.createdTime,
'desc'
)
return allChanges
}

const getTxnBalanceChanges = async (after: number, userId: string) => {
const getTxnBalanceChanges = async (
before: number | undefined,
after: number,
userId: string
) => {
const pg = createSupabaseDirectClient()
const balanceChanges = [] as TxnBalanceChange[]

const txns = await pg.map(
`select *
from txns
where created_time > millis_to_ts($1)
and (to_id = $2 or from_id = $2)
where
($1 is null or created_time < millis_to_ts($1)) and
created_time >= millis_to_ts($2)
and (to_id = $3 or from_id = $3)
order by created_time`,
[after, userId],
[before, after, userId],
convertTxn
)
const contractIds = filterDefined(
Expand Down Expand Up @@ -113,7 +120,11 @@ const getContractIdFromTxn = (txn: Txn) => {
return null
}

const getBetBalanceChanges = async (after: number, userId: string) => {
const getBetBalanceChanges = async (
before: number | undefined,
after: number,
userId: string
) => {
const pg = createSupabaseDirectClient()
const contractToBets: {
[contractId: string]: {
Expand All @@ -133,11 +144,13 @@ const getBetBalanceChanges = async (after: number, userId: string) => {
from contract_bets cb
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
where
($1 is null or cb.updated_time < millis_to_ts($1))
and cb.updated_time >= millis_to_ts($2)
and cb.user_id = $3
group by c.id;
`,
[after, userId],
[before, after, userId],
(row) => {
contractToBets[row.id] = {
bets: orderBy(row.bets, (bet) => bet.createdTime, 'asc'),
Expand Down
13 changes: 13 additions & 0 deletions backend/api/src/get-next-loan-amount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { type APIHandler } from './helpers/endpoint'
import { getNextLoanAmountResults } from 'api/request-loan'

export const getNextLoanAmount: APIHandler<'get-next-loan-amount'> = async ({
userId,
}) => {
try {
const { result } = await getNextLoanAmountResults(userId)
return { amount: result.payout }
} catch (e) {
return { amount: 0 }
}
}
5 changes: 3 additions & 2 deletions backend/api/src/league-activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,9 @@ export const getLeagueActivity = async (
`select
data from contracts
where
contracts.id = any($1)
and contracts.visibility = 'public'
id = any($1)
and visibility = 'public'
and token = 'MANA'
`,
[contractIds],
(row) => row.data
Expand Down
18 changes: 7 additions & 11 deletions backend/api/src/multi-sell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ import { APIError, type APIHandler } from './helpers/endpoint'
import { onCreateBets } from 'api/on-create-bet'
import { executeNewBetResult } from 'api/place-bet'
import { getContract, getUser, log } from 'shared/utils'
import { groupBy, mapValues, sum, sumBy } from 'lodash'
import { groupBy, keyBy, mapValues, sumBy } from 'lodash'
import { getCpmmMultiSellSharesInfo } from 'common/sell-bet'
import { incrementBalance } from 'shared/supabase/users'
import { runTransactionWithRetries } from 'shared/transact-with-retries'
import { convertBet } from 'common/supabase/bets'
import { betsQueue } from 'shared/helpers/fn-queue'
Expand Down Expand Up @@ -72,9 +71,13 @@ const multiSellMain: APIHandler<'multi-sell'> = async (props, auth) => {
)

const loanAmountByAnswerId = mapValues(
groupBy(userBets, 'answerId'),
(bets) => sumBy(bets, (bet) => bet.loanAmount ?? 0)
keyBy(
allMyMetrics.filter((m) => m.answerId !== null),
'answerId'
),
(m) => m.loan ?? 0
)

const nonRedemptionBetsByAnswerId = groupBy(
userBets.filter((bet) => bet.shares !== 0),
(bet) => bet.answerId
Expand Down Expand Up @@ -115,13 +118,6 @@ const multiSellMain: APIHandler<'multi-sell'> = async (props, auth) => {
)
results.push(result)
}
const bets = results.flatMap((r) => r.fullBets)
const loanPaid = sum(Object.values(loanAmountByAnswerId))
if (loanPaid > 0 && bets.length > 0) {
await incrementBalance(pgTrans, uid, {
balance: -loanPaid,
})
}
return results
})

Expand Down
2 changes: 1 addition & 1 deletion backend/api/src/place-bet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ export const executeNewBetResult = async (
{
id: user.id,
[contract.token === 'CASH' ? 'cashBalance' : 'balance']:
-newBet.amount - apiFee,
-newBet.amount - apiFee + (newBet.loanAmount ?? 0),
},
]
const makersByTakerBetId: Record<string, maker[]> = {
Expand Down
8 changes: 6 additions & 2 deletions backend/api/src/redeem-shares.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export const redeemShares = async (
for (const userId of userIds) {
// This should work for any sum-to-one cpmm-multi contract, as well
if (contract.outcomeType === 'NUMBER') {
const myMetrics = contractMetrics.filter((m) => m.userId === userId)
const userNonRedemptionBetsByAnswer = groupBy(
bets.filter((bet) => bet.shares !== 0 && bet.userId === userId),
(bet) => bet.answerId
Expand All @@ -67,8 +68,11 @@ export const redeemShares = async (
const minShares = min(allShares) ?? 0
if (minShares > 0 && allShares.length === contract.answers.length) {
const loanAmountByAnswerId = mapValues(
groupBy(bets, 'answerId'),
(bets) => sumBy(bets, (bet) => bet.loanAmount ?? 0)
groupBy(
myMetrics.filter((m) => m.answerId !== null),
'answerId'
),
(metrics) => sumBy(metrics, (m) => m.loan ?? 0)
)

const saleBets = getSellAllRedemptionPreliminaryBets(
Expand Down
Loading
Loading