Skip to content

Commit

Permalink
feat: ref mainnent
Browse files Browse the repository at this point in the history
  • Loading branch information
RasenGUY committed Dec 5, 2023
1 parent a356dc3 commit eec2e73
Show file tree
Hide file tree
Showing 14 changed files with 171 additions and 88 deletions.
19 changes: 12 additions & 7 deletions src/components/CreateGameCard/CreateCoinFlipGameCard.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { useEffect, useRef, useState } from 'react';
import Joi from 'joi';
import { parseEther } from 'ethers';
import { useBalance } from 'wagmi';
import toast from 'react-hot-toast';
import {
Expand Down Expand Up @@ -75,7 +74,7 @@ export const CreateCoinFlipGameCard = ({
const [currentCurrencyType, setCurrentCurrencyType] = useState<AllPossibleCurrencyTypes>(currencyType);
const [currentCoinSide, setCurrentCoinSide] = useState<AllPossibleCoinSides>(CoinSideTypes[CoinSideTypesEnum.HEADS]);
const {revealed, triggerRevealAnimation} = useFormReveal(false, formRef, detailsBlock);
const { playerAddress, tokenAddress, playerUuid} = useCreateGameParams({
const { playerAddress, tokenAddress, playerUuid, tokenDecimals } = useCreateGameParams({
wallet, network, user, currencyType: currentCurrencyType
});

Expand All @@ -90,7 +89,11 @@ export const CreateCoinFlipGameCard = ({

// approval for allowance
const wagerUSDValue = useTokenUSDValue(currentCurrencyType, watch('wager'));
const isWagerApproved = (allowance: number, wagerAmount: number) => allowance >= wagerAmount;
const isWagerApproved = (allowance: string, wagerAmount: number, withDecimals?: boolean ) => {
if(withDecimals) return toBigIntInWei(allowance, tokenDecimals) >= toBigIntInWei(String(wagerAmount), tokenDecimals);
return toBigIntInWei(allowance) >= toBigIntInWei(String(wagerAmount), tokenDecimals); // if decimals then the correct wei amount will be returned
};

const allowanceQuery = useAllowanceQuery({
spender: escrowConfig.address[network?.id as keyof typeof escrowConfig.address],
owner: playerAddress,
Expand All @@ -116,9 +119,12 @@ export const CreateCoinFlipGameCard = ({
try {
if(!isWagerApproved(allowanceQuery.data, wager)) {
await approveERC20({
spender: escrowConfig.address[network?.id as keyof typeof escrowConfig.address], wagerAsBigint: toBigIntInWei(wager), tokenAddress }).unwrap();
spender: escrowConfig.address[network?.id as keyof typeof escrowConfig.address],
wagerAsBigint: toBigIntInWei(String(wager), tokenDecimals),
tokenAddress
}).unwrap();
}
const receipt = await createWagerAndDeposit({ tokenAddress, wagerAsBigint: toBigIntInWei(wager), gameType, randomness: [convertBytesToNumber(drand.randomness)] }).unwrap();
const receipt = await createWagerAndDeposit({ tokenAddress, wagerAsBigint: toBigIntInWei(String(wager), tokenDecimals), gameType, randomness: [convertBytesToNumber(drand.randomness)] }).unwrap();
const parsedTopicData = parseTopicDataFromEventLog(receipt.logs[2], ['event GameCreation(bytes32 indexed escrowHash, uint256 indexed nonce, address creator, string name)']);
await createGame({
gameType,
Expand All @@ -130,7 +136,7 @@ export const CreateCoinFlipGameCard = ({
wagerType: currentWagerType.toUpperCase() as AllPossibleWagerTypes,
wagerHash: parsedTopicData?.escrowHash,
tokenAddress,
wagerAmount: parseEther(String(wager)).toString(),
wagerAmount: toBigIntInWei(String(wager), tokenDecimals).toString(),
wagerCurrency: currentCurrencyType,
nonce: Number(parsedTopicData?.nonce),
},
Expand All @@ -153,7 +159,6 @@ export const CreateCoinFlipGameCard = ({
useEffect(() => {
if(wallet){
allowanceQuery.refetch();

if(createGameStatus === 'fulfilled' && createGameResponse) {
navigateToGameUi(`/play/${gameType.toLowerCase()}/${createGameResponse.uuid}`, 1500, { replace: true,
state: { gameId: createGameResponse.id, gameUuid: createGameResponse.uuid } });
Expand Down
35 changes: 21 additions & 14 deletions src/components/CreateGameCard/CreateDiceGameCard.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { useEffect, useRef, useState } from 'react';
import { parseEther } from 'ethers';
import Joi from 'joi';
import {
useConnectModal,
Expand All @@ -19,7 +18,7 @@ import {
AllPossibleCurrencyTypes,
AllPossibleWagerTypes,
HexishString,
AllPossibleWegaTypes,
AllPossibleWegaTypes
} from "../../models";
import {
BadgeIcon,
Expand Down Expand Up @@ -77,7 +76,7 @@ export const CreateDiceGameCard = ({
const detailsBlock = useRef<HTMLDivElement>(null)
const [currentWagerType] = useState<AllPossibleWagerTypes>(wagerType);
const [currentCurrencyType, setCurrentCurrencyType] = useState<AllPossibleCurrencyTypes>(currencyType);
const {tokenAddress, playerAddress, playerUuid } = useCreateGameParams({ wallet, user, network, currencyType: currentCurrencyType});
const {tokenAddress, playerAddress, playerUuid, tokenDecimals } = useCreateGameParams({ wallet, user, network, currencyType: currentCurrencyType});
const {revealed, triggerRevealAnimation} = useFormReveal(false, formRef, detailsBlock);
const { register, formState: { errors }, watch, handleSubmit, setValue } = useForm({
mode: 'onChange',
Expand All @@ -87,10 +86,14 @@ export const CreateDiceGameCard = ({
wager: 1
}
});
const wagerUSDValue = useTokenUSDValue(currentCurrencyType, watch('wager'));

// approval for allowance
const isWagerApproved = (allowance: number, wagerAmount: number) => allowance >= toBigIntInWei(wagerAmount);
const wagerUSDValue = useTokenUSDValue(currentCurrencyType, watch('wager'));
const isWagerApproved = (allowance: string, wagerAmount: number, withDecimals?: boolean ) => {
if(withDecimals) return toBigIntInWei(allowance, tokenDecimals) >= toBigIntInWei(String(wagerAmount), tokenDecimals);
return toBigIntInWei(allowance) >= toBigIntInWei(String(wagerAmount), tokenDecimals); // if decimals then the correct wei amount will be returned
};

const allowanceQuery = useAllowanceQuery({
spender: escrowConfig.address[network?.id as keyof typeof escrowConfig.address],
owner: playerAddress,
Expand All @@ -114,17 +117,21 @@ export const CreateDiceGameCard = ({
}] = useCreateGameMutation();

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

try {
if(!isWagerApproved(allowanceQuery.data, wager)) {
await approveERC20({ spender: escrowConfig.address[network?.id as keyof typeof escrowConfig.address], wagerAsBigint: toBigIntInWei(wager), tokenAddress }).unwrap();
if(!isWagerApproved(allowanceQuery?.data, wager)) {
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(wager),
wagerAsBigint: toBigIntInWei(String(wager), tokenDecimals),
gameType,
randomness: [convertBytesToNumber(randomness.randomness)]
}).unwrap();

const parsedTopicData = parseTopicDataFromEventLog(receipt.logs[2], ['event GameCreation(bytes32 indexed escrowHash, uint256 indexed nonce, address creator, string name)']);
await createGame({
gameType,
Expand All @@ -136,7 +143,7 @@ export const CreateDiceGameCard = ({
wagerType: currentWagerType.toUpperCase() as AllPossibleWagerTypes,
wagerHash: parsedTopicData?.escrowHash,
tokenAddress,
wagerAmount: parseEther(String(wager)).toString(),
wagerAmount: toBigIntInWei(String(wager), tokenDecimals).toString(),
wagerCurrency: currentCurrencyType,
nonce: Number(parsedTopicData?.nonce),
}
Expand All @@ -156,10 +163,7 @@ export const CreateDiceGameCard = ({

const navigateToGameUi = useNavigateTo()
useEffect(() => {
console.log(userWagerBalance)

if(playerAddress && tokenAddress){
allowanceQuery.refetch();
if(playerAddress && tokenAddress) {
if(createGameStatus === 'fulfilled' && createGameResponse) {
navigateToGameUi(`/play/${gameType.toLowerCase()}/${createGameResponse.uuid}`, 1500, { replace: true,
state: { gameId: createGameResponse.id, gameUuid: createGameResponse.uuid }
Expand All @@ -172,6 +176,9 @@ export const CreateDiceGameCard = ({
createGameStatus,
createGameResponse
]);
useEffect(() => {
allowanceQuery.refetch();
}, [ watch('wager'), playerAddress, tokenAddress ]);
return randomness ? (
<form
tw="w-full flex flex-row justify-center"
Expand Down
34 changes: 20 additions & 14 deletions src/components/JoinGameCard/JoinCoinFlipGameCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ import { useNavigateTo, useCreateGameParams, useWegaStore, useTokenUSDValue, use
import { useDepositAndJoinCoinflipMutation } from './blockchainApiSlice';
import { useAllowanceQuery, useApproveERC20Mutation } from '../CreateGameCard/blockchainApiSlice';
import toast from 'react-hot-toast';
import { toastSettings, escrowConfig, toBigIntInWei, convertBytesToNumber, parseError } from '../../utils';
import { toastSettings, escrowConfig, convertBytesToNumber, parseError, formatLowerDecimalTokenValue, exponentialToBigintInWei } from '../../utils';
import Button from '../../common/Button';
import { useFormReveal } from '../CreateGameCard/animations';
import { useJoinGameMutation, useUpdateGameMutation } from './apiSlice';
Expand Down Expand Up @@ -87,20 +87,22 @@ const JoinCoinFlipGameCard = ({
const [currentCurrencyType] = useState<AllPossibleCurrencyTypes>(currencyType);
const {revealed, triggerRevealAnimation} = useFormReveal(false, formRef, detailsBlock);
const [currentCoinSide] = useState<AllPossibleCoinSides>(gameAttributes && Number(gameAttributes[0].value) === 1 ? 2 : 1);
const {tokenAddress, playerAddress, playerUuid} = useCreateGameParams({ wallet, user, network, currencyType: currentCurrencyType }); // TODO change to generic name
const {tokenAddress, playerAddress, playerUuid, tokenDecimals } = useCreateGameParams({ wallet, user, network, currencyType: currentCurrencyType }); // TODO change to generic name

const { register, formState: { errors }, handleSubmit, watch } = useForm({
const { register, formState: { errors }, handleSubmit } = useForm({
mode: 'onChange',
resolver: joiResolver(createGameSchema('wager', wagerAmount)) ,
resolver: joiResolver(createGameSchema('wager', formatLowerDecimalTokenValue(wagerAmount, tokenDecimals))) ,
reValidateMode: 'onChange',
defaultValues: {
wager: wagerAmount,
wager: tokenDecimals && formatLowerDecimalTokenValue(wagerAmount, tokenDecimals),
}
});

// approval for allowance
const wagerUSDValue = useTokenUSDValue(currentCurrencyType, watch('wager'));
const isWagerApproved = (allowance: number, wagerAmount: number) => allowance >= wagerAmount;
const wagerUSDValue = useTokenUSDValue(currentCurrencyType, tokenDecimals && formatLowerDecimalTokenValue(wagerAmount, tokenDecimals));
const isWagerApproved = (allowance: string | number, wagerAmount: number) => {
return exponentialToBigintInWei(Number(allowance)) >= exponentialToBigintInWei(wagerAmount); // if decimals then the correct wei amount will be returned
};
const allowanceQuery = useAllowanceQuery({
spender: escrowConfig.address[network?.id as keyof typeof escrowConfig.address],
owner: playerAddress,
Expand All @@ -121,7 +123,11 @@ const JoinCoinFlipGameCard = ({
const handleDepositWagerClick = async () => {
try {
if(!isWagerApproved(allowanceQuery.data, wagerAmount)) {
await approveERC20({ spender: escrowConfig.address[network?.id as keyof typeof escrowConfig.address], wagerAsBigint: toBigIntInWei(wagerAmount), tokenAddress }).unwrap();
await approveERC20({
spender: escrowConfig.address[network?.id as keyof typeof escrowConfig.address],
wagerAsBigint: exponentialToBigintInWei(wagerAmount),
tokenAddress
}).unwrap();
}
const playerChoices = [Number(gameAttributes[0].value), currentCoinSide];
await depositAndJoinCoinflip({escrowHash: escrowId, playerChoices, randomness: [convertBytesToNumber(drand.randomness)] }).unwrap();
Expand Down Expand Up @@ -153,10 +159,12 @@ const JoinCoinFlipGameCard = ({
allowanceQuery.refetch();
}, [
tokenAddress,
wagerAmount
playerAddress,
wagerAmount,
tokenDecimals
]);

return drand ? (
return drand && tokenDecimals ? (
<form
tw="w-full flex flex-col justify-center items-center"
onSubmit={handleSubmit(handleDepositWagerClick)}
Expand All @@ -176,9 +184,7 @@ const JoinCoinFlipGameCard = ({
<div >
{/* wager */}
<div tw="flex flex-col items-center gap-y-[16px]">
<InputBox tw="pointer-events-none" type="number" step="any" { ...register('wager', {
setValueAs: () => wagerAmount,
}) }/>
<InputBox tw="pointer-events-none" type="number" step="any" defaultValue={formatLowerDecimalTokenValue(wagerAmount, tokenDecimals)} { ...register('wager') }/>
<ErrorMessage
errors={errors}
name="wager"
Expand Down Expand Up @@ -219,7 +225,7 @@ const JoinCoinFlipGameCard = ({
<div tw="flex justify-between p-[20px] items-center" className="details-1 invisible">
<LargeText>Wager</LargeText>
<div tw="dark:bg-[#4B4B4B] rounded-[10px] flex w-[fit-content] justify-center items-center gap-[10px] py-[5px] px-[10px]">
<span>{wagerAmount}</span>
<span>{formatLowerDecimalTokenValue(wagerAmount, tokenDecimals)}</span>
<BadgeIcon><>{renderWagerBadge(currentWagerType, currentCurrencyType)}</></BadgeIcon>
<span>{currencyType}</span>
</div>
Expand Down
49 changes: 34 additions & 15 deletions src/components/JoinGameCard/JoinDiceGamecard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,21 @@ import { useCreateGameParams, useWegaStore, useNavigateTo, useTokenUSDValue, use
import { useDepositAndJoinDiceMutation } from './blockchainApiSlice';
import { useAllowanceQuery, useApproveERC20Mutation } from '../CreateGameCard/blockchainApiSlice';
import toast from 'react-hot-toast';
import { toastSettings, escrowConfig, toBigIntInWei, convertBytesToNumber, parseError } from '../../utils';
import {
toastSettings,
escrowConfig,
formatLowerDecimalTokenValue,
convertBytesToNumber,
parseError,
exponentialToBigintInWei
} from '../../utils';
import Button from '../../common/Button';
import { useFormReveal } from '../CreateGameCard/animations';
import { useJoinGameMutation, useUpdateGameMutation } from './apiSlice';
import { JoinGameCardProps } from './'
import { ComponentLoader } from '../../common/loaders'


export interface JoinDiceGameCardProps extends JoinGameCardProps, React.Attributes, React.AllHTMLAttributes<HTMLDivElement> {};

const JoinGameDiceCard: React.FC<JoinDiceGameCardProps> = ({
Expand All @@ -63,24 +71,27 @@ const JoinGameDiceCard: React.FC<JoinDiceGameCardProps> = ({
const detailsBlock = useRef<HTMLDivElement>(null)
const [currentWagerType] = useState<AllPossibleWagerTypes>(wagerType);
const [currentCurrencyType] = useState<AllPossibleCurrencyTypes>(currencyType);
const {tokenAddress, playerAddress, playerUuid} = useCreateGameParams({ wallet, user, network, currencyType: currentCurrencyType }); // TODO change to generic name
const {tokenAddress, playerAddress, playerUuid, tokenDecimals } = useCreateGameParams({ wallet, user, network, currencyType: currentCurrencyType }); // TODO change to generic name
const {revealed, triggerRevealAnimation} = useFormReveal(false, formRef, detailsBlock);


// should go into blockchain api slice
const { register, formState: { errors }, handleSubmit, watch } = useForm({
// should go into blockchain api slice
const { formState: { errors }, handleSubmit, setValue, register } = useForm({
mode: 'onChange',
resolver: joiResolver(createGameSchema('wager', wagerAmount)) ,
resolver: joiResolver(createGameSchema('wager', formatLowerDecimalTokenValue(wagerAmount, tokenDecimals))) ,
reValidateMode: 'onChange',
defaultValues: {
wager: wagerAmount,
wager: tokenDecimals && formatLowerDecimalTokenValue(wagerAmount, tokenDecimals),
}
});

const wagerUSDValue = useTokenUSDValue(currentCurrencyType, watch('wager'));
const wagerUSDValue = useTokenUSDValue(currentCurrencyType, tokenDecimals && formatLowerDecimalTokenValue(wagerAmount, tokenDecimals));

// approval for allowance
const isWagerApproved = (allowance: number, wagerAmount: number) => allowance >= wagerAmount;
const isWagerApproved = (allowance: string | number, wagerAmount: number) => {
return exponentialToBigintInWei(Number(allowance)) >= exponentialToBigintInWei(wagerAmount); // if decimals then the correct wei amount will be returned
};

const allowanceQuery = useAllowanceQuery({
spender: escrowConfig.address[network?.id as keyof typeof escrowConfig.address],
owner: playerAddress,
Expand All @@ -100,7 +111,11 @@ const JoinGameDiceCard: React.FC<JoinDiceGameCardProps> = ({
const handleDepositWagerClick = async () => {
try {
if(!isWagerApproved(allowanceQuery.data, wagerAmount)) {
await approveERC20({ spender: escrowConfig.address[network?.id as keyof typeof escrowConfig.address], wagerAsBigint: toBigIntInWei(wagerAmount), tokenAddress }).unwrap();
await approveERC20({
spender: escrowConfig.address[network?.id as keyof typeof escrowConfig.address],
wagerAsBigint: exponentialToBigintInWei(wagerAmount),
tokenAddress
}).unwrap();
}
await depositAndJoinDice({
escrowHash: escrowId,
Expand All @@ -120,9 +135,15 @@ const JoinGameDiceCard: React.FC<JoinDiceGameCardProps> = ({
const navigateToGameUi = useNavigateTo()
useEffect(() => {
allowanceQuery.refetch();
}, [tokenAddress, wagerAmount]);
if(tokenDecimals) setValue('wager', formatLowerDecimalTokenValue(wagerAmount, tokenDecimals))
}, [
tokenAddress,
playerAddress,
wagerAmount,
tokenDecimals
]);

return drand ? (
return drand && tokenDecimals ? (
<form
tw="w-full flex flex-row justify-center"
onSubmit={handleSubmit(handleDepositWagerClick)}
Expand All @@ -138,9 +159,7 @@ const JoinGameDiceCard: React.FC<JoinDiceGameCardProps> = ({
<div >
{/* wager */}
<div tw="flex flex-col items-center gap-y-[16px]">
<InputBox tw="pointer-events-none" type="number" step="any" { ...register('wager', {
setValueAs: () => wagerAmount,
}) }/>
<InputBox tw="pointer-events-none" type="number" step="none" defaultValue={formatLowerDecimalTokenValue(wagerAmount, tokenDecimals)} { ...register('wager' )} />
<ErrorMessage
errors={errors}
name="wager"
Expand Down Expand Up @@ -181,7 +200,7 @@ const JoinGameDiceCard: React.FC<JoinDiceGameCardProps> = ({
<div tw="flex justify-between p-[20px] items-center" className="details-1 invisible">
<LargeText>Wager</LargeText>
<div tw="dark:bg-[#4B4B4B] rounded-[10px] flex w-[fit-content] justify-center items-center gap-[10px] py-[5px] px-[10px]">
<span>{wagerAmount}</span>
<span>{formatLowerDecimalTokenValue(wagerAmount, tokenDecimals)}</span>
<BadgeIcon><>{renderWagerBadge(currentWagerType, currentCurrencyType)}</></BadgeIcon>
<span>{currencyType}</span>
</div>
Expand Down
Loading

0 comments on commit eec2e73

Please sign in to comment.