2022-05-09 13:04:36 +00:00
|
|
|
import { Binary, CPMM, DPM, FullContract } from 'common/contract'
|
|
|
|
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-04-20 14:13:39 +00:00
|
|
|
|
|
|
|
export const useSaveShares = (
|
|
|
|
contract: FullContract<CPMM | DPM, Binary>,
|
|
|
|
userBets: Bet[] | undefined
|
|
|
|
) => {
|
|
|
|
const [savedShares, setSavedShares] = useState<
|
|
|
|
| {
|
|
|
|
yesShares: number
|
|
|
|
noShares: number
|
|
|
|
yesFloorShares: number
|
|
|
|
noFloorShares: number
|
|
|
|
}
|
|
|
|
| undefined
|
|
|
|
>()
|
|
|
|
|
2022-05-22 08:36:05 +00:00
|
|
|
const [yesBets, noBets] = partition(
|
2022-04-20 14:13:39 +00:00
|
|
|
userBets ?? [],
|
|
|
|
(bet) => bet.outcome === 'YES'
|
|
|
|
)
|
|
|
|
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(() => {
|
|
|
|
// Save yes and no shares to local storage.
|
|
|
|
const savedShares = localStorage.getItem(`${contract.id}-shares`)
|
|
|
|
if (!userBets && savedShares) {
|
|
|
|
setSavedShares(JSON.parse(savedShares))
|
|
|
|
}
|
|
|
|
|
|
|
|
if (userBets) {
|
|
|
|
const updatedShares = { yesShares, noShares }
|
|
|
|
localStorage.setItem(
|
|
|
|
`${contract.id}-shares`,
|
|
|
|
JSON.stringify(updatedShares)
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}, [contract.id, userBets, noShares, yesShares])
|
|
|
|
|
|
|
|
if (userBets) return { yesShares, noShares, yesFloorShares, noFloorShares }
|
|
|
|
return (
|
|
|
|
savedShares ?? {
|
|
|
|
yesShares: 0,
|
|
|
|
noShares: 0,
|
|
|
|
yesFloorShares: 0,
|
|
|
|
noFloorShares: 0,
|
|
|
|
}
|
|
|
|
)
|
|
|
|
}
|