Skip to content

Commit

Permalink
feat: fix randomness bug
Browse files Browse the repository at this point in the history
  • Loading branch information
RasenGUY committed Dec 8, 2023
1 parent 45877de commit 7c64df6
Show file tree
Hide file tree
Showing 6 changed files with 30 additions and 38 deletions.
11 changes: 5 additions & 6 deletions src/components/CreateGameCard/CreateCoinFlipGameCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ import { ErrorMessage } from '@hookform/error-message';
import { ArrowDownIcon, StarLoaderIcon } from '../../assets/icons';
import tw from 'twin.macro';
import { useForm } from 'react-hook-form';
import { useCreateGameParams, useNavigateTo, useWegaStore, useTokenUSDValue, useDrand } from '../../hooks';
import { useCreateGameParams, useNavigateTo, useWegaStore, useTokenUSDValue } from '../../hooks';
import {
useCreateWagerAndDepositMutation,
useAllowanceQuery,
useApproveERC20Mutation,
} from './blockchainApiSlice';
import { useCreateGameMutation } from './apiSlice';
import { useCreateGameMutation, useGetRandomNumberQuery } from './apiSlice';
import { toastSettings, toBigIntInWei, escrowConfig, parseTopicDataFromEventLogs, convertBytesToNumber, parseError } from '../../utils';
import Button from '../../common/Button';
import { ToggleWagerBadge } from '../../common/ToggleWagerBadge';
Expand Down Expand Up @@ -69,7 +69,7 @@ export const CreateCoinFlipGameCard = ({
const { wallet, network, user} = useWegaStore();
const formRef = useRef<HTMLFormElement>(null);
const detailsBlock = useRef<HTMLDivElement>(null)
const drand = useDrand();
const drand = useGetRandomNumberQuery(undefined);
const [currentWagerType] = useState<AllPossibleWagerTypes>(wagerType);
const [currentCurrencyType, setCurrentCurrencyType] = useState<AllPossibleCurrencyTypes>(currencyType);
const [currentCoinSide, setCurrentCoinSide] = useState<AllPossibleCoinSides>(CoinSideTypes[CoinSideTypesEnum.HEADS]);
Expand Down Expand Up @@ -114,15 +114,14 @@ export const CreateCoinFlipGameCard = ({
const handleCreateGameClick = async ({ wager }: { wager: number }) => {
try {
if(!isWagerApproved(allowanceQuery.data, toBigIntInWei(String(wager), tokenDecimals))) {
console.log(toBigIntInWei(String(watch('wager')), tokenDecimals).toString())
await approveERC20({
spender: escrowConfig.address[network?.id as keyof typeof escrowConfig.address],
wagerAsBigint: toBigIntInWei(String(wager), tokenDecimals),
tokenAddress
}).unwrap();
}
const receipt = await createWagerAndDeposit({
tokenAddress, wagerAsBigint: toBigIntInWei(String(wager), tokenDecimals), gameType, randomness: [convertBytesToNumber(drand.randomness)] }).unwrap();
tokenAddress, wagerAsBigint: toBigIntInWei(String(wager), tokenDecimals), gameType, randomness: [convertBytesToNumber(drand.data.randomness)] }).unwrap();
const parsedTopicData = parseTopicDataFromEventLogs(receipt.logs, ['event GameCreation(bytes32 indexed escrowHash, uint256 indexed nonce, address creator, string name)']);
await createGame({
gameType,
Expand Down Expand Up @@ -170,7 +169,7 @@ export const CreateCoinFlipGameCard = ({
tokenDecimals
]);

return drand && tokenDecimals ? (
return drand?.data && tokenDecimals ? (
<form
tw="w-full flex flex-col justify-center items-center"
onSubmit={handleSubmit(handleCreateGameClick)}
Expand Down
12 changes: 6 additions & 6 deletions src/components/CreateGameCard/CreateDiceGameCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ import { ArrowDownIcon, StarLoaderIcon } from '../../assets/icons';
import tw from 'twin.macro';
import { useForm } from 'react-hook-form';
import { useBalance } from 'wagmi';
import { useNavigateTo, useWegaStore, useCreateGameParams, useTokenUSDValue, useDrand} from '../../hooks';
import { useCreateGameMutation } from './apiSlice';
import { useNavigateTo, useWegaStore, useCreateGameParams, useTokenUSDValue } from '../../hooks';
import { useCreateGameMutation, useGetRandomNumberQuery } from './apiSlice';
import {
useCreateWagerAndDepositMutation,
useAllowanceQuery,
Expand All @@ -55,6 +55,7 @@ import { ComponentLoader } from '../../common/loaders'




export interface CreateGameCardInterface {
wagerType: AllPossibleWagerTypes;
currencyType: AllPossibleCurrencyTypes;
Expand All @@ -71,7 +72,7 @@ export const CreateDiceGameCard = ({
}: CreateGameCardInterface & React.Attributes & React.AllHTMLAttributes<HTMLDivElement> ) => {
const { openConnectModal } = useConnectModal();
const { wallet, user, network } = useWegaStore();
const randomness = useDrand();
const randomness = useGetRandomNumberQuery(undefined);
const formRef = useRef<HTMLFormElement>(null);
const detailsBlock = useRef<HTMLDivElement>(null)
const [currentWagerType] = useState<AllPossibleWagerTypes>(wagerType);
Expand Down Expand Up @@ -114,7 +115,6 @@ export const CreateDiceGameCard = ({
}] = useCreateGameMutation();

const handleCreateGameClick = async ({ wager }: { wager: number }) => {

try {
if(!isWagerApproved(allowanceQuery.data, toBigIntInWei(String(wager), tokenDecimals))) {
await approveERC20({
Expand All @@ -127,7 +127,7 @@ export const CreateDiceGameCard = ({
tokenAddress,
wagerAsBigint: toBigIntInWei(String(wager), tokenDecimals),
gameType,
randomness: [convertBytesToNumber(randomness.randomness)]
randomness: [convertBytesToNumber(randomness.data.randomness)]
}).unwrap();
const parsedTopicData = parseTopicDataFromEventLogs(receipt.logs, ['event GameCreation(bytes32 indexed escrowHash, uint256 indexed nonce, address creator, string name)']);
await createGame({
Expand Down Expand Up @@ -177,7 +177,7 @@ export const CreateDiceGameCard = ({
useEffect(() => {
allowanceQuery.refetch();
}, [ watch('wager'), playerAddress, tokenAddress ]);
return randomness ? (
return randomness?.data ? (
<form
tw="w-full flex flex-row justify-center"
onSubmit={handleSubmit(handleCreateGameClick)}
Expand Down
10 changes: 5 additions & 5 deletions src/components/JoinGameCard/JoinCoinFlipGameCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,10 @@ import { ArrowDownIcon, StarLoaderIcon } from '../../assets/icons';
import tw from 'twin.macro';
import { useForm } from 'react-hook-form';
import { useBalance } from 'wagmi';
import { useNavigateTo, useCreateGameParams, useWegaStore, useTokenUSDValue, useDrand } from '../../hooks';
import { useNavigateTo, useCreateGameParams, useWegaStore, useTokenUSDValue } from '../../hooks';
import { useDepositAndJoinCoinflipMutation } from './blockchainApiSlice';
import { useAllowanceQuery, useApproveERC20Mutation } from '../CreateGameCard/blockchainApiSlice';
import { useGetRandomNumberQuery } from '../CreateGameCard/apiSlice';
import toast from 'react-hot-toast';
import { toastSettings, escrowConfig, convertBytesToNumber, parseError } from '../../utils';
import Button from '../../common/Button';
Expand Down Expand Up @@ -78,8 +79,7 @@ const JoinCoinFlipGameCard = ({
}: JoinCoinFlipGameCardProps) => {
const { openConnectModal } = useConnectModal();
const { wallet, user, network } = useWegaStore();
const drand = useDrand();

const drand = useGetRandomNumberQuery(undefined);
const formRef = useRef<HTMLFormElement>(null);
const detailsBlock = useRef<HTMLDivElement>(null)
const [currentWagerType] = useState<AllPossibleWagerTypes>(wagerType);
Expand Down Expand Up @@ -127,7 +127,7 @@ const JoinCoinFlipGameCard = ({
}).unwrap();
}
const playerChoices = [Number(gameAttributes[0].value), currentCoinSide];
await depositAndJoinCoinflip({escrowHash: escrowId, playerChoices, randomness: [convertBytesToNumber(drand.randomness)] }).unwrap();
await depositAndJoinCoinflip({escrowHash: escrowId, playerChoices, randomness: [convertBytesToNumber(drand?.data.randomness)] }).unwrap();
await joinGame({ newPlayerUuid: playerUuid, gameUuid }).unwrap();
await updateGame({
uuid: gameUuid,
Expand Down Expand Up @@ -162,7 +162,7 @@ const JoinCoinFlipGameCard = ({
tokenDecimals
]);

return drand && tokenDecimals ? (
return drand?.data && tokenDecimals ? (
<form
tw="w-full flex flex-col justify-center items-center"
onSubmit={handleSubmit(handleDepositWagerClick)}
Expand Down
11 changes: 7 additions & 4 deletions src/components/JoinGameCard/JoinDiceGamecard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,11 @@ import { ArrowDownIcon, StarLoaderIcon } from '../../assets/icons';
import tw from 'twin.macro';
import { useForm } from 'react-hook-form';
import { useBalance } from 'wagmi';
import { useCreateGameParams, useWegaStore, useNavigateTo, useTokenUSDValue, useDrand } from '../../hooks';
import { useCreateGameParams, useWegaStore, useNavigateTo, useTokenUSDValue } from '../../hooks';
import { useDepositAndJoinDiceMutation } from './blockchainApiSlice';
import { useAllowanceQuery, useApproveERC20Mutation } from '../CreateGameCard/blockchainApiSlice';
import { useGetRandomNumberQuery } from '../CreateGameCard/apiSlice';

import toast from 'react-hot-toast';
import {
toastSettings,
Expand Down Expand Up @@ -66,7 +68,8 @@ const JoinGameDiceCard: React.FC<JoinDiceGameCardProps> = ({
}: JoinDiceGameCardProps) => {
const { openConnectModal } = useConnectModal();
const { wallet, user, network } = useWegaStore();
const drand = useDrand();
const drand = useGetRandomNumberQuery(undefined);

const formRef = useRef<HTMLFormElement>(null);
const detailsBlock = useRef<HTMLDivElement>(null)
const [currentWagerType] = useState<AllPossibleWagerTypes>(wagerType);
Expand Down Expand Up @@ -116,7 +119,7 @@ const JoinGameDiceCard: React.FC<JoinDiceGameCardProps> = ({
}
await depositAndJoinDice({
escrowHash: escrowId,
randomness: [convertBytesToNumber(drand.randomness)]
randomness: [convertBytesToNumber(drand.data.randomness)]
}).unwrap();
await joinGame({ newPlayerUuid: playerUuid, gameUuid }).unwrap();
await updateGame({ uuid: gameUuid, state: WegaState.PLAYING }).unwrap();
Expand All @@ -140,7 +143,7 @@ const JoinGameDiceCard: React.FC<JoinDiceGameCardProps> = ({
tokenDecimals
]);

return drand && tokenDecimals ? (
return drand?.data && tokenDecimals ? (
<form
tw="w-full flex flex-row justify-center"
onSubmit={handleSubmit(handleDepositWagerClick)}
Expand Down
20 changes: 5 additions & 15 deletions src/hooks/useDrand.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,19 @@
import {useEffect, useState} from 'react'
import { useGetRandomNumberQuery } from '../components/CreateGameCard/apiSlice';
import { convertBytesToNumber} from '../utils'
export function useDrand() {
const randomness = useGetRandomNumberQuery(undefined);
// eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
const [drandInLocalStorage, _] = useState<string>(window.localStorage.getItem('drand') ?? 'empty');
const [currentDrand, setCurrentDrand] = useState<any>(null);

useEffect(() => {
if(drandInLocalStorage === 'empty' && randomness?.data) {
if(!currentDrand && randomness?.data){
setCurrentDrand(randomness.data);
console.log(randomness?.data.randomness && convertBytesToNumber(randomness?.data.randomness))
} else {
setTimeout(() => {
randomness.refetch();
}, (60 * 1000) * 3);
} else if (drandInLocalStorage !== 'empty' && randomness?.data) {
setCurrentDrand(JSON.parse(drandInLocalStorage));
window.localStorage.setItem('drand', JSON.stringify(randomness?.data ?? 'empty'))
}
if(drandInLocalStorage === 'empty' && (randomness.data && randomness.data?.round === JSON.parse(drandInLocalStorage).round)){
setTimeout(() => {
randomness.refetch();
}, (60 * 1000) * 3);
} else {
window.localStorage.setItem('drand', JSON.stringify(randomness?.data ?? 'empty'))
}
}, [randomness?.data, randomness?.isLoading, setCurrentDrand]);

}, [randomness?.data, randomness?.isLoading]);
return currentDrand;
}
4 changes: 2 additions & 2 deletions src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ import { gamesApiSlice } from './components/WegaGames/apiSlice.ts'
import './themes/index.css'
import GlobalStyles from "./themes/GlobalStyles.tsx";
import WalletProvider from './containers/WalletProvider/index.tsx'

import { defaultNetwork } from "./models/constants.ts";
// TODO
// remove old api files
store.dispatch(gamesApiSlice.endpoints.getGames.initiate(undefined));
store.dispatch(gamesApiSlice.endpoints.getGames.initiate({ networkId: defaultNetwork?.id }));
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<ReduxProvider store={store}>
Expand Down

0 comments on commit 7c64df6

Please sign in to comment.