2022-05-25 22:51:33 +00:00
|
|
|
import {
|
|
|
|
Binary,
|
|
|
|
CPMM,
|
|
|
|
DPM,
|
|
|
|
FreeResponseContract,
|
|
|
|
FullContract,
|
|
|
|
} from 'common/contract'
|
2022-05-09 13:04:36 +00:00
|
|
|
import { Bet } from 'common/bet'
|
2022-04-20 14:13:39 +00:00
|
|
|
import { useEffect, useState } from 'react'
|
2022-05-22 08:36:05 +00:00
|
|
|
import { partition, sumBy } from 'lodash'
|
2022-05-26 05:30:03 +00:00
|
|
|
import { safeLocalStorage } from 'web/lib/util/local'
|
2022-04-20 14:13:39 +00:00
|
|
|
|
|
|
|
export const useSaveShares = (
|
2022-05-25 22:51:33 +00:00
|
|
|
contract: FullContract<CPMM | DPM, Binary | FreeResponseContract>,
|
|
|
|
userBets: Bet[] | undefined,
|
|
|
|
freeResponseAnswerOutcome?: string
|
2022-04-20 14:13:39 +00:00
|
|
|
) => {
|
|
|
|
const [savedShares, setSavedShares] = useState<
|
|
|
|
| {
|
|
|
|
yesShares: number
|
|
|
|
noShares: number
|
|
|
|
yesFloorShares: number
|
|
|
|
noFloorShares: number
|
|
|
|
}
|
|
|
|
| undefined
|
|
|
|
>()
|
|
|
|
|
2022-05-25 22:51:33 +00:00
|
|
|
// TODO: How do we handle numeric yes / no bets? - maybe bet amounts above vs below the highest peak
|
|
|
|
const [yesBets, noBets] = partition(userBets ?? [], (bet) =>
|
|
|
|
freeResponseAnswerOutcome
|
|
|
|
? bet.outcome === freeResponseAnswerOutcome
|
|
|
|
: bet.outcome === 'YES'
|
2022-04-20 14:13:39 +00:00
|
|
|
)
|
|
|
|
const [yesShares, noShares] = [
|
2022-05-22 08:36:05 +00:00
|
|
|
sumBy(yesBets, (bet) => bet.shares),
|
|
|
|
sumBy(noBets, (bet) => bet.shares),
|
2022-04-20 14:13:39 +00:00
|
|
|
]
|
|
|
|
|
2022-05-02 16:16:29 +00:00
|
|
|
const yesFloorShares = Math.round(yesShares) === 0 ? 0 : Math.floor(yesShares)
|
|
|
|
const noFloorShares = Math.round(noShares) === 0 ? 0 : Math.floor(noShares)
|
2022-04-20 14:13:39 +00:00
|
|
|
|
|
|
|
useEffect(() => {
|
2022-05-26 05:30:03 +00:00
|
|
|
const local = safeLocalStorage()
|
2022-04-20 14:13:39 +00:00
|
|
|
// Save yes and no shares to local storage.
|
2022-05-26 05:30:03 +00:00
|
|
|
const savedShares = local?.getItem(`${contract.id}-shares`)
|
2022-04-20 14:13:39 +00:00
|
|
|
if (!userBets && savedShares) {
|
|
|
|
setSavedShares(JSON.parse(savedShares))
|
|
|
|
}
|
|
|
|
|
|
|
|
if (userBets) {
|
|
|
|
const updatedShares = { yesShares, noShares }
|
2022-05-26 05:30:03 +00:00
|
|
|
local?.setItem(`${contract.id}-shares`, JSON.stringify(updatedShares))
|
2022-04-20 14:13:39 +00:00
|
|
|
}
|
|
|
|
}, [contract.id, userBets, noShares, yesShares])
|
|
|
|
|
|
|
|
if (userBets) return { yesShares, noShares, yesFloorShares, noFloorShares }
|
|
|
|
return (
|
|
|
|
savedShares ?? {
|
|
|
|
yesShares: 0,
|
|
|
|
noShares: 0,
|
|
|
|
yesFloorShares: 0,
|
|
|
|
noFloorShares: 0,
|
|
|
|
}
|
|
|
|
)
|
|
|
|
}
|