diff --git a/package.json b/package.json index 4523957..7e80a49 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,6 @@ "@chakra-ui/react": "^1.7.2", "@emotion/react": "^11.7.0", "@emotion/styled": "^11.6.0", - "@fontsource/titillium-web": "^4.5.9", "@near-wallet-selector/core": "^6.0.0", "@near-wallet-selector/modal-ui": "^6.0.0", "@near-wallet-selector/my-near-wallet": "^6.0.0", diff --git a/src/App.tsx b/src/App.tsx index 231cb32..9f455a1 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -4,7 +4,6 @@ import { ReactQueryDevtools } from "react-query/devtools"; import Main from "./components/Main/Main"; import { WalletSelectorContextProvider } from "./contexts/WalletSelectorContext"; import { theme } from "./components/lib/theme"; -import "@fontsource/titillium-web"; const queryClient = new QueryClient(); diff --git a/src/components/Navbar/components/ButtonConnectWallet.tsx b/src/components/Navbar/components/ButtonConnectWallet.tsx index 047550c..a5058ed 100644 --- a/src/components/Navbar/components/ButtonConnectWallet.tsx +++ b/src/components/Navbar/components/ButtonConnectWallet.tsx @@ -1,12 +1,10 @@ import { ChevronDownIcon } from "@chakra-ui/icons"; import { Button, Menu, MenuButton, MenuList } from "@chakra-ui/react"; import { useWalletSelector } from "../../../contexts/WalletSelectorContext"; -import useScreenSize from "../../../hooks/useScreenSize"; import { YellowButton } from "../../../shared/components/YellowButton"; export function ButtonConnectWallet() { const walletSelector = useWalletSelector(); - const { width } = useScreenSize(); const handleOnClick = async () => { if (walletSelector.selector.isSignedIn() && walletSelector.wallet) { @@ -27,7 +25,7 @@ export function ButtonConnectWallet() { borderRadius="full" rightIcon={} > - {walletSelector.ticTacToeLogic?.getDisplayableAccountId(width)} + {walletSelector.accountId} (); const [loadingFinalizedGame, setLoadingFinalizedGame] = useState(false); const walletSelector = useWalletSelector(); - const { width } = useScreenSize(); const handleGiveUp = () => { if (data?.active_game?.[0]) { @@ -54,7 +51,7 @@ export function ActiveGame({ }; const handleCloseGame = () => { - setActiveGameParams(initialActiveGameParamsState); + setActiveGameParams(initialActiveGameParamsState2); }; useEffect(() => { @@ -153,11 +150,7 @@ export function ActiveGame({ {activeGameParams.game_result.winner_id === walletSelector.accountId ? "You Are The Winner!" - : `The Winner is - ${formatAccountId( - activeGameParams.game_result.winner_id, - width - )}`} + : `The Winner is ${activeGameParams.game_result.winner_id}`} Reward:{" "} @@ -229,10 +222,7 @@ export function ActiveGame({ {data.active_game[1].current_player.account_id === walletSelector.accountId ? "You" - : formatAccountId( - data.active_game[1].current_player.account_id, - width - )} + : data.active_game[1].current_player.account_id} diff --git a/src/components/TicTacToe/components/Board.tsx b/src/components/TicTacToe/components/Board.tsx index 77e177b..c8fccb7 100644 --- a/src/components/TicTacToe/components/Board.tsx +++ b/src/components/TicTacToe/components/Board.tsx @@ -1,7 +1,5 @@ import { Box, Flex } from "@chakra-ui/react"; -import React, { useEffect, useState } from "react"; -import { useQuery } from "react-query"; -import { GameParams } from "../../../hooks/useContractParams"; +import React, { useState } from "react"; import { GameParamsState } from "../containers/TicTacToe"; import { BoardSquare } from "./BoardSquare"; @@ -25,9 +23,6 @@ export default function Board({ row: null, column: null, }); - - const { data } = useQuery("contractParams"); - const boardSize = { base: "260px", sm: isLandscape ? "260px" : "350px", @@ -35,7 +30,6 @@ export default function Board({ lg: "455px", "2xl": "605px", }; - const squareSize = { base: "80px", sm: isLandscape ? "80px" : "110px", @@ -44,18 +38,6 @@ export default function Board({ "2xl": "195px", }; - useEffect(() => { - if ( - data?.active_game === undefined && - loadingSquare.row && - loadingSquare.column - ) { - setLoadingSquare({ row: null, column: null }); - } - }, [data?.active_game, loadingSquare]); - - console.log(activeGameParams); - return ( ("contractParams"); + const currentPlayer = data?.active_game?.[1].current_player.account_id; const border = "5px solid"; const borderColor = "purpleCheddar"; - const tiles = data?.active_game?.[1].tiles; - const currentPlayer = data?.active_game?.[1].current_player; const handleClick = async ( e: React.MouseEvent ) => { console.log(e.currentTarget.id); if ( - data?.active_game && activeGameParams.board[row][column] === null && - activeGameParams.current_player.account_id === walletSelector.accountId && - !loadingSquare.column && - !loadingSquare.row + currentPlayer === walletSelector.accountId ) { const gameId = parseInt(data?.active_game?.[0]!); console.log("play(", gameId, row, column, ")"); setLoadingSquare({ row, column }); try { if (walletSelector.ticTacToeLogic) { - await walletSelector.ticTacToeLogic.play(gameId, row, column); + const response = await walletSelector.ticTacToeLogic.play( + gameId, + row, + column + ); + setActiveGameParams((prev) => { + return { + ...prev, + board: getTransactionLastResult(response), + }; + }); } } catch (error) { console.error(error); + } finally { setLoadingSquare({ row: null, column: null }); } } }; + const tiles = data?.active_game?.[1].tiles; useEffect(() => { - if ( - tiles && - tiles[row][column] !== activeGameParams.board[row][column] && - currentPlayer - ) { + if (tiles && tiles[row][column] !== activeGameParams.board[row][column]) { setActiveGameParams((prev) => { return { ...prev, board: tiles, - current_player: currentPlayer, }; }); + //setLoading(false); setLoadingSquare({ row: null, column: null }); } }, [ - activeGameParams, - currentPlayer, + activeGameParams.board, column, row, setActiveGameParams, @@ -91,18 +95,6 @@ export function BoardSquare({ setLoadingSquare, ]); - const isAvailableToClick = - !activeGameParams.board[row][column] && - activeGameParams.current_player.account_id === walletSelector.accountId && - !loadingSquare.column && - !loadingSquare.row; - - const isActiveTurn = - data?.active_game && - activeGameParams.current_player.account_id === walletSelector.accountId && - !loadingSquare.row && - !loadingSquare.column; - return ( {activeGameParams.board[row][column] && ( {activeGameParams.board[row][column] === "O" ? ( - + ) : ( - + )} )} diff --git a/src/components/TicTacToe/components/Info.tsx b/src/components/TicTacToe/components/Info.tsx index 52dd6e4..794b7ae 100644 --- a/src/components/TicTacToe/components/Info.tsx +++ b/src/components/TicTacToe/components/Info.tsx @@ -2,25 +2,22 @@ import { Accordion } from "@chakra-ui/react"; import { useWalletSelector } from "../../../contexts/WalletSelectorContext"; import { GameParams } from "../../../hooks/useContractParams"; import WaitingList from "./WaitingList"; -import WaitingListForm from "./WaitingListForm/WaitingListForm"; +import WaitingListForm from "./WaitingListForm"; import { useEffect, useState } from "react"; import { ActiveGame } from "./ActiveGame"; import { HowToPlay } from "./HowToPlay"; import { GameParamsState } from "../containers/TicTacToe"; import { UserStats } from "./Stats"; import { Referral } from "./Referral"; -import { WhiteListedTokens } from "../../../hooks/useWhiteListedTokens"; type Props = { data: GameParams | undefined; - tokensData: WhiteListedTokens[]; activeGameParams: GameParamsState; setActiveGameParams: React.Dispatch>; }; export default function Info({ data, - tokensData, activeGameParams, setActiveGameParams, }: Props) { @@ -52,7 +49,7 @@ export default function Info({ {walletSelector.selector.isSignedIn() && !data?.active_game && - !haveOwnChallenge && } + !haveOwnChallenge && } {walletSelector.selector.isSignedIn() && } diff --git a/src/components/TicTacToe/components/WaiitingListElement.tsx b/src/components/TicTacToe/components/WaiitingListElement.tsx index 8f22cdd..080a6bb 100644 --- a/src/components/TicTacToe/components/WaiitingListElement.tsx +++ b/src/components/TicTacToe/components/WaiitingListElement.tsx @@ -1,17 +1,15 @@ -import { Button, Flex, Grid, Text } from "@chakra-ui/react"; +import { Button, Grid, Text } from "@chakra-ui/react"; import { utils } from "near-api-js"; import { useWalletSelector } from "../../../contexts/WalletSelectorContext"; import { AvailablePlayerConfig } from "../../../near/contracts/TicTacToe"; import { PurpleButton } from "../../../shared/components/PurpleButton"; -import { formatAccountId } from "../../../shared/helpers/formatAccountId"; import TokenName from "./TokenName"; type Props = { player: [string, AvailablePlayerConfig]; - width: number; }; -export function WaiitingListElement({ player, width }: Props) { +export function WaiitingListElement({ player }: Props) { const walletSelector = useWalletSelector(); const handleAcceptButton = ( @@ -39,33 +37,19 @@ export function WaiitingListElement({ player, width }: Props) { walletSelector.ticTacToeLogic?.removeBet(); }; - const isSmallDesign = width < 480 || (width > 768 && width < 992); return ( - {isSmallDesign ? ( - - {formatAccountId(player[0], width)} - - {utils.format.formatNearAmount(player[1].deposit)}  - {} - - - ) : ( - <> - {formatAccountId(player[0], width)} - - {utils.format.formatNearAmount(player[1].deposit)}  - {} - - - )} + {player[0]} + + {utils.format.formatNearAmount(player[1].deposit)}{" "} + {} + {player[0] !== walletSelector.accountId ? ( )} - + ))} @@ -73,7 +71,7 @@ export default function WaitingList({ showingActiveGame }: Props) { Private Challenges )} - + ))} @@ -90,7 +88,7 @@ export default function WaitingList({ showingActiveGame }: Props) { Public Challenges )} - + ))} diff --git a/src/components/TicTacToe/components/WaitingListForm.tsx b/src/components/TicTacToe/components/WaitingListForm.tsx new file mode 100644 index 0000000..bf3c7b8 --- /dev/null +++ b/src/components/TicTacToe/components/WaitingListForm.tsx @@ -0,0 +1,111 @@ +import { + AccordionButton, + AccordionIcon, + AccordionItem, + AccordionPanel, + Box, + Flex, + FormControl, + FormLabel, + Input, + Select, + Text, +} from "@chakra-ui/react"; +import { useState } from "react"; +import { useWalletSelector } from "../../../contexts/WalletSelectorContext"; +import { PurpleButton } from "../../../shared/components/PurpleButton"; + +export default function WaitingListForm() { + const [bidInput, setBidInput] = useState("0"); + const [opponentInput, setOpponentInput] = useState(""); + const [withCheddar, setWithCheddar] = useState(false); + const walletSelector = useWalletSelector(); + + const params = new URLSearchParams(window.location.search); + + const referral = params.get("r") ?? undefined; + + const handleBidInputChange = (e: React.ChangeEvent) => { + setBidInput(e.target.value); + }; + + const handleOpponentInputChange = ( + e: React.ChangeEvent + ) => { + setOpponentInput(e.target.value); + }; + + const handleOnClick = () => { + walletSelector.ticTacToeLogic?.bet( + parseFloat(bidInput), + withCheddar, + referral, + opponentInput.trim() === "" ? undefined : opponentInput + ); + }; + + const handleSelectChange = (e: React.ChangeEvent) => { + if (e.target.value === "NEAR") { + setWithCheddar(false); + } else if (e.target.value === "CHEDDAR") { + setWithCheddar(true); + } + }; + + return ( + +

+ + + + Join Waiting List + + + + +

+ + + + My Bid: + + + + + + + Opponent (optional): + + + + + Join Waiting List + + +
+ ); +} diff --git a/src/components/TicTacToe/components/WaitingListForm/OpponentInput.tsx b/src/components/TicTacToe/components/WaitingListForm/OpponentInput.tsx deleted file mode 100644 index fb9dc3c..0000000 --- a/src/components/TicTacToe/components/WaitingListForm/OpponentInput.tsx +++ /dev/null @@ -1,114 +0,0 @@ -import { - Flex, - FormControl, - FormErrorMessage, - FormLabel, - Input, - Text, -} from "@chakra-ui/react"; -import { useEffect, useState } from "react"; -import { useWalletSelector } from "../../../../contexts/WalletSelectorContext"; - -type Props = { - opponentInput: { - id: string; - exist: boolean; - loading: boolean; - }; - setOpponentInput: React.Dispatch< - React.SetStateAction<{ - id: string; - exist: boolean; - loading: boolean; - }> - >; -}; - -export function OpponentInput({ opponentInput, setOpponentInput }: Props) { - const [timer, setTimer] = useState(); - const walletSelector = useWalletSelector(); - const handleOpponentInputChange = ( - e: React.ChangeEvent - ) => { - clearTimeout(timer); - setOpponentInput({ - id: e.target.value, - exist: false, - loading: true, - }); - }; - - const borderColor = - opponentInput.loading || opponentInput.id.trim() === "" - ? "inherit" - : opponentInput.exist - ? "green" - : "red"; - const focusBorderColor = - opponentInput.loading || opponentInput.id.trim() === "" - ? "#3182ce" - : opponentInput.exist - ? "green" - : "red"; - - useEffect(() => { - if (opponentInput.id.trim() !== "") { - let timerId = setTimeout(function () { - walletSelector.ticTacToeLogic - ?.getAccountBalance(opponentInput.id) - .then((resp) => { - console.log(resp); - const balanceExists = !isNaN(parseInt(resp)); - setOpponentInput((prev) => { - return { - ...prev, - loading: false, - exist: balanceExists, - }; - }); - }); - }, 300); - setTimer(timerId); - } - }, [opponentInput.id, setOpponentInput, walletSelector.ticTacToeLogic]); - - return ( - - - - Opponent: - - (optional) - - - - - - This Account Doesn't exist - - - ); -} diff --git a/src/components/TicTacToe/components/WaitingListForm/PriceInput.tsx b/src/components/TicTacToe/components/WaitingListForm/PriceInput.tsx deleted file mode 100644 index 014ea54..0000000 --- a/src/components/TicTacToe/components/WaitingListForm/PriceInput.tsx +++ /dev/null @@ -1,75 +0,0 @@ -import { - Flex, - FormControl, - FormErrorMessage, - FormLabel, - Input, -} from "@chakra-ui/react"; -import { utils } from "near-api-js"; -import { isValidAmountInput } from "./helpers"; -type Props = { - bidInput: string; - setBidInput: React.Dispatch>; - minDeposit: string; - tokenName: string; -}; -export function PriceInput({ - bidInput, - setBidInput, - minDeposit, - tokenName, -}: Props) { - const handleBidInputChange = (e: React.ChangeEvent) => { - if (isValidAmountInput(e.target.value)) { - setBidInput(e.target.value); - } - }; - const borderColor = - bidInput.trim() === "" || - parseFloat(bidInput) >= - parseFloat(utils.format.formatNearAmount(minDeposit)) - ? "inherit" - : "red"; - - return ( - - - - My Bid: - - - - - Minimun Deposit: {utils.format.formatNearAmount(minDeposit)} {tokenName} - - - ); -} diff --git a/src/components/TicTacToe/components/WaitingListForm/WaitingListForm.tsx b/src/components/TicTacToe/components/WaitingListForm/WaitingListForm.tsx deleted file mode 100644 index bb79651..0000000 --- a/src/components/TicTacToe/components/WaitingListForm/WaitingListForm.tsx +++ /dev/null @@ -1,136 +0,0 @@ -import { - AccordionButton, - AccordionIcon, - AccordionItem, - AccordionPanel, - Box, - Flex, - FormControl, - FormLabel, - Select, - Text, -} from "@chakra-ui/react"; -import { utils } from "near-api-js"; -import { useState } from "react"; -import { useWalletSelector } from "../../../../contexts/WalletSelectorContext"; -import { WhiteListedTokens } from "../../../../hooks/useWhiteListedTokens"; -import { PurpleButton } from "../../../../shared/components/PurpleButton"; -import { OpponentInput } from "./OpponentInput"; -import { PriceInput } from "./PriceInput"; - -type Props = { - tokensData: WhiteListedTokens[]; -}; - -export default function WaitingListForm({ tokensData }: Props) { - const [bidInput, setBidInput] = useState(""); - const [opponentInput, setOpponentInput] = useState({ - id: "", - exist: false, - loading: false, - }); - const [tokenName, setTokenName] = useState(tokensData[0].name); - const [minDeposit, setMinDeposit] = useState(tokensData[0].minDeposit); - const [withCheddar, setWithCheddar] = useState(false); - const walletSelector = useWalletSelector(); - - const params = new URLSearchParams(window.location.search); - - const referral = params.get("r") ?? undefined; - - const handleOnClick = () => { - walletSelector.ticTacToeLogic?.bet( - parseFloat(bidInput), - withCheddar, - referral, - opponentInput.id.trim() === "" ? undefined : opponentInput.id - ); - }; - - const handleSelectChange = (e: React.ChangeEvent) => { - setTokenName(e.target.value); - setMinDeposit( - tokensData.find((item) => item.name === e.target.value)?.minDeposit || "1" - ); - if (e.target.value === "CHEDDAR") { - setWithCheddar(true); - } else { - setWithCheddar(false); - } - }; - - return ( - -

- - - - Join Waiting List - - - - -

- - - - - FT Type: - - - - - { - - } - - - - Join Waiting List - - - -
- ); -} diff --git a/src/components/TicTacToe/components/WaitingListForm/helpers.ts b/src/components/TicTacToe/components/WaitingListForm/helpers.ts deleted file mode 100644 index 06fd5ad..0000000 --- a/src/components/TicTacToe/components/WaitingListForm/helpers.ts +++ /dev/null @@ -1,6 +0,0 @@ -export const isValidAmountInput = (input: string) => { - const regex = /\d{1,10}\.\d{1,4}|\d{1,10}\.?|\.?\d{0,4}/; - const resp = regex.exec(input); - - return resp && resp[0] === resp.input; -}; diff --git a/src/components/TicTacToe/containers/TicTacToe.tsx b/src/components/TicTacToe/containers/TicTacToe.tsx index 0506a10..18a0ae2 100644 --- a/src/components/TicTacToe/containers/TicTacToe.tsx +++ b/src/components/TicTacToe/containers/TicTacToe.tsx @@ -3,7 +3,6 @@ import { useEffect, useState } from "react"; import { useWalletSelector } from "../../../contexts/WalletSelectorContext"; import { useContractParams } from "../../../hooks/useContractParams"; import useScreenSize from "../../../hooks/useScreenSize"; -import { useWhiteListedTokens } from "../../../hooks/useWhiteListedTokens"; import Board from "../components/Board"; import Info from "../components/Info"; @@ -20,7 +19,7 @@ export type GameParamsState = { board: ("O" | "X" | null)[][]; }; -export const initialActiveGameParamsState = { +export const initialActiveGameParamsState2 = { game_id: null, game_result: { result: null, winner_id: null }, player1: null, @@ -39,30 +38,41 @@ export const initialActiveGameParamsState = { export function TicTacToe() { const [activeGameParams, setActiveGameParams] = useState( - initialActiveGameParamsState + initialActiveGameParamsState2 ); const walletSelector = useWalletSelector(); - const { data } = useContractParams(); - const { data: tokensData } = useWhiteListedTokens(); const { height, width } = useScreenSize(); const isLandscape = width > height * 1.5; console.log(data); + console.log(data?.active_game); + console.log(activeGameParams); useEffect(() => { if (data?.active_game && !activeGameParams.game_id) { setActiveGameParams({ - ...initialActiveGameParamsState, + ...initialActiveGameParamsState2, game_id: data.active_game[0], current_player: data.active_game[1].current_player, board: data.active_game[1].tiles, - player1: data.active_game[1].player1, - player2: data.active_game[1].player2, }); } + console.log("first"); }, [activeGameParams.game_id, data?.active_game, walletSelector.accountId]); + useEffect(() => { + const currentPlayer = data?.active_game?.[1].current_player; + if (currentPlayer) { + setActiveGameParams((prev) => { + return { + ...prev, + current_player: currentPlayer, + }; + }); + } + }, [data?.active_game]); + return ( - {data && tokensData && ( - <> - - - - )} + + ); } diff --git a/src/components/lib/theme.ts b/src/components/lib/theme.ts index e275417..9d9544c 100644 --- a/src/components/lib/theme.ts +++ b/src/components/lib/theme.ts @@ -29,8 +29,8 @@ const components = { }; const fonts = { - heading: `'Titillium Web', sans-serif`, - body: `'Titillium Web', sans-serif`, + heading: `'Bubblegum Sans', cursive`, + body: `'Bubblegum Sans', cursive`, }; const colors = { diff --git a/src/contexts/WalletSelectorContext.tsx b/src/contexts/WalletSelectorContext.tsx index f6295d9..653eefb 100644 --- a/src/contexts/WalletSelectorContext.tsx +++ b/src/contexts/WalletSelectorContext.tsx @@ -10,6 +10,7 @@ import { setupModal } from "@near-wallet-selector/modal-ui"; import type { WalletSelectorModal } from "@near-wallet-selector/modal-ui"; import { setupNearWallet } from "@near-wallet-selector/near-wallet"; import { setupSender } from "@near-wallet-selector/sender"; +import { contractName, nearConfig } from "../near"; import { setupNearWalletCustom } from "../near/wallet/selector-utils"; import "./WalletSelectorContext.css"; import { NEP141 } from "../near/contracts/NEP141"; @@ -59,7 +60,7 @@ export const WalletSelectorContextProvider = ({ children }: Props) => { const init = useCallback(async () => { const _selector = await setupWalletSelector({ - network: getEnv(ENV).nearEnv.networkId as NetworkId, + network: nearConfig.networkId as NetworkId, debug: true, modules: [ setupNearWallet({ iconUrl: nearIcon }), @@ -67,9 +68,7 @@ export const WalletSelectorContextProvider = ({ children }: Props) => { setupNearWalletCustom(), ], }); - const _modal = setupModal(_selector, { - contractId: getEnv(ENV).contractId, - }); + const _modal = setupModal(_selector, { contractId: contractName }); const state = _selector.store.getState(); setAccounts(state.accounts); diff --git a/src/hooks/useWhiteListedTokens.ts b/src/hooks/useWhiteListedTokens.ts deleted file mode 100644 index 8c309bf..0000000 --- a/src/hooks/useWhiteListedTokens.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { useQuery } from "react-query"; -import { - useWalletSelector, - WalletSelectorContextValue, -} from "../contexts/WalletSelectorContext"; -import { NEP141 } from "../near/contracts/NEP141"; -import { SelectorWallet } from "../near/wallet/wallet-selector"; - -export interface WhiteListedTokens { - name: string; - contractId: string; - value: string; - minDeposit: string; -} - -const getWhiteListedTokens = async ( - walletSelector: WalletSelectorContextValue -) => { - const whiteListedTokens: WhiteListedTokens[] = [ - { - name: "NEAR", - contractId: "", - value: "1000000000000000000000000", - minDeposit: "10000000000000000000000", - }, - ]; - const resp = await walletSelector.ticTacToeLogic?.getWhiteListedTokens(); - if (!resp) { - return whiteListedTokens; - } - const selectorWallet = new SelectorWallet(walletSelector.selector); - for (const item of resp) { - const minDeposit = await walletSelector.ticTacToeLogic?.getTokenMinDeposit( - item[0] - ); - const metadata = await new NEP141(selectorWallet, item[0]).ft_metadata(); - whiteListedTokens.push({ - name: metadata.name.toUpperCase(), - contractId: item[0], - value: item[1], - minDeposit: minDeposit || "1", - }); - } - - return whiteListedTokens; -}; - -export const useWhiteListedTokens = () => { - const walletSelector = useWalletSelector(); - return useQuery( - ["WhiteListedTokens"], - () => getWhiteListedTokens(walletSelector), - { - refetchInterval: Infinity, - cacheTime: 0, - notifyOnChangePropsExclusions: ["isStale", "isRefetching", "isFetching"], - } - ); -}; diff --git a/src/near/contracts/TicTacToe.ts b/src/near/contracts/TicTacToe.ts index 4bf46f6..e4b9557 100644 --- a/src/near/contracts/TicTacToe.ts +++ b/src/near/contracts/TicTacToe.ts @@ -114,8 +114,16 @@ export class TicTacToeContract { }; } - getDisplayableAccountId(screenWidth: number): string { - return this.wallet.getDisplayableAccountId(screenWidth); + getDisplayableAccountId( + startLength?: number, + endLength?: number, + maxLength?: number + ): string { + return this.wallet.getDisplayableAccountId( + startLength, + endLength, + maxLength + ); } /** @@ -128,10 +136,6 @@ export class TicTacToeContract { return this.wallet.view(this.contractId, "get_active_games", {}); } - get_account_balance(accountId: string): Promise { - return this.wallet.getAccountBalance(accountId); - } - get_last_games(): Promise<[number, FinalizedGame][]> { return this.wallet.view(this.contractId, "get_last_games", {}); } @@ -144,16 +148,6 @@ export class TicTacToeContract { return this.wallet.view(this.contractId, "get_contract_params", {}); } - get_token_min_deposit(accountId: string): Promise { - return this.wallet.view(this.contractId, "get_token_min_deposit", { - token_id: accountId, - }); - } - - get_whitelisted_tokens(): Promise<[string, string][]> { - return this.wallet.view(this.contractId, "get_whitelisted_tokens", {}); - } - make_move( game_id: number, row: number, diff --git a/src/near/index.ts b/src/near/index.ts new file mode 100644 index 0000000..aa032e6 --- /dev/null +++ b/src/near/index.ts @@ -0,0 +1,54 @@ +import * as naj from "near-api-js"; + +import { Buffer } from "buffer"; +if (typeof window !== "undefined") window.Buffer = Buffer; +if (typeof global !== "undefined") global.Buffer = Buffer; + +export const contractName = "tictactoe.cheddar.testnet"; + +export const nearConfig = /near$/.test(contractName) + ? { + networkId: "mainnet", + nodeUrl: "https://rpc.mainnet.near.org", + walletUrl: "https://wallet.near.org", + helperUrl: "https://helper.mainnet.near.org", + headers: {}, + } + : // /testnet$/.test(contractName)? + { + networkId: "testnet", + nodeUrl: "https://rpc.testnet.near.org", + walletUrl: "https://wallet.testnet.near.org", + helperUrl: "https://helper.testnet.near.org", + headers: {}, + }; +//: undefined; + +/* +if (!nearConfig) { + throw new Error( + `Don't know what network settings to use for contract "${contractName}"; expected name to end in 'testnet' or 'near'` + ); +} +*/ +/** + * NEAR Config object + */ +export const near = new naj.Near({ + ...nearConfig, + keyStore: + typeof window === "undefined" + ? new naj.keyStores.InMemoryKeyStore() + : new naj.keyStores.BrowserLocalStorageKeyStore(), +}); + +/** + * Interface to NEAR Wallet + export const wallet = new naj.WalletConnection(near); + */ + +/* +export function signIn() { + wallet.requestSignIn({ contractId: contractName }); +} +*/ diff --git a/src/near/logics/TicTacToeLogic.ts b/src/near/logics/TicTacToeLogic.ts index 3eb4e0d..125b95f 100644 --- a/src/near/logics/TicTacToeLogic.ts +++ b/src/near/logics/TicTacToeLogic.ts @@ -31,24 +31,20 @@ export class TicTacToeLogic { return this.ticTacToeContract.get_available_players(); } - getAccountBalance(accountId: string): Promise { - return this.ticTacToeContract.get_account_balance(accountId); - } - getContractParams(): Promise { return this.ticTacToeContract.get_contract_params(); } - getTokenMinDeposit(accountId: string): Promise { - return this.ticTacToeContract.get_token_min_deposit(accountId); - } - - getWhiteListedTokens(): Promise<[string, string][]> { - return this.ticTacToeContract.get_whitelisted_tokens(); - } - - getDisplayableAccountId(screenWidth: number): string { - return this.ticTacToeContract.getDisplayableAccountId(screenWidth); + getDisplayableAccountId( + startLength?: number, + endLength?: number, + maxLength?: number + ): string { + return this.ticTacToeContract.getDisplayableAccountId( + startLength, + endLength, + maxLength + ); } getLastGames(): Promise<[number, FinalizedGame][]> { diff --git a/src/near/wallet/selector-utils.ts b/src/near/wallet/selector-utils.ts index b00de6e..d0920d3 100644 --- a/src/near/wallet/selector-utils.ts +++ b/src/near/wallet/selector-utils.ts @@ -5,12 +5,12 @@ import { } from "@near-wallet-selector/core"; import { setupMyNearWallet } from "@near-wallet-selector/my-near-wallet"; import { setupSender } from "@near-wallet-selector/sender"; -import { ENV, getEnv } from "../config"; +import { nearConfig } from "../index"; export const setupNearWalletCustom = () => { return async (options: any) => { const wallet = await setupMyNearWallet({ - walletUrl: getEnv(ENV).nearEnv.walletUrl, // get walletUrl from config + walletUrl: nearConfig.walletUrl, // get walletUrl from config iconUrl: "./assets/near-wallet-iconx.png", })(options); @@ -35,7 +35,7 @@ export const setupNearWalletCustom = () => { export async function setupSelector(): Promise { return setupWalletSelector({ - network: (getEnv(ENV).nearEnv.networkId as NetworkId) || "testnet", + network: (nearConfig.networkId as NetworkId) || "testnet", modules: [setupNearWalletCustom(), setupSender(), setupMyNearWallet()], }); } diff --git a/src/near/wallet/wallet-interface.ts b/src/near/wallet/wallet-interface.ts index ff76822..4f1a6ff 100644 --- a/src/near/wallet/wallet-interface.ts +++ b/src/near/wallet/wallet-interface.ts @@ -9,9 +9,9 @@ export type EventHandler = (this: Document, ev: any) => any; //----------------------- export interface WalletInterface { getAccountId(): string; - getDisplayableAccountId(screenWidth: number): string; + getDisplayableAccountId(): string; - getAccountBalance(accountId?: string): Promise; + //getAccountBalance(accountId?:string):Promise; getNetwork(): string; setNetwork(value: string): void; diff --git a/src/near/wallet/wallet-selector.ts b/src/near/wallet/wallet-selector.ts index adf9230..17886bd 100644 --- a/src/near/wallet/wallet-selector.ts +++ b/src/near/wallet/wallet-selector.ts @@ -5,7 +5,7 @@ import { } from "@near-wallet-selector/core"; import { BrowserWalletSignAndSendTransactionParams } from "@near-wallet-selector/core/lib/wallet"; import { JsonRpcProvider } from "near-api-js/lib/providers"; -import { ENV, getEnv } from "../config"; +import { nearConfig } from "../../near"; //import { TGas } from "../../util/conversions"; //import { BatchTransaction } from "../batch-transaction"; //import { U128String } from "../util"; @@ -28,31 +28,17 @@ export class SelectorWallet implements WalletInterface { ?.accountId!; } - getDisplayableAccountId(screenWidth: number): string { - const { startLength, endLength, maxLength } = - this.getAccountLengths(screenWidth); + getDisplayableAccountId( + startLength = 10, + endLength = 10, + maxLength = 22 + ): string { const accountId = this.getAccountId(); return accountId.length > maxLength - ? accountId.slice(0, startLength) + - ".." + - (endLength === 0 ? "" : accountId.slice(0 - endLength)) + ? accountId.slice(0, startLength) + ".." + accountId.slice(0 - endLength) : accountId; } - private getAccountLengths(screenWidth: number): { - startLength: number; - endLength: number; - maxLength: number; - } { - if (screenWidth < 480) { - return { startLength: 7, endLength: 0, maxLength: 8 }; - } else if (screenWidth < 768) { - return { startLength: 8, endLength: 8, maxLength: 18 }; - } else { - return { startLength: 10, endLength: 10, maxLength: 22 }; - } - } - async getAccountBalance(accountId?: string | undefined): Promise { if (!accountId) { accountId = this.walletState.accounts.find( @@ -71,7 +57,7 @@ export class SelectorWallet implements WalletInterface { } }`; - const result = await fetch(getEnv(ENV).nearEnv.nodeUrl, { + const result = await fetch(nearConfig.nodeUrl, { method: "POST", body, headers: { @@ -79,7 +65,7 @@ export class SelectorWallet implements WalletInterface { }, }); const resultJson = await result.json(); - return resultJson.result ? resultJson.result.amount : resultJson.error.data; + return resultJson.result.amount; //---------as U128String; } setNetwork(value: string): void { @@ -113,7 +99,7 @@ export class SelectorWallet implements WalletInterface { try { const argsAsString = JSON.stringify(args); let argsBase64 = Buffer.from(argsAsString).toString("base64"); - const provider = new JsonRpcProvider(getEnv(ENV).nearEnv.nodeUrl); + const provider = new JsonRpcProvider(nearConfig.nodeUrl); const rawResult = await provider.query({ request_type: "call_function", account_id: contract, @@ -174,7 +160,7 @@ export class SelectorWallet implements WalletInterface { } */ async queryChain(method: string, args: object): Promise { - const provider = new JsonRpcProvider(getEnv(ENV).nearEnv.nodeUrl); + const provider = new JsonRpcProvider(nearConfig.nodeUrl); return provider.sendJsonRpc(method, args); } } diff --git a/src/shared/components/PurpleButton.tsx b/src/shared/components/PurpleButton.tsx index a06266c..2a17062 100644 --- a/src/shared/components/PurpleButton.tsx +++ b/src/shared/components/PurpleButton.tsx @@ -11,7 +11,6 @@ export function PurpleButton(props: Props) { bg="purpleCheddar" size={props.size} onClick={props.onClick} - {...props} > {props.children} diff --git a/src/shared/helpers/formatAccountId.ts b/src/shared/helpers/formatAccountId.ts deleted file mode 100644 index 5b0fbc2..0000000 --- a/src/shared/helpers/formatAccountId.ts +++ /dev/null @@ -1,23 +0,0 @@ -export function formatAccountId( - accountId: string, - screenWidth: number -): string { - const { startLength, endLength, maxLength } = getAccountLengths(screenWidth); - return accountId.length > maxLength - ? accountId.slice(0, startLength) + - ".." + - (endLength === 0 ? "" : accountId.slice(0 - endLength)) - : accountId; -} - -function getAccountLengths(screenWidth: number): { - startLength: number; - endLength: number; - maxLength: number; -} { - if (screenWidth < 1200) { - return { startLength: 7, endLength: 7, maxLength: 6 }; - } else { - return { startLength: 9, endLength: 9, maxLength: 20 }; - } -} diff --git a/yarn.lock b/yarn.lock index 1acd6a9..77882bd 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1808,11 +1808,6 @@ minimatch "^3.0.4" strip-json-comments "^3.1.1" -"@fontsource/titillium-web@^4.5.9": - version "4.5.9" - resolved "https://registry.yarnpkg.com/@fontsource/titillium-web/-/titillium-web-4.5.9.tgz#9de41e7b27fd6913055c2e9f616e5a2c5180f121" - integrity sha512-C9bkYCeelkLcom4dHcT3/sM6CmlPwisyRbHUNGAt5LtF3XBdxqOW/R3cB6IaHWjqQvLYb93bTQpJu8X+KfggGA== - "@gar/promisify@^1.0.1": version "1.1.3" resolved "https://registry.yarnpkg.com/@gar/promisify/-/promisify-1.1.3.tgz#555193ab2e3bb3b6adc3d551c9c030d9e860daf6"