Compare commits

...

11 Commits

Author SHA1 Message Date
vincanger
0346b0353e add RPC Provider & Mumbai Deploy config
end state of Chapter 3. > Deployment & Final Words > Deploy to Polygon
2022-07-28 11:28:37 +02:00
vincanger
e6cae4ff4a add useEvents
end state of Chapter 3. > Writing & Events > Responding to Events
2022-07-28 11:28:37 +02:00
vincanger
24dfc75f59 add mutations & token contract
end state of Chapter 3. > Writing & Events > Submitting Answers & Upvotes
2022-07-28 11:28:37 +02:00
vincanger
98c365cf35 add Read & Render components
end state of Chapter 3. > Interacting with our Deployed Contract > Reading and Rendering
2022-07-28 11:28:37 +02:00
vincanger
93851c86bb add wagmi config & useForumContract
end state of Chapter 3. > Connecting to the Blockchain
2022-07-28 11:28:37 +02:00
vincanger
693aec4410 add useForumContract
Chapter 2. > Deploying to a Local Node > Calling our Smart Contract
2022-07-28 11:28:37 +02:00
vincanger
e04d5c6c0d add comments to Forum test
End state of Chapter 2 > Testing
2022-07-28 11:28:37 +02:00
vincanger
695096fecc update OurToken test comments 2022-07-28 11:28:37 +02:00
vincanger
dc51e3f96c add forum test types and lib 2022-07-28 11:28:37 +02:00
vincanger
2e8e8ad61d add forum test 2022-07-28 11:28:37 +02:00
vincanger
b58d9d751b add hardhat, token contract, and test
Chapter 2. > Designing the Forum Backend

add hardhat, token contract, and test

Chapter 2 > Our ERC20 Token > Testing
2022-07-28 11:28:37 +02:00
42 changed files with 20632 additions and 57 deletions

11
Front-end/.gitignore vendored
View File

@ -7,6 +7,7 @@
# testing
/coverage
comp.tsx
# next.js
/.next/
@ -33,3 +34,13 @@ yarn-error.log*
# typescript
*.tsbuildinfo
node_modules
.env
coverage
coverage.json
typechain
#Hardhat files
cache
artifacts

View File

@ -0,0 +1,40 @@
import * as React from 'react';
import { Text, Badge, HStack, Stack, Flex, Spacer } from '@chakra-ui/react';
import TimeAgo from 'react-timeago';
import Avatar from '@davatar/react/dist/Image';
import { Answer as AnswerStruct } from '../hooks/contracts/useForumContract';
import Username from './Username';
import Upvote from './Upvote';
import { useProvider } from 'wagmi';
interface AnswerProps {
answer: AnswerStruct;
first?: boolean;
}
const Answer: React.FunctionComponent<AnswerProps> = ({ answer, first }) => {
const provider = useProvider();
return (
<HStack spacing={3} alignItems='start'>
<Avatar size={48} provider={provider} address={answer.creatorAddress} />
<Stack spacing={1} flex={1} bg={first ? 'purple.900' : 'whiteAlpha.300'} rounded='md' p={3}>
<Text color='white' fontSize='lg'>
{answer.message}
</Text>
<Flex alignItems='center' w='100%'>
<Badge borderRadius='full' px='5' color='purple.400' colorScheme='purple'>
<Username address={answer.creatorAddress} />
</Badge>
<Text px='8px' fontSize='sm' color='gray.500'>
<TimeAgo date={answer.timestamp.toNumber() * 1000} />
</Text>
<Spacer />
<Upvote answerId={answer.answerId} alignSelf='flex-end' size='sm'></Upvote>
</Flex>
</Stack>
</HStack>
);
};
export default Answer;

View File

@ -0,0 +1,107 @@
import * as React from 'react';
import { HStack, Stack, Flex, Textarea, Image, Text, Spacer, Button } from '@chakra-ui/react';
import type { BigNumber } from 'ethers';
import { useAccount } from 'wagmi';
import useAddAnswer from '../hooks/useAddAnswer';
import AuthButton from './AuthButton';
import toast from 'react-hot-toast';
import useBalance from '../hooks/useBalance';
import useAddMint from '../hooks/useAddMint';
interface AnswerEditorProps {
questionid: BigNumber;
}
const AnswerEditor: React.FunctionComponent<AnswerEditorProps> = ({ questionid }) => {
const [message, setMessage] = React.useState('');
const { address: account } = useAccount();
const { contractBalanceQuery, userBalanceQuery } = useBalance();
const addAnswer = useAddAnswer();
const addMint = useAddMint();
const isDataFetched = contractBalanceQuery.isFetched && userBalanceQuery.isFetched && account;
const isUserTippable = async () => {
if (isDataFetched) {
const balance = Number(userBalanceQuery.data);
return balance >= 10;
}
};
const handleFocus = async () => {
if (!account) {
toast.error('Please sign in to submit an answer');
return;
}
const tippable = await isUserTippable();
if (!tippable) {
toast.error(`Keep your Goflow balance above 10 tokens to receive tips 🧧`);
} else {
toast.success('Your balance is sufficient to receive tips 💸');
}
};
const handleMint = async () => {
try {
await addMint.mutateAsync({ amount: '10' });
toast.success(`Minted 10 tokens for you :) Import the GOFLOW token address to your wallet`);
} catch (e: any) {
toast.error(e.message);
console.log(e);
}
};
const handleClick = async () => {
try {
await addAnswer.mutateAsync({ questionId: questionid, message });
setMessage('');
} catch (e: any) {
toast.error(e.data?.message || e.message);
}
};
return (
<Stack spacing={3}>
<HStack spacing={3} alignItems='start'>
<Image borderRadius='full' boxSize='50px' fit='contain' src='../polygon-logo.png' alt='Polygon Logo' />
<Textarea
value={message}
onFocus={handleFocus}
onChange={(e) => setMessage(e.target.value)}
placeholder='Submit an Answer..'
p={3}
flex={1}
bg='whiteAlpha.400'
rounded='md'
fontSize='lg'
/>
</HStack>
<Flex alignItems='center'>
<Spacer />
<Button size='sm' mx='5px' onClick={handleMint} isLoading={addMint.isLoading} alignSelf='flex-end'>
💰 Goflow Faucet
</Button>
<AuthButton
text='Submit'
size='sm'
colorScheme='purple'
alignSelf='flex-end'
onClick={handleClick}
isLoading={addAnswer.isLoading}
/>
</Flex>
{isDataFetched && (
<Flex direction='column' alignItems='flex-end'>
<Text fontSize='sm' mx='5px'>
Contract Balance: {contractBalanceQuery.data}{' '}
</Text>
<Text fontSize='sm' mx='5px'>
User Balance: {userBalanceQuery.data}{' '}
</Text>
</Flex>
)}
</Stack>
);
};
export default AnswerEditor;

View File

@ -0,0 +1,44 @@
import * as React from 'react';
import { Box, Center, Spinner, Stack } from '@chakra-ui/react';
import useAnswers from '../hooks/useAnswers';
import Answer from './Answer';
import type { BigNumber } from 'ethers';
import type { Answer as AnswerStruct } from '../hooks/contracts/useForumContract';
import AnswerEditor from './AnswerEditor';
import useEvents from '../hooks/useEvents';
interface AnswersProps {
questionId: BigNumber;
}
const Answers: React.FunctionComponent<AnswersProps> = ({ questionId }) => {
const [sortedAnswers, setSortedAnswers] = React.useState<AnswerStruct[]>([]);
const answersQuery = useAnswers({ questionId });
useEvents({ questionId });
React.useEffect(() => {
if (answersQuery.data) {
const sortAnswers = answersQuery.data.sort((a, b) => (a.upvotes > b.upvotes ? -1 : 1));
setSortedAnswers(sortAnswers);
}
}, [answersQuery.data, answersQuery.isFetched]);
return (
<Box>
{answersQuery.isLoading && (
<Center p={8}>
<Spinner />
</Center>
)}
<Stack spacing={2}>
{sortedAnswers?.map((answer, i) => (
<Answer key={answer.answerId.toNumber()} answer={answer} first={i === 0 && answer.upvotes.toNumber() != 0} />
))}
{answersQuery.isFetched && <AnswerEditor questionid={questionId} />}
</Stack>
</Box>
);
};
export default Answers;

View File

@ -0,0 +1,52 @@
import * as React from 'react';
import toast from 'react-hot-toast';
import { Button, ButtonProps } from '@chakra-ui/react';
import { useAccount, useConnect, useNetwork, chain as chains } from 'wagmi';
import { InjectedConnector } from 'wagmi/connectors/injected';
interface AuthButtonProps extends ButtonProps {
text: string;
}
const AuthButton: React.FunctionComponent<AuthButtonProps> = ({ text, ...props }) => {
const [btnText, setBtnText] = React.useState('Sign In');
// Pass new InjectedConnector to useConnect so we only connect
// with MetaMask rather than an array of wallet connectors
const { connect, error } = useConnect({ connector: new InjectedConnector() });
const { isConnected } = useAccount();
const { chain } = useNetwork();
React.useEffect(() => {
if (error?.name === 'ConnectorNotFoundError') {
toast.error('MetaMask extension required to sign in');
}
if (isConnected && chain?.id !== chains.polygonMumbai.id) {
toast.error('please connect to the Polygon Mumbai test network', {id: 'network-error'});
}
}, [error, chain, isConnected]);
React.useEffect(() => {
if (isConnected) {
setBtnText(text);
} else {
setBtnText('Sign In');
}
}, [isConnected]);
if (isConnected) {
return <Button {...props}>{btnText}</Button>;
} else {
return (
<Button
{...props}
onClick={() => {
!isConnected && connect();
}}
>
{btnText}
</Button>
);
}
};
export default AuthButton;

View File

@ -1,30 +1,30 @@
import * as React from 'react'
import NextLink from 'next/link'
import { Icon } from '@chakra-ui/react'
import { Tabs, TabList, Tab } from '@chakra-ui/react'
import { FaBalanceScale, FaCommentAlt } from "react-icons/fa";
import { useRouter } from "next/router";
import * as React from 'react';
import NextLink from 'next/link';
import { Icon } from '@chakra-ui/react';
import { Tabs, TabList, Tab } from '@chakra-ui/react';
import { FaBalanceScale, FaCommentAlt } from 'react-icons/fa';
import { useRouter } from 'next/router';
const Navbar: React.FunctionComponent = () => {
const { route } = useRouter();
const { route } = useRouter();
return (
<nav>
<Tabs
pt={1}
size="lg"
index={route !== '/amm' ? 0 : 1}
align='center'
colorScheme='gray'
>
<TabList>
<NextLink href='/' passHref><Tab><Icon as={FaCommentAlt} /></Tab></NextLink>
<NextLink href='/amm' passHref><Tab><Icon as={FaBalanceScale} /></Tab></NextLink>
</TabList>
</Tabs>
</nav>
)
}
<Tabs pt={1} size='lg' index={route !== '/amm' ? 0 : 1} align='center' colorScheme='gray'>
<TabList>
<NextLink href='/' passHref>
<Tab>
<Icon as={FaCommentAlt} />
</Tab>
</NextLink>
<NextLink href='/amm' passHref>
<Tab>
<Icon as={FaBalanceScale} />
</Tab>
</NextLink>
</TabList>
</Tabs>
</nav>
);
};
export default Navbar
export default Navbar;

View File

@ -0,0 +1,80 @@
import * as React from 'react';
import NextLink from 'next/link';
import { Box, Heading, HStack, Flex, Badge, Spacer, Text, LinkBox, LinkOverlay } from '@chakra-ui/react';
import TimeAgo from 'react-timeago';
import Username from './Username';
import Avatar from '@davatar/react/dist/Image';
import { useProvider } from 'wagmi';
import { Question as QuestionStruct } from '../hooks/contracts/useForumContract';
import useAnswers from '../hooks/useAnswers';
interface QuestionProps extends QuestionStruct {
answerPage?: boolean;
}
const Question: React.FunctionComponent<QuestionProps> = ({
questionId,
message,
creatorAddress,
timestamp,
answerPage,
}) => {
const provider = useProvider();
const answersQuery = useAnswers({ questionId });
return (
<>
{!answerPage ? (
<HStack spacing={3} alignItems='center'>
<Avatar size={48} provider={provider} address={creatorAddress} />
<LinkBox as='article' flex={1} borderWidth='1px' rounded='md' p={3}>
<Box>
<TimeAgo date={Number(timestamp) * 1000} />
</Box>
<Heading size='md' my='2'>
<NextLink href='/question/[id]' as={`/question/${questionId}`} passHref>
<LinkOverlay>{message}</LinkOverlay>
</NextLink>
</Heading>
<Flex alignItems='center' w='100%'>
<Badge borderRadius='full' px='5' color='purple.400' colorScheme='purple'>
<Username address={creatorAddress} />
</Badge>
<Spacer />
{answersQuery.isFetched && (
<Badge px='5' borderRadius='full' colorScheme='gray'>
<Text color='gray.500'>{answersQuery.data?.length} answers</Text>
</Badge>
)}
</Flex>
</LinkBox>
</HStack>
) : (
<HStack spacing={3} alignItems='center'>
<Avatar size={48} provider={provider} address={creatorAddress} />
<LinkBox as='article' flex={1} borderWidth='1px' rounded='md' p={3}>
<NextLink href='/' passHref>
<LinkOverlay>
<Text color='white' fontSize='lg'>
{message}
</Text>
</LinkOverlay>
</NextLink>
<Flex alignItems='center' w='100%'>
<Badge borderRadius='full' px='5' color='purple.400' colorScheme='purple'>
<Username address={creatorAddress} />
</Badge>
<Text px='8px' fontSize='sm'>
<TimeAgo date={Number(timestamp) * 1000} />
</Text>
<Spacer />
</Flex>
</LinkBox>
</HStack>
)}
</>
);
};
export default Question;

View File

@ -0,0 +1,45 @@
import * as React from 'react';
import { HStack, Stack, Flex, Textarea, Image, Spacer } from '@chakra-ui/react';
import useAddQuestion from '../hooks/useAddQuestion';
import AuthButton from './AuthButton';
const QuestionEditor: React.FunctionComponent = () => {
const [message, setMessage] = React.useState('');
const addQuestion = useAddQuestion();
const handleSubmit = async () => {
await addQuestion.mutateAsync({ message });
setMessage('');
}
return (
<Stack spacing={3}>
<HStack spacing={3} alignItems='start'>
<Image borderRadius='full' boxSize='50px' fit='contain' src='polygon-logo.png' alt='Polygon Logo' />
<Textarea
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder='Submit question.'
p={3}
flex={1}
bg='whiteAlpha.400'
rounded='md'
fontSize='lg'
/>
</HStack>
<Flex alignItems='center'>
<Spacer />
<AuthButton
text='Submit'
size='sm'
colorScheme='purple'
alignSelf='flex-end'
onClick={handleSubmit}
isLoading={addQuestion.isLoading}
/>
</Flex>
</Stack>
);
};
export default QuestionEditor;

View File

@ -0,0 +1,31 @@
import * as React from 'react';
import { Box, Center, Spinner, Stack } from '@chakra-ui/react';
import useQuestions from '../hooks/useQuestions';
import Question from './Question';
import QuestionEditor from './QuestionEditor';
import useEvents from '../hooks/useEvents';
const Questions: React.FunctionComponent = () => {
const { allQuestionsQuery } = useQuestions({});
// call it with an empty object to get all the questions
useEvents({});
return (
<Box>
{allQuestionsQuery.isLoading && (
<Center p={8}>
<Spinner />
</Center>
)}
<Stack spacing={4}>
{allQuestionsQuery.data?.map((q) => (
<Question {...q} key={q.questionId.toNumber()} />
))}
{allQuestionsQuery.isFetched && <QuestionEditor />}
</Stack>
</Box>
);
};
export default Questions;

View File

@ -0,0 +1,62 @@
import * as React from 'react';
import { useEffect } from 'react';
import { Icon } from '@chakra-ui/react';
import { FaArrowUp } from 'react-icons/fa';
import { Button, ButtonProps, Text } from '@chakra-ui/react';
import { useAccount } from 'wagmi';
import type { BigNumber } from 'ethers';
import useUpvotes from '../hooks/useUpvotes';
import toast from 'react-hot-toast';
import useForumContract from '../hooks/contracts/useForumContract';
import useAddApprove from '../hooks/useAddApprove';
import useAddUpvote from '../hooks/useAddUpvote';
interface UpvoteButtonProps extends ButtonProps {
answerId: BigNumber;
}
const Upvote: React.FunctionComponent<UpvoteButtonProps> = ({ answerId, ...props }) => {
const [upvoteCount, setUpvoteCount] = React.useState(0);
const { address: account } = useAccount();
const forumContract = useForumContract();
const upvotesQuery = useUpvotes({ answerId });
const addApprove = useAddApprove();
const addUpvote = useAddUpvote();
const isLoading = addApprove.isLoading || addUpvote.isLoading;
const upvoteCountText = upvoteCount === 1 ? '1 Upvote' : `${upvoteCount} Upvotes`;
useEffect(() => {
const fetchUpvoteCount = async () => {
if (upvotesQuery.isFetched && !!upvotesQuery.data) {
setUpvoteCount(upvotesQuery.data?.toNumber());
}
};
fetchUpvoteCount();
}, [answerId, upvotesQuery.data, upvotesQuery.isFetched]);
const handleClick = async () => {
try {
await addApprove.mutateAsync({ address: forumContract.contract.address, amount: '1' });
await addUpvote.mutateAsync({ answerId });
toast.success('Upvoted!');
} catch (e: any) {
toast.error(e.data?.message || e.message);
}
};
return (
<>
<Text fontSize='sm' color='gray.500' mx={3}>
{upvoteCountText}
</Text>
<Button {...props} isLoading={isLoading} disabled={!account} onClick={handleClick}>
<Icon as={FaArrowUp} />
</Button>
</>
);
};
export default Upvote;

View File

@ -0,0 +1,19 @@
import * as React from 'react';
import { Text, TextProps } from '@chakra-ui/react';
import truncateMiddle from 'truncate-middle';
interface UsernameProps extends TextProps {
address: string;
}
const Username: React.FunctionComponent<UsernameProps> = ({ address, ...otherProps }) => {
const data = address;
return (
<Text display='inline' textTransform={data ? 'none' : 'uppercase'} {...otherProps}>
{truncateMiddle(address || '', 6, 5, '...')}
</Text>
);
};
export default Username;

View File

@ -0,0 +1,96 @@
import * as wagmi from "wagmi";
import { useProvider, useSigner } from "wagmi";
import type { BigNumber } from "ethers";
// Import our contract ABI (a json representation of our contract's public interface).
// The hardhat compiler writes this file to artifacts every time we run `npx hardhat`.
import ForumContract from '../../../Hardhat/artifacts/contracts/Forum.sol/Forum.json';
export enum ForumEvent {
QuestionAdded = 'QuestionAdded',
AnswerAdded = 'AnswerAdded',
AnswerUpvoted = 'AnswerUpvoted',
}
export interface Question {
questionId: BigNumber;
message: string;
creatorAddress: string;
timestamp: BigNumber;
}
export interface Answer {
answerId: BigNumber;
questionId: BigNumber;
creatorAddress: string;
message: string;
timestamp: BigNumber;
upvotes: BigNumber;
}
const useForumContract = () => {
// An ethers.Provider instance. This will help us read from the contract
// even if we don't have a logged in wallet
const provider = useProvider();
const { data: signer } = useSigner();
// This returns a new ethers.Contract ready to interact with our API.
// We need to pass in the address of our deployed contract as well as its abi.
const contract = wagmi.useContract({
// Add the address that was output from your deploy script
addressOrName: '0x1Bd7ba264a48F128C9Afdb381A9Ed48A01e8929B',
contractInterface: ForumContract.abi,
signerOrProvider: signer || provider,
});
// Wrapper to fetch a question from the contract
const getQuestion = async (questionId: BigNumber): Promise<Question> => {
return {...await contract.questions(questionId)};
};
const getAllQuestions = async (): Promise<Question[]> => {
const qArray = await contract.getQuestions();
return qArray.map((q: Question) => ({ ...q }));
};
const getAnswers = async (questionId: BigNumber): Promise<Answer[]> => {
const answerIds: BigNumber[] = await contract.getAnswersPerQuestion(questionId);
const mappedAnswers = answerIds.map((answerId: BigNumber) => contract.answers(answerId));
const allAnswers = await Promise.all(mappedAnswers);
return allAnswers.map((a) => {
return { ...a };
});
};
const getUpvotes = async (answerId: BigNumber): Promise<BigNumber> => {
return await contract.getUpvotes(answerId);
};
const postQuestion = async (message: string): Promise<void> => {
const tx = await contract.postQuestion(message);
await tx.wait();
};
const postAnswer = async (questionId: BigNumber, message: string): Promise<void> => {
const tx = await contract.postAnswer(questionId, message);
await tx.wait();
};
const upvoteAnswer = async (answerId: BigNumber): Promise<void> => {
const tx = await contract.upvoteAnswer(answerId);
await tx.wait();
};
return {
contract,
chainId: contract.provider.network?.chainId,
getQuestion,
getAllQuestions,
getAnswers,
getUpvotes,
postQuestion,
postAnswer,
upvoteAnswer,
};
};
export default useForumContract;

View File

@ -0,0 +1,52 @@
import * as wagmi from 'wagmi';
import { useProvider, useSigner } from 'wagmi';
import { makeNum } from '../../lib/number-utils';
import type { BigNumber } from 'ethers';
import GoflowContract from '../../../Hardhat/artifacts/contracts/OurToken.sol/Goflow.json';
export enum TokenEvent {
Transfer = 'Transfer',
Mint = 'Mint',
}
export type Amount = BigNumber;
const useGoflowContract = () => {
const { data: signer } = useSigner();
const provider = useProvider();
const contract = wagmi.useContract({
// Change this adress after every deploy!
addressOrName: '0xd70390c032DDb6c73C03930db1203f5C3C784C04',
contractInterface: GoflowContract.abi,
signerOrProvider: signer || provider,
});
// Get a user's balance and convert to readable number
const getBalance = async (address: string): Promise<string> => {
const userBalanceBN = await contract.balanceOf(address);
return makeNum(userBalanceBN);
};
// "We have to approve before we can move" with transferFrom
const approve = async (address: string, amount: BigNumber): Promise<void> => {
const tx = await contract.approve(address, amount);
await tx.wait();
};
const mint = async (amount: BigNumber): Promise<void> => {
const tx = await contract.mint(amount);
await tx.wait();
};
return {
contract,
chainId: contract.provider.network?.chainId,
mint,
approve,
getBalance,
};
};
export default useGoflowContract;

View File

@ -0,0 +1,17 @@
import type { BigNumber } from 'ethers';
import { useMutation } from 'react-query';
import useForumContract from './contracts/useForumContract';
interface UseAddAnswerPayload {
questionId: BigNumber;
message: string;
}
const useAddAnswer = () => {
const contract = useForumContract();
return useMutation(async ({ questionId, message }: UseAddAnswerPayload) => {
await contract.postAnswer(questionId, message);
});
};
export default useAddAnswer;

View File

@ -0,0 +1,17 @@
import { makeBig } from '../lib/number-utils';
import { useMutation } from 'react-query';
import useGoflowContract from './contracts/useGoflowContract';
interface UseApprovePayload {
address: string;
amount: string;
}
const useAddApprove = () => {
const contract = useGoflowContract();
return useMutation(async ({ address, amount }: UseApprovePayload) => {
await contract.approve(address, makeBig(amount));
});
};
export default useAddApprove;

View File

@ -0,0 +1,16 @@
import { makeBig } from '../lib/number-utils';
import { useMutation } from 'react-query';
import useGoflowContract from './contracts/useGoflowContract';
interface UseMintPayload {
amount: string;
}
const useAddMint = () => {
const contract = useGoflowContract();
return useMutation(async ({ amount }: UseMintPayload) => {
await contract.mint(makeBig(amount));
});
};
export default useAddMint;

View File

@ -0,0 +1,16 @@
import { useMutation } from 'react-query';
import useForumContract from './contracts/useForumContract';
interface UseAddQuestionPayload {
message: string;
}
const useAddQuestion = () => {
const contract = useForumContract();
return useMutation(async ({ message }: UseAddQuestionPayload) => {
console.log('here')
await contract.postQuestion(message);
});
};
export default useAddQuestion;

View File

@ -0,0 +1,16 @@
import type { BigNumber } from 'ethers';
import { useMutation } from 'react-query';
import useForumContract from './contracts/useForumContract';
interface UseAddUpvotePayload {
answerId: BigNumber;
}
const useAddUpvote = () => {
const contract = useForumContract();
return useMutation(async ({ answerId }: UseAddUpvotePayload) => {
await contract.upvoteAnswer(answerId);
});
};
export default useAddUpvote;

View File

@ -0,0 +1,21 @@
import type { BigNumber } from 'ethers';
import { useQuery } from 'react-query';
import useForumContract from './contracts/useForumContract';
interface UseAnswersQuery {
questionId: BigNumber;
}
const useAnswers = ({ questionId }: UseAnswersQuery) => {
const contract = useForumContract();
return useQuery(
['answers', questionId.toNumber()],
async () => {
return await contract.getAnswers(questionId);
},
{ enabled: !!questionId }
);
};
export default useAnswers;

View File

@ -0,0 +1,30 @@
import { useQuery } from 'react-query';
import { useAccount } from 'wagmi';
import useGoflowContract from './contracts/useGoflowContract';
import useForumContract from './contracts/useForumContract';
const useBalance = () => {
const forumContract = useForumContract();
const goflowContract = useGoflowContract();
const { address: account } = useAccount();
const contractBalanceQuery = useQuery(['contractBalance'], async () => {
return await goflowContract.getBalance(forumContract.contract.address);
});
const userBalanceQuery = useQuery(
['userBalance', account],
async () => {
if (account) {
return await goflowContract.getBalance(account);
} else {
return '0';
}
},
{ enabled: !!account }
);
return { contractBalanceQuery, userBalanceQuery };
};
export default useBalance;

View File

@ -0,0 +1,76 @@
import type { BigNumber, Event } from 'ethers';
import { constants } from 'ethers';
import { useEffect } from 'react';
import { useQueryClient } from 'react-query';
import { useAccount } from 'wagmi';
import useGoflowContract, { TokenEvent } from './contracts/useGoflowContract';
import useForumContract, { Answer, ForumEvent } from './contracts/useForumContract';
import { makeNum } from '../lib/number-utils';
import truncateMiddle from 'truncate-middle';
interface UseEventsQuery {
questionId?: BigNumber;
}
// Listen to events and refresh data
const useEvents = ({ questionId }: UseEventsQuery) => {
const { address: account } = useAccount();
const queryClient = useQueryClient();
const forumContract = useForumContract();
const tokenContract = useGoflowContract();
useEffect(() => {
const questionHandler = () => {
// refetch all questions whenever we call this handler
queryClient.invalidateQueries(['questions']);
};
const answerHandler = (answer: Answer, emittedEvent: Event) => {
if (questionId) {
const answerQidNumber = answer.questionId.toNumber();
const questionIdNumber = questionId.toNumber();
const answerIdNumber = answer.answerId.toNumber();
if (answerQidNumber !== questionIdNumber) {
return;
}
// Check which event we've received
// and only refetch the query by its id
if (emittedEvent.event === ForumEvent.AnswerAdded) {
queryClient.invalidateQueries(['answers', answerQidNumber]);
} else if (emittedEvent.event === ForumEvent.AnswerUpvoted) {
queryClient.invalidateQueries(['upvotes', answerIdNumber]);
}
}
};
// Consume the Transfer event from the ERC20 token standard
const transferHandler = async (from: string, to: string, amount: BigNumber, emittedEvent: Event) => {
if (to === forumContract.contract.address) {
console.log(`Transferred ${makeNum(amount)} GOFLOW to Forum contract`);
queryClient.invalidateQueries(['contractBalance']);
} else if (from === constants.AddressZero) {
// e.g. '0x0000000000000000000000000000000000000000'
console.log(`Minted ${makeNum(amount)} GOFLOW to: ${truncateMiddle(to, 6, 5, '...')}`);
queryClient.invalidateQueries(['userBalance', to]);
} else {
console.log(`Transferred ${makeNum(amount)} GOFLOW to: ${truncateMiddle(to, 6, 5, '...')}`);
queryClient.invalidateQueries(['userBalance', to]);
}
};
forumContract.contract.on(ForumEvent.QuestionAdded, questionHandler);
forumContract.contract.on(ForumEvent.AnswerAdded, answerHandler);
forumContract.contract.on(ForumEvent.AnswerUpvoted, answerHandler);
tokenContract.contract.on(TokenEvent.Transfer, transferHandler);
return () => {
forumContract.contract.off(ForumEvent.QuestionAdded, questionHandler);
forumContract.contract.off(ForumEvent.AnswerAdded, answerHandler);
forumContract.contract.off(ForumEvent.AnswerUpvoted, answerHandler);
tokenContract.contract.off(TokenEvent.Transfer, transferHandler);
};
}, [queryClient, questionId, forumContract, tokenContract, account]);
};
export default useEvents;

View File

@ -0,0 +1,29 @@
import { BigNumber } from 'ethers';
import { useQuery } from 'react-query';
import useForumContract from './contracts/useForumContract';
interface UseQuestionQuery {
questionId?: BigNumber;
}
const useQuestions = ({ questionId }: UseQuestionQuery) => {
const contract = useForumContract();
const questionQuery = useQuery(
['question', questionId?.toNumber()],
async () => {
if (questionId) {
return await contract.getQuestion(questionId);
}
},
{ enabled: !!questionId } // ensures questionId has a value before fetching
);
const allQuestionsQuery = useQuery(['questions'], async () => {
return await contract.getAllQuestions();
});
return { questionQuery, allQuestionsQuery };
};
export default useQuestions;

View File

@ -0,0 +1,17 @@
import { BigNumber } from 'ethers';
import { useQuery } from 'react-query';
import useForumContract from './contracts/useForumContract';
interface UseUpvotesQuery {
answerId: BigNumber;
}
const useUpvotes = ({ answerId }: UseUpvotesQuery) => {
const contract = useForumContract();
return useQuery(['upvotes', answerId.toNumber()], async () => {
return await contract.getUpvotes(answerId);
});
};
export default useUpvotes;

59
Front-end/lib/accounts.md Normal file
View File

@ -0,0 +1,59 @@
✅ Account #0: 0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266 (10000 ETH)
Private Key: 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80
✅ Account #1: 0x70997970c51812dc3a010c7d01b50e0d17dc79c8 (10000 ETH)
Private Key: 0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d
Account #2: 0x3c44cdddb6a900fa2b585dd299e03d12fa4293bc (10000 ETH)
Private Key: 0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a
Account #3: 0x90f79bf6eb2c4f870365e785982e1f101e93b906 (10000 ETH)
Private Key: 0x7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6
Account #4: 0x15d34aaf54267db7d7c367839aaf71a00a2c6a65 (10000 ETH)
Private Key: 0x47e179ec197488593b187f80a00eb0da91f1b9d0b13f8733639f19c30a34926a
Account #5: 0x9965507d1a55bcc2695c58ba16fb37d819b0a4dc (10000 ETH)
Private Key: 0x8b3a350cf5c34c9194ca85829a2df0ec3153be0318b5e2d3348e872092edffba
Account #6: 0x976ea74026e726554db657fa54763abd0c3a0aa9 (10000 ETH)
Private Key: 0x92db14e403b83dfe3df233f83dfa3a0d7096f21ca9b0d6d6b8d88b2b4ec1564e
Account #7: 0x14dc79964da2c08b23698b3d3cc7ca32193d9955 (10000 ETH)
Private Key: 0x4bbbf85ce3377467afe5d46f804f221813b2bb87f24d81f60f1fcdbf7cbf4356
Account #8: 0x23618e81e3f5cdf7f54c3d65f7fbc0abf5b21e8f (10000 ETH)
Private Key: 0xdbda1821b80551c9d65939329250298aa3472ba22feea921c0cf5d620ea67b97
Account #9: 0xa0ee7a142d267c1f36714e4a8f75612f20a79720 (10000 ETH)
Private Key: 0x2a871d0798f97d79848a013d4936a73bf4cc922c825d33c1cf7073dff6d409c6
Account #10: 0xbcd4042de499d14e55001ccbb24a551f3b954096 (10000 ETH)
Private Key: 0xf214f2b2cd398c806f84e317254e0f0b801d0643303237d97a22a48e01628897
Account #11: 0x71be63f3384f5fb98995898a86b02fb2426c5788 (10000 ETH)
Private Key: 0x701b615bbdfb9de65240bc28bd21bbc0d996645a3dd57e7b12bc2bdf6f192c82
Account #12: 0xfabb0ac9d68b0b445fb7357272ff202c5651694a (10000 ETH)
Private Key: 0xa267530f49f8280200edf313ee7af6b827f2a8bce2897751d06a843f644967b1
Account #13: 0x1cbd3b2770909d4e10f157cabc84c7264073c9ec (10000 ETH)
Private Key: 0x47c99abed3324a2707c28affff1267e45918ec8c3f20b8aa892e8b065d2942dd
Account #14: 0xdf3e18d64bc6a983f673ab319ccae4f1a57c7097 (10000 ETH)
Private Key: 0xc526ee95bf44d8fc405a158bb884d9d1238d99f0612e9f33d006bb0789009aaa
Account #15: 0xcd3b766ccdd6ae721141f452c550ca635964ce71 (10000 ETH)
Private Key: 0x8166f546bab6da521a8369cab06c5d2b9e46670292d85c875ee9ec20e84ffb61
Account #16: 0x2546bcd3c84621e976d8185a91a922ae77ecec30 (10000 ETH)
Private Key: 0xea6c44ac03bff858b476bba40716402b03e41b8e97e276d1baec7c37d42484a0
Account #17: 0xbda5747bfd65f08deb54cb465eb87d40e51b197e (10000 ETH)
Private Key: 0x689af8efa8c651a91ad287602527f3af2fe9f6501a7ac4b061667b5a93e037fd
Account #18: 0xdd2fd4581271e230360230f9337d5c0430bf44c0 (10000 ETH)
Private Key: 0xde9be858da4a475276426320d5e9262ecfc3ba460bfac56360bfa6c4c28b4ee0
✅ Account #19: 0x8626f6940e2eb28930efb4cef49b2d1f2c9c1199 (10000 ETH)
Private Key: 0xdf57089febbacf7ba0bc227dafbffa9fc08a93fdc68e1e42411a14efcf23656e

View File

@ -0,0 +1,26 @@
import { BigNumber, ethers } from 'ethers';
/**
* converts the number to a BigNumber with the correct units to keep Solidity happy
* NOTE: Math in Solidity only uses fixed-point numbers so we use the smallest unit, i.e. n * 10^18
* e.g. makeBig(1) = 1000000000000000000, as 1 ETH is equal to 1000000000000000000 wei
* for more info see https://docs.openzeppelin.com/contracts/3.x/erc20#a-note-on-decimals
*/
const makeBig = (value: string | number) => {
if (typeof value === 'number') {
value = value.toString();
}
return ethers.utils.parseUnits(value);
};
/**
* converts a BigNumber to a user-friendly string for readability
* e.g. makeNum(1345600000000000000) = 1.34
* for more info see https://docs.ethers.io/v5/api/utils/display-logic/
*/
const makeNum = (value: BigNumber) => {
const numStr = ethers.utils.formatUnits(value, 18);
return numStr.substring(0, numStr.indexOf('.') + 3); // keep only 2 decimals
};
export { makeBig, makeNum };

View File

@ -9,6 +9,7 @@
"version": "0.1.0",
"dependencies": {
"@chakra-ui/react": "^2.2.1",
"@davatar/react": "^1.10.4",
"@emotion/react": "^11.9.3",
"@emotion/styled": "^11.9.3",
"@fontsource/poppins": "^4.5.8",
@ -20,12 +21,16 @@
"react-hot-toast": "^2.2.0",
"react-icons": "^4.4.0",
"react-query": "^3.39.1",
"react-timeago": "^7.1.0",
"truncate-middle": "^1.0.6",
"wagmi": "^0.5.6"
},
"devDependencies": {
"@types/node": "18.0.1",
"@types/react": "18.0.14",
"@types/react-dom": "18.0.6",
"@types/react-timeago": "^4.1.3",
"@types/truncate-middle": "^1.0.1",
"eslint": "8.19.0",
"eslint-config-next": "12.2.0",
"typescript": "4.7.4"
@ -1382,6 +1387,26 @@
"node": ">=10"
}
},
"node_modules/@davatar/react": {
"version": "1.10.4",
"resolved": "https://registry.npmjs.org/@davatar/react/-/react-1.10.4.tgz",
"integrity": "sha512-q6Ce+bbV2FGzaIj+eXIxaxfupGUr04i+xPAWGSVzPpTVHp4tYQyvvc4w9eX4IMupDNC3N6doYGk2ax7r745xWA==",
"dependencies": {
"@ethersproject/abstract-signer": "^5",
"@ethersproject/contracts": "^5",
"@ethersproject/logger": "^5",
"@ethersproject/properties": "^5",
"@ethersproject/providers": "^5",
"@types/react-blockies": "^1.4.1",
"bn.js": "^5.2.0",
"color": "^3.2.1",
"mersenne-twister": "^1.1.0",
"react-blockies": "^1.4.1"
},
"peerDependencies": {
"react": ">=16.8"
}
},
"node_modules/@emotion/babel-plugin": {
"version": "11.9.2",
"resolved": "https://registry.npmjs.org/@emotion/babel-plugin/-/babel-plugin-11.9.2.tgz",
@ -2628,20 +2653,26 @@
"node_modules/@types/prop-types": {
"version": "15.7.5",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.5.tgz",
"integrity": "sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w==",
"devOptional": true
"integrity": "sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w=="
},
"node_modules/@types/react": {
"version": "18.0.14",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.0.14.tgz",
"integrity": "sha512-x4gGuASSiWmo0xjDLpm5mPb52syZHJx02VKbqUKdLmKtAwIh63XClGsiTI1K6DO5q7ox4xAsQrU+Gl3+gGXF9Q==",
"devOptional": true,
"dependencies": {
"@types/prop-types": "*",
"@types/scheduler": "*",
"csstype": "^3.0.2"
}
},
"node_modules/@types/react-blockies": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@types/react-blockies/-/react-blockies-1.4.1.tgz",
"integrity": "sha512-aDX0g0hwzdodkGLSDNUQr6gXxwclGjnhS8jhsR8uQhAfe/7i3GZD/NDcSlQ2SiQiLhfRxX3NlY+nvBwf5Y0tTg==",
"dependencies": {
"@types/react": "*"
}
},
"node_modules/@types/react-dom": {
"version": "18.0.6",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.0.6.tgz",
@ -2651,11 +2682,19 @@
"@types/react": "*"
}
},
"node_modules/@types/react-timeago": {
"version": "4.1.3",
"resolved": "https://registry.npmjs.org/@types/react-timeago/-/react-timeago-4.1.3.tgz",
"integrity": "sha512-XaaMBzuXLw7lxPPDs/fenlohcf3NDqM5qP4oOL/Meu+Hb1QChW4Igw/SruS1llEqch18RQB3wDTIwvqq4nivvw==",
"dev": true,
"dependencies": {
"@types/react": "*"
}
},
"node_modules/@types/scheduler": {
"version": "0.16.2",
"resolved": "https://registry.npmjs.org/@types/scheduler/-/scheduler-0.16.2.tgz",
"integrity": "sha512-hppQEBDmlwhFAXKJX2KnWLYu5yMfi91yazPb2l+lbJiwW+wdo1gNeRA+3RgNSO39WYX2euey41KEwnqesU2Jew==",
"devOptional": true
"integrity": "sha512-hppQEBDmlwhFAXKJX2KnWLYu5yMfi91yazPb2l+lbJiwW+wdo1gNeRA+3RgNSO39WYX2euey41KEwnqesU2Jew=="
},
"node_modules/@types/secp256k1": {
"version": "4.0.3",
@ -2665,6 +2704,12 @@
"@types/node": "*"
}
},
"node_modules/@types/truncate-middle": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@types/truncate-middle/-/truncate-middle-1.0.1.tgz",
"integrity": "sha512-HpUx5cnvMJpeCIqS3Q0neIviFWIH8W6nSmPhAMdzugxiCywOBy0n5OeZgJ+0u3GibDg8ZboxHYYKUg9ArtRdJg==",
"dev": true
},
"node_modules/@types/use-sync-external-store": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz",
@ -3545,6 +3590,20 @@
"resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz",
"integrity": "sha512-571s0T7nZWK6vB67HI5dyUF7wXiNcfaPPPTl6zYCNApANjIvYJTg7hlud/+cJpdAhS7dVzqMLmfhfHR3rAcOjQ=="
},
"node_modules/bufferutil": {
"version": "4.0.6",
"resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.0.6.tgz",
"integrity": "sha512-jduaYOYtnio4aIAyc6UbvPCVcgq7nYpVnucyxr6eCYg/Woad9Hf/oxxBRDnGGjPfjUm6j5O/uBWhIu4iLebFaw==",
"hasInstallScript": true,
"optional": true,
"peer": true,
"dependencies": {
"node-gyp-build": "^4.3.0"
},
"engines": {
"node": ">=6.14.2"
}
},
"node_modules/call-bind": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz",
@ -3658,6 +3717,15 @@
"node": ">=6"
}
},
"node_modules/color": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/color/-/color-3.2.1.tgz",
"integrity": "sha512-aBl7dZI9ENN6fUGC7mWpMTPNHmWUSNan9tuWN6ahh5ZLNk9baLJOnSMlrQkHcrfFgz2/RigjUVAjdx36VcemKA==",
"dependencies": {
"color-convert": "^1.9.3",
"color-string": "^1.6.0"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@ -3673,8 +3741,29 @@
"node_modules/color-name": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"dev": true
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="
},
"node_modules/color-string": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz",
"integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==",
"dependencies": {
"color-name": "^1.0.0",
"simple-swizzle": "^0.2.2"
}
},
"node_modules/color/node_modules/color-convert": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
"integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
"dependencies": {
"color-name": "1.1.3"
}
},
"node_modules/color/node_modules/color-name": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
"integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw=="
},
"node_modules/compute-scroll-into-view": {
"version": "1.0.14",
@ -5823,6 +5912,11 @@
"node": ">= 8"
}
},
"node_modules/mersenne-twister": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/mersenne-twister/-/mersenne-twister-1.1.0.tgz",
"integrity": "sha512-mUYWsMKNrm4lfygPkL3OfGzOPTR2DBlTkBNHM//F6hGp8cLThY897crAlk3/Jo17LEOOjQUrNAx6DvgO77QJkA=="
},
"node_modules/micromatch": {
"version": "4.0.5",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz",
@ -6453,6 +6547,17 @@
"node": ">=0.10.0"
}
},
"node_modules/react-blockies": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/react-blockies/-/react-blockies-1.4.1.tgz",
"integrity": "sha512-4N015X5oPNnD3xQPsiqolOFzPZSSWyc5mJhJUZShUCHtiGUxVN+1qsWTcglkHMNySux9hUofaispqcw9QkWP5Q==",
"dependencies": {
"prop-types": "^15.5.10"
},
"peerDependencies": {
"react": ">=15.0.0"
}
},
"node_modules/react-clientside-effect": {
"version": "1.2.6",
"resolved": "https://registry.npmjs.org/react-clientside-effect/-/react-clientside-effect-1.2.6.tgz",
@ -6623,6 +6728,14 @@
}
}
},
"node_modules/react-timeago": {
"version": "7.1.0",
"resolved": "https://registry.npmjs.org/react-timeago/-/react-timeago-7.1.0.tgz",
"integrity": "sha512-rouF7MiEm55fH791Y8cg+VobIJgx8gtNJ+gjr86R4ZqO1WKPkXiXjdT/lRzrvEkUzsxT1exHqV2V+Zdi114H3A==",
"peerDependencies": {
"react": "^16.0.0 || ^17.0.0 || ^18.0.0"
}
},
"node_modules/readable-stream": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz",
@ -6911,6 +7024,19 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/simple-swizzle": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz",
"integrity": "sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==",
"dependencies": {
"is-arrayish": "^0.3.1"
}
},
"node_modules/simple-swizzle/node_modules/is-arrayish": {
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz",
"integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ=="
},
"node_modules/slash": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz",
@ -7212,6 +7338,11 @@
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
},
"node_modules/truncate-middle": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/truncate-middle/-/truncate-middle-1.0.6.tgz",
"integrity": "sha512-oJLDTdHAk27V+JUUu1vKYezKehx/tECV0vnJ1e8JV/rvre5oLoFMaCLP53ZwiPsw4ZIJzyLoZr/TKQABnaNF6A=="
},
"node_modules/tsconfig-paths": {
"version": "3.14.1",
"resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.14.1.tgz",
@ -7401,6 +7532,20 @@
"react": "^16.8.0 || ^17.0.0 || ^18.0.0"
}
},
"node_modules/utf-8-validate": {
"version": "5.0.9",
"resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.9.tgz",
"integrity": "sha512-Yek7dAy0v3Kl0orwMlvi7TPtiCNrdfHNd7Gcc/pLq4BLXqfAmd0J7OWMizUQnTTJsyjKn02mU7anqwfmUP4J8Q==",
"hasInstallScript": true,
"optional": true,
"peer": true,
"dependencies": {
"node-gyp-build": "^4.3.0"
},
"engines": {
"node": ">=6.14.2"
}
},
"node_modules/util": {
"version": "0.12.4",
"resolved": "https://registry.npmjs.org/util/-/util-0.12.4.tgz",
@ -8772,6 +8917,23 @@
"resolved": "https://registry.npmjs.org/@ctrl/tinycolor/-/tinycolor-3.4.1.tgz",
"integrity": "sha512-ej5oVy6lykXsvieQtqZxCOaLT+xD4+QNarq78cIYISHmZXshCvROLudpQN3lfL8G0NL7plMSSK+zlyvCaIJ4Iw=="
},
"@davatar/react": {
"version": "1.10.4",
"resolved": "https://registry.npmjs.org/@davatar/react/-/react-1.10.4.tgz",
"integrity": "sha512-q6Ce+bbV2FGzaIj+eXIxaxfupGUr04i+xPAWGSVzPpTVHp4tYQyvvc4w9eX4IMupDNC3N6doYGk2ax7r745xWA==",
"requires": {
"@ethersproject/abstract-signer": "^5",
"@ethersproject/contracts": "^5",
"@ethersproject/logger": "^5",
"@ethersproject/properties": "^5",
"@ethersproject/providers": "^5",
"@types/react-blockies": "^1.4.1",
"bn.js": "^5.2.0",
"color": "^3.2.1",
"mersenne-twister": "^1.1.0",
"react-blockies": "^1.4.1"
}
},
"@emotion/babel-plugin": {
"version": "11.9.2",
"resolved": "https://registry.npmjs.org/@emotion/babel-plugin/-/babel-plugin-11.9.2.tgz",
@ -9545,20 +9707,26 @@
"@types/prop-types": {
"version": "15.7.5",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.5.tgz",
"integrity": "sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w==",
"devOptional": true
"integrity": "sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w=="
},
"@types/react": {
"version": "18.0.14",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.0.14.tgz",
"integrity": "sha512-x4gGuASSiWmo0xjDLpm5mPb52syZHJx02VKbqUKdLmKtAwIh63XClGsiTI1K6DO5q7ox4xAsQrU+Gl3+gGXF9Q==",
"devOptional": true,
"requires": {
"@types/prop-types": "*",
"@types/scheduler": "*",
"csstype": "^3.0.2"
}
},
"@types/react-blockies": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@types/react-blockies/-/react-blockies-1.4.1.tgz",
"integrity": "sha512-aDX0g0hwzdodkGLSDNUQr6gXxwclGjnhS8jhsR8uQhAfe/7i3GZD/NDcSlQ2SiQiLhfRxX3NlY+nvBwf5Y0tTg==",
"requires": {
"@types/react": "*"
}
},
"@types/react-dom": {
"version": "18.0.6",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.0.6.tgz",
@ -9568,11 +9736,19 @@
"@types/react": "*"
}
},
"@types/react-timeago": {
"version": "4.1.3",
"resolved": "https://registry.npmjs.org/@types/react-timeago/-/react-timeago-4.1.3.tgz",
"integrity": "sha512-XaaMBzuXLw7lxPPDs/fenlohcf3NDqM5qP4oOL/Meu+Hb1QChW4Igw/SruS1llEqch18RQB3wDTIwvqq4nivvw==",
"dev": true,
"requires": {
"@types/react": "*"
}
},
"@types/scheduler": {
"version": "0.16.2",
"resolved": "https://registry.npmjs.org/@types/scheduler/-/scheduler-0.16.2.tgz",
"integrity": "sha512-hppQEBDmlwhFAXKJX2KnWLYu5yMfi91yazPb2l+lbJiwW+wdo1gNeRA+3RgNSO39WYX2euey41KEwnqesU2Jew==",
"devOptional": true
"integrity": "sha512-hppQEBDmlwhFAXKJX2KnWLYu5yMfi91yazPb2l+lbJiwW+wdo1gNeRA+3RgNSO39WYX2euey41KEwnqesU2Jew=="
},
"@types/secp256k1": {
"version": "4.0.3",
@ -9582,6 +9758,12 @@
"@types/node": "*"
}
},
"@types/truncate-middle": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@types/truncate-middle/-/truncate-middle-1.0.1.tgz",
"integrity": "sha512-HpUx5cnvMJpeCIqS3Q0neIviFWIH8W6nSmPhAMdzugxiCywOBy0n5OeZgJ+0u3GibDg8ZboxHYYKUg9ArtRdJg==",
"dev": true
},
"@types/use-sync-external-store": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz",
@ -10259,6 +10441,16 @@
"resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz",
"integrity": "sha512-571s0T7nZWK6vB67HI5dyUF7wXiNcfaPPPTl6zYCNApANjIvYJTg7hlud/+cJpdAhS7dVzqMLmfhfHR3rAcOjQ=="
},
"bufferutil": {
"version": "4.0.6",
"resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.0.6.tgz",
"integrity": "sha512-jduaYOYtnio4aIAyc6UbvPCVcgq7nYpVnucyxr6eCYg/Woad9Hf/oxxBRDnGGjPfjUm6j5O/uBWhIu4iLebFaw==",
"optional": true,
"peer": true,
"requires": {
"node-gyp-build": "^4.3.0"
}
},
"call-bind": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz",
@ -10337,6 +10529,30 @@
"resolved": "https://registry.npmjs.org/clsx/-/clsx-1.2.0.tgz",
"integrity": "sha512-EPRP7XJsM1y0iCU3Z7C7jFKdQboXSeHgEfzQUTlz7m5NP3hDrlz48aUsmNGp4pC+JOW9WA3vIRqlYuo/bl4Drw=="
},
"color": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/color/-/color-3.2.1.tgz",
"integrity": "sha512-aBl7dZI9ENN6fUGC7mWpMTPNHmWUSNan9tuWN6ahh5ZLNk9baLJOnSMlrQkHcrfFgz2/RigjUVAjdx36VcemKA==",
"requires": {
"color-convert": "^1.9.3",
"color-string": "^1.6.0"
},
"dependencies": {
"color-convert": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
"integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
"requires": {
"color-name": "1.1.3"
}
},
"color-name": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
"integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw=="
}
}
},
"color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@ -10349,8 +10565,16 @@
"color-name": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"dev": true
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="
},
"color-string": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz",
"integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==",
"requires": {
"color-name": "^1.0.0",
"simple-swizzle": "^0.2.2"
}
},
"compute-scroll-into-view": {
"version": "1.0.14",
@ -12038,6 +12262,11 @@
"integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",
"dev": true
},
"mersenne-twister": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/mersenne-twister/-/mersenne-twister-1.1.0.tgz",
"integrity": "sha512-mUYWsMKNrm4lfygPkL3OfGzOPTR2DBlTkBNHM//F6hGp8cLThY897crAlk3/Jo17LEOOjQUrNAx6DvgO77QJkA=="
},
"micromatch": {
"version": "4.0.5",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz",
@ -12471,6 +12700,14 @@
"loose-envify": "^1.1.0"
}
},
"react-blockies": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/react-blockies/-/react-blockies-1.4.1.tgz",
"integrity": "sha512-4N015X5oPNnD3xQPsiqolOFzPZSSWyc5mJhJUZShUCHtiGUxVN+1qsWTcglkHMNySux9hUofaispqcw9QkWP5Q==",
"requires": {
"prop-types": "^15.5.10"
}
},
"react-clientside-effect": {
"version": "1.2.6",
"resolved": "https://registry.npmjs.org/react-clientside-effect/-/react-clientside-effect-1.2.6.tgz",
@ -12566,6 +12803,12 @@
"tslib": "^2.0.0"
}
},
"react-timeago": {
"version": "7.1.0",
"resolved": "https://registry.npmjs.org/react-timeago/-/react-timeago-7.1.0.tgz",
"integrity": "sha512-rouF7MiEm55fH791Y8cg+VobIJgx8gtNJ+gjr86R4ZqO1WKPkXiXjdT/lRzrvEkUzsxT1exHqV2V+Zdi114H3A==",
"requires": {}
},
"readable-stream": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz",
@ -12776,6 +13019,21 @@
"object-inspect": "^1.9.0"
}
},
"simple-swizzle": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz",
"integrity": "sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==",
"requires": {
"is-arrayish": "^0.3.1"
},
"dependencies": {
"is-arrayish": {
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz",
"integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ=="
}
}
},
"slash": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz",
@ -12990,6 +13248,11 @@
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
},
"truncate-middle": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/truncate-middle/-/truncate-middle-1.0.6.tgz",
"integrity": "sha512-oJLDTdHAk27V+JUUu1vKYezKehx/tECV0vnJ1e8JV/rvre5oLoFMaCLP53ZwiPsw4ZIJzyLoZr/TKQABnaNF6A=="
},
"tsconfig-paths": {
"version": "3.14.1",
"resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.14.1.tgz",
@ -13114,6 +13377,16 @@
"integrity": "sha512-SEnieB2FPKEVne66NpXPd1Np4R1lTNKfjuy3XdIoPQKYBAFdzbzSZlSn1KJZUiihQLQC5Znot4SBz1EOTBwQAQ==",
"requires": {}
},
"utf-8-validate": {
"version": "5.0.9",
"resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.9.tgz",
"integrity": "sha512-Yek7dAy0v3Kl0orwMlvi7TPtiCNrdfHNd7Gcc/pLq4BLXqfAmd0J7OWMizUQnTTJsyjKn02mU7anqwfmUP4J8Q==",
"optional": true,
"peer": true,
"requires": {
"node-gyp-build": "^4.3.0"
}
},
"util": {
"version": "0.12.4",
"resolved": "https://registry.npmjs.org/util/-/util-0.12.4.tgz",

View File

@ -10,6 +10,7 @@
},
"dependencies": {
"@chakra-ui/react": "^2.2.1",
"@davatar/react": "^1.10.4",
"@emotion/react": "^11.9.3",
"@emotion/styled": "^11.9.3",
"@fontsource/poppins": "^4.5.8",
@ -21,12 +22,16 @@
"react-hot-toast": "^2.2.0",
"react-icons": "^4.4.0",
"react-query": "^3.39.1",
"react-timeago": "^7.1.0",
"truncate-middle": "^1.0.6",
"wagmi": "^0.5.6"
},
"devDependencies": {
"@types/node": "18.0.1",
"@types/react": "18.0.14",
"@types/react-dom": "18.0.6",
"@types/react-timeago": "^4.1.3",
"@types/truncate-middle": "^1.0.1",
"eslint": "8.19.0",
"eslint-config-next": "12.2.0",
"typescript": "4.7.4"

View File

@ -6,8 +6,17 @@ import { ChakraProvider } from '@chakra-ui/react';
import { Toaster, toast } from 'react-hot-toast';
import { ReactQueryDevtools } from 'react-query/devtools';
import { QueryClient, QueryClientProvider, QueryCache } from 'react-query';
import { WagmiConfig, createClient } from 'wagmi';
import { providers } from 'ethers';
// Use wagmi to configure the provider.
const quicknodeProvider = new providers.JsonRpcProvider('<YOUR-QUICKNODE-POLYGON-URL>');
// Give wagmi our provider config and allow it to autoconnect wallet
const client = createClient({
autoConnect: true,
provider: quicknodeProvider,
});
// Create a react-query client
const queryClient = new QueryClient({
defaultOptions: {
queries: {
@ -25,14 +34,17 @@ const queryClient = new QueryClient({
function MyApp({ Component, pageProps }: AppProps) {
return (
<ChakraProvider theme={theme}>
<QueryClientProvider client={queryClient}>
<Navbar />
<Component {...pageProps} />
<Toaster position='bottom-right' />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
</ChakraProvider>
// Provide the WagmiConfig at the top-level of our app
<WagmiConfig client={client}>
<ChakraProvider theme={theme}>
<QueryClientProvider client={queryClient}>
<Navbar />
<Component {...pageProps} />
<Toaster position='bottom-right' />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
</ChakraProvider>
</WagmiConfig>
);
}

View File

@ -1,18 +1,12 @@
import type { NextPage } from 'next';
import * as React from 'react';
import { Box, Text, Stack, Image } from '@chakra-ui/react';
import { Box } from '@chakra-ui/react';
import Questions from '../components/Questions';
const App: NextPage = () => {
return (
<Box p={8} maxW='600px' minW='320px' m='0 auto'>
<Stack align='center'>
<Image width={300} src='https://c.tenor.com/ILZS6yuNQ3wAAAAC/yo-chris-farley.gif' />
<Text align='center'>
This is the beginning of a journey through the DeFi universe
<br />
with our good friends at Polygon
</Text>
</Stack>
<Questions />
</Box>
);
};

View File

@ -0,0 +1,52 @@
import type { NextPage } from 'next';
import * as React from 'react';
import { Box, Center, Icon, Spinner, Stack } from '@chakra-ui/react';
import { FaCommentDollar } from 'react-icons/fa';
import { BigNumber } from 'ethers';
import { useRouter } from 'next/router';
import Question from '../../components/Question';
import useQuestions from '../../hooks/useQuestions';
import Answers from '../../components/Answers';
const QuestionPage: NextPage = () => {
const [questionId, setQuestionId] = React.useState<BigNumber | undefined>();
const { questionQuery } = useQuestions({ questionId });
const router = useRouter();
React.useEffect(() => {
// If we refresh the URL `/question/[id]` in our browser,
// router.query.id may be undefined for a moment. Therefore,
// we wait for the useRouter hook before setting the questionId
if (router.isReady) {
setQuestionId(BigNumber.from(router.query.id));
}
}, [router.isReady, router.query.id]);
// TODO: uncomment to check how ethers parses binary data from contract
// console.log(JSON.stringify(questionQuery.data, null, 4));
return (
<Box p={3} pt={8} maxW='600px' minW='320px' m='0 auto'>
{questionQuery.isLoading && (
<Center p={8}>
<Spinner />
</Center>
)}
{questionQuery.isFetched && questionQuery?.data && (
<Stack spacing={2}>
<Box mb={5}>
<Question {...questionQuery.data} answerPage={true} />
</Box>
<Center pt='8px' height='20px'>
<Icon as={FaCommentDollar} alignSelf='center' />
</Center>
<Box p={8} maxW='600px' minW='320px' m='0 auto'>
{!!questionId && <Answers questionId={questionId} />}
</Box>
</Stack>
)}
</Box>
);
};
export default QuestionPage;

11
Hardhat/.gitignore vendored Normal file
View File

@ -0,0 +1,11 @@
node_modules
.env
coverage
coverage.json
typechain
typechain-types
#Hardhat files
cache
artifacts

13
Hardhat/README.md Normal file
View File

@ -0,0 +1,13 @@
# Sample Hardhat Project
This project demonstrates a basic Hardhat use case. It comes with a sample contract, a test for that contract, and a script that deploys that contract.
Try running some of the following tasks:
```shell
npx hardhat help
npx hardhat test
GAS_REPORT=true npx hardhat test
npx hardhat node
npx hardhat run scripts/deploy.ts
```

112
Hardhat/contracts/Forum.sol Normal file
View File

@ -0,0 +1,112 @@
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract Forum {
struct Question {
uint questionId;
string message;
address creatorAddress;
uint timestamp;
}
struct Answer {
uint answerId;
uint questionId;
address creatorAddress;
string message;
uint timestamp;
uint upvotes;
}
Question[] public questions;
Answer[] public answers;
mapping (uint => uint[]) public answersPerQuestion;
mapping (uint => mapping(address => bool)) public upvoters;
mapping (address => uint) public usersUpvoteCount;
event QuestionAdded(Question question);
event AnswerAdded(Answer answer);
event AnswerUpvoted(Answer answer);
IERC20 public immutable Goflow;
uint constant decimals = 18;
uint amountToPay = 1 * 10**decimals;
uint amountToParticipate = 10 * 10**decimals;
constructor(address _tokenAddress) {
Goflow = IERC20(_tokenAddress);
}
modifier answerExists(uint _answerId) {
require(answers.length > _answerId, 'Answer does not exist!');
_;
}
function postQuestion(string calldata _message) external {
uint questionCounter = questions.length;
Question memory question = Question({
questionId: questionCounter,
message: _message,
creatorAddress: msg.sender,
timestamp: block.timestamp
});
questions.push(question);
emit QuestionAdded(question);
}
function postAnswer(uint _questionId, string calldata _message) external {
uint answerCounter = answers.length;
Answer memory answer = Answer({
answerId: answerCounter,
questionId: _questionId,
creatorAddress: msg.sender,
message: _message,
timestamp: block.timestamp,
upvotes: 0
});
// we use an answer array and an answersPerQuestion mapping to store answerIds for each question.
// This makes it easier for us to fetch the answers based on a questionId
answers.push(answer);
answersPerQuestion[_questionId].push(answerCounter);
emit AnswerAdded(answer);
}
function upvoteAnswer(uint _answerId) external answerExists(_answerId) {
Answer storage currentAnswer = answers[_answerId];
require(upvoters[_answerId][msg.sender] != true, 'User already upvoted this answer!');
require(answers[_answerId].creatorAddress != msg.sender, 'Cannot upvote own answer!');
require(Goflow.balanceOf(msg.sender) >= amountToPay, 'User has insufficient balance!');
require(Goflow.allowance(msg.sender, address(this)) >= amountToPay, 'Account did not approve token succesfully!');
bool sent;
if (Goflow.balanceOf(currentAnswer.creatorAddress) >= amountToParticipate) {
sent = Goflow.transferFrom(msg.sender, currentAnswer.creatorAddress, amountToPay);
} else {
sent = Goflow.transferFrom(msg.sender, address(this), amountToPay);
}
require(sent, "Token transfer failed!");
currentAnswer.upvotes++;
usersUpvoteCount[msg.sender]++;
upvoters[_answerId][msg.sender] = true;
emit AnswerUpvoted(currentAnswer);
}
function getQuestions() external view returns (Question[] memory) {
return questions;
}
function getAnswersPerQuestion(uint _questionId) public view returns (uint[] memory) {
return answersPerQuestion[_questionId];
}
function getUpvotes(uint _answerId) public view answerExists(_answerId) returns (uint) {
return answers[_answerId].upvotes;
}
}

View File

@ -0,0 +1,58 @@
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract Goflow is IERC20 {
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
string public name = "Goflow";
string public symbol = "GOFLOW";
uint256 public decimals = 18;
function transfer(address recipient, uint256 amount)
external
returns (bool)
{
balanceOf[msg.sender] -= amount;
balanceOf[recipient] += amount;
emit Transfer(msg.sender, recipient, amount);
return true;
}
function approve(address spender, uint256 amount) external returns (bool) {
require(msg.sender != spender, "Cannot approve self");
require(
balanceOf[msg.sender] >= amount,
"insufficient balance for approval!"
);
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool) {
allowance[sender][msg.sender] -= amount;
balanceOf[sender] -= amount;
balanceOf[recipient] += amount;
emit Transfer(sender, recipient, amount);
return true;
}
function mint(uint256 amount) external {
balanceOf[msg.sender] += amount;
totalSupply += amount;
emit Transfer(address(0), msg.sender, amount);
}
function burn(uint256 amount) external {
balanceOf[msg.sender] -= amount;
totalSupply -= amount;
emit Transfer(msg.sender, address(0), amount);
}
}

18
Hardhat/hardhat.config.ts Normal file
View File

@ -0,0 +1,18 @@
import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";
import 'dotenv/config';
const config: HardhatUserConfig = {
solidity: '0.8.9',
networks: {
hardhat: {
chainId: 1337,
},
matic: {
url: '<YOUR-QUICKNODE-POLYGON-URL>',
accounts: process.env.PRIVATE_KEY ? [process.env.PRIVATE_KEY] : [],
},
},
};
export default config;

18659
Hardhat/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

22
Hardhat/package.json Normal file
View File

@ -0,0 +1,22 @@
{
"name": "hardhat",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@openzeppelin/contracts": "^4.7.0",
"dotenv": "^16.0.1",
"hardhat": "^2.10.1"
},
"devDependencies": {
"@nomicfoundation/hardhat-toolbox": "^1.0.2",
"ts-node": "^10.9.1",
"typescript": "^4.7.4"
}
}

View File

@ -0,0 +1,32 @@
import { Contract, ContractFactory } from 'ethers';
import { ethers } from 'hardhat';
async function main() {
// deploy the contracts
const Goflow: ContractFactory = await ethers.getContractFactory('Goflow');
const goflow: Contract = await Goflow.deploy();
const Forum: ContractFactory = await ethers.getContractFactory('Forum');
// pass the GOFLOW token address to the Forum contract's constructor!
const forum: Contract = await Forum.deploy(goflow.address);
await forum.deployed();
console.log('goflow deployed to: ', goflow.address);
console.log('forum deployed to: ', forum.address);
// Let's populate our app with some questions and answers.
// We are posting with our wallet address by default
const qTx = await forum.postQuestion('Are you my fren? 🤗');
await qTx.wait();
// What a nice answer 🤝 🤗
const answerTx3 = await forum.postAnswer(0, 'Yes, I am ur fren! 👊');
await answerTx3.wait();
}
// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

View File

@ -0,0 +1,63 @@
import { Contract, ContractFactory } from 'ethers';
import { ethers } from 'hardhat';
import { makeBig } from '../../Front-end/lib/number-utils';
async function main() {
// let's get a another SignerWithAddress to upvote a question
const [owner, user1] = await ethers.getSigners();
// these addresses should match Account #0 & #1 from our local node
console.log('With each deployment to the localhost...');
console.log('...these addresses will stay the same');
console.log('owner address: ', owner.address);
console.log('user1 address: ', user1.address, '\n');
// deploy the contracts
const Goflow: ContractFactory = await ethers.getContractFactory('Goflow');
const goflow: Contract = await Goflow.deploy();
console.log('...these addresses may change');
console.log('goflow deployed to: ', goflow.address);
const Forum: ContractFactory = await ethers.getContractFactory('Forum');
// pass the GOFLOW token address to the Forum contract's constructor!
const forum: Contract = await Forum.deploy(goflow.address);
await forum.deployed();
console.log('forum deployed to: ', forum.address);
// Let's populate our app with some questions and answers.
// We are posting as `owner` by default
const qTx = await forum.postQuestion('Are you my fren? 🤗');
await qTx.wait();
// Let's post an answer to the question
// Our first question has the id 0 which we pass as the first argument
const answerTx = await forum.postAnswer(0, '1st answer');
await answerTx.wait();
const answerTx2 = await forum.postAnswer(0, '2nd answer');
await answerTx2.wait();
// What a nice answer 🤝 🤗
const answerTx3 = await forum.postAnswer(0, 'Yes, I am ur fren! 👊');
await answerTx3.wait();
// Connect to `user1` in order to mint, approve, and upvote an answer
// We need to parse the token amount into a BigNumber of the correct unit
const mintTx = await goflow.connect(user1).mint(makeBig('1000'));
await mintTx.wait();
// "approve before someone else can move" our tokens with the transferFrom method
const approve = await goflow.connect(user1).approve(forum.address, makeBig('1000'));
await approve.wait();
// upvote answer with id 2, 'Yes, I am ur fren! 👊'
const upvote1 = await forum.connect(user1).upvoteAnswer(2);
await upvote1.wait();
}
// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

178
Hardhat/test/Forum.test.ts Normal file
View File

@ -0,0 +1,178 @@
import { expect } from 'chai';
import { Contract } from 'ethers';
import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers';
import { ethers } from 'hardhat';
import { makeBig } from '../../Front-end/lib/number-utils';
describe('Forum', () => {
let goflow: Contract;
let forum: Contract;
let owner: SignerWithAddress, user1: SignerWithAddress, user2: SignerWithAddress;
// We want to post the same question and answers for each test
// so we create a function to avoid duplicating code
const postQuestionsAndAnswers = async (user1: SignerWithAddress, user2: SignerWithAddress) => {
const tx = await forum.connect(user1).postQuestion('are you my fren?');
await tx.wait();
const tx2 = await forum.connect(user2).postQuestion('suh?');
await tx2.wait();
const tx3 = await forum.connect(user1).postAnswer(0, 'yes, I am');
await tx3.wait();
const tx4 = await forum.connect(user2).postAnswer(1, 'dude!');
await tx4.wait();
};
beforeEach(async () => {
// the getSigners() method allows us a to create mock users
const [_owner, _user1, _user2] = await ethers.getSigners();
owner = _owner;
user1 = _user1;
user2 = _user2;
});
beforeEach(async () => {
// Deploy the Goflow contract
const Goflow = await ethers.getContractFactory('Goflow');
goflow = await Goflow.deploy();
await goflow.deployed();
// Deploy the Forum contract
const Forum = await ethers.getContractFactory('Forum');
// We make sure to pass the address of our ERC20 contract
// to the Forum contract's constructor!
forum = await Forum.deploy(goflow.address);
await forum.deployed();
});
describe('Deployment', () => {
it('should deploy the Forum contract and import Goflow Token', async () => {
console.log('Forum address: ', forum.address);
console.log('imported Goflow address: ', await forum.Goflow());
// Check that the Goflow contract has been imported
// into the Forum contract correctly
expect(await forum.Goflow()).to.equal(goflow.address);
});
});
describe('Posting questions and answers', () => {
it('should be possible to post a question', async () => {
// Remember, we use the `connect` method to interact with
// our smart contracts as different mock users
const tx = await forum.connect(user1).postQuestion('are you my fren?');
await tx.wait();
const tx2 = await forum.connect(user2).postQuestion('suh?');
await tx2.wait();
// console.log('nquestion 0 ', await forum.questions(0));
// console.log('\nquestion 1 ', await forum.questions(1));
expect((await forum.questions(0)).message).to.equal('are you my fren?');
expect((await forum.questions(1)).message).to.equal('suh?');
});
it('should be possible to post a question and answer it', async () => {
// Using the utility function we created above
await postQuestionsAndAnswers(user1, user2);
expect((await forum.answers(0)).message).to.equal('yes, I am');
expect((await forum.answers(1)).message).to.equal('dude!');
expect((await forum.answers(0)).questionId).to.equal(0);
expect((await forum.answers(1)).questionId).to.equal(1);
expect((await forum.answers(0)).creatorAddress).to.equal(user1.address);
expect((await forum.answers(1)).creatorAddress).to.equal(user2.address);
});
});
describe('Upvoting answers', () => {
it('should upvote an answer and pay the answer creator', async () => {
// mint some tokens to you -- a.k.a. the OWNER.
// We are connected to owner by default, but let's explicityly connect
// so that it's easier to read the tests
const mintTx = await goflow.connect(owner).mint(makeBig(10));
await mintTx.wait();
// mint user1 at least 10 tokens so that they meet requirement to receive tips
const mintTx2 = await goflow.connect(user1).mint(makeBig(10));
await mintTx2.wait();
const mintTx3 = await goflow.connect(user2).mint(makeBig(10));
await mintTx3.wait();
// Remember, we gotta "approve before we move" with transferFrom
const ownerApprove = await goflow.connect(owner).approve(forum.address, makeBig(10));
await ownerApprove.wait();
const user2Approve = await goflow.connect(user2).approve(forum.address, makeBig(10));
await user2Approve.wait();
await postQuestionsAndAnswers(user1, user2);
// Our upvoteAnswer function uses the token transfeFrom method to tip
const upvoteTx = await forum.connect(owner).upvoteAnswer(0);
await upvoteTx.wait();
const upvoteTx2 = await forum.connect(user2).upvoteAnswer(0);
await upvoteTx2.wait();
expect(await forum.getUpvotes(0)).to.equal(2);
expect(await forum.getUpvotes(1)).to.equal(0);
expect(await goflow.balanceOf(user1.address)).to.equal(makeBig(12));
});
it('should upvote an answer but pay the forum contract', async () => {
const mintTx = await goflow.connect(owner).mint(makeBig(10));
await mintTx.wait();
const mintTx2 = await goflow.connect(user2).mint(makeBig(10));
await mintTx2.wait();
// "approve before we move"
const tokenApprove = await goflow.connect(owner).approve(forum.address, makeBig(10));
await tokenApprove.wait();
await postQuestionsAndAnswers(user1, user2);
const upvoteTx = await forum.connect(owner).upvoteAnswer(0);
await upvoteTx.wait();
const upvoteTx2 = await forum.connect(owner).upvoteAnswer(1);
await upvoteTx2.wait();
// console.log('goflow balance of contract at start', await goflow.balanceOf(forum.address));
// each answer should have one upvote 👍
expect(await forum.getUpvotes(0)).to.equal(1);
expect(await forum.getUpvotes(1)).to.equal(1);
// user2 has a balance of >= 10, and receives the tip! 👍
expect(await goflow.balanceOf(user2.address)).to.equal(makeBig(11));
// user1 has no tokens, so receives no tip...👎
expect(await goflow.balanceOf(user1.address)).to.equal(makeBig(0));
// ...but the contract receives the tip instead 📈
expect(await goflow.balanceOf(forum.address)).to.equal(makeBig(1));
});
it('should not be possible to upvote an answer twice', async () => {
const mintTx = await goflow.connect(owner).mint(makeBig(10));
await mintTx.wait();
const tokenApprove = await goflow.connect(owner).approve(forum.address, makeBig(10));
await tokenApprove.wait();
await postQuestionsAndAnswers(user1, user2);
// owner upvotes answer 0 👍
const upvoteTx = await forum.connect(owner).upvoteAnswer(0);
await upvoteTx.wait();
// owner upvotes answer 1 👍
const upvoteTx2 = await forum.connect(owner).upvoteAnswer(1);
await upvoteTx2.wait();
// owner tries to upvote answer 0 again 👎
// NOTE: for expecting a reverted message, we need to put await first!
await expect(forum.connect(owner).upvoteAnswer(0)).to.be.revertedWith('User already upvoted this answer!');
// answer 0 should only have one upvote ✅
expect(await forum.getUpvotes(0)).to.equal(1);
// owner should have upvoted other answers two times ✅
expect(await forum.usersUpvoteCount(owner.address)).to.equal(2);
});
});
});

View File

@ -0,0 +1,84 @@
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers";
import { expect } from "chai";
import { Contract } from "ethers";
import { ethers } from "hardhat";
describe("Goflow", function () {
let goflow: Contract, owner: SignerWithAddress, otherAccount:SignerWithAddress;
const deployContract = async () => {
// Contracts are deployed using the first signer/account by default
// but we can create multiple user accounts for testing
const [_owner, _otherAccount] = await ethers.getSigners();
// Make sure the string argument passed to getContractFactory matches
// the exact name of your token contract!
const Goflow = await ethers.getContractFactory('Goflow');
goflow = await Goflow.deploy();
owner = _owner;
otherAccount = _otherAccount;
}
const mint = async (user: SignerWithAddress, amount: number) => {
// We mock different users with the `connect` method
const tx = await goflow.connect(user).mint(amount);
await tx.wait();
}
beforeEach(async () => {
await deployContract();
})
describe("Deployment", () => {
it("Should deploy and return correct symbol", async () => {
expect(await goflow.symbol()).to.equal("GOFLOW");
});
});
describe("Minting", () => {
it("Should mint tokens to user", async () => {
await mint(owner, 100);
expect(await goflow.balanceOf(owner.address)).to.equal(100);
});
});
describe("Transfer", () => {
it("Should transfer tokens to another account", async () => {
await mint(owner, 100); // mint 100 tokens to owner
await goflow.transfer(otherAccount.address, 100);
expect(await goflow.balanceOf(owner.address)).to.equal(0);
expect(await goflow.balanceOf(otherAccount.address)).to.equal(100);
});
});
describe("TransferFrom", () => {
it("Should approve a spender to be able to transfer owner's tokens", async () => {
await mint(owner, 100); // owner should start with 100 tokens
expect(await goflow.balanceOf(owner.address)).to.equal(100);
// first we gotta "approve before we can move"
// so the "spender" can access and transfer the owner's tokens!
const approve = await goflow.approve(otherAccount.address, 100);
await approve.wait();
// use the connect method to connect to the otherAccount
const transferFrom = await goflow.connect(otherAccount).transferFrom(owner.address, otherAccount.address, 100);
await transferFrom.wait();
// the spender should now have transferred the 100 tokens to themselves
expect(await goflow.balanceOf(owner.address)).to.equal(0);
expect(await goflow.balanceOf(otherAccount.address)).to.equal(100);
});
it("Should not allow a spender to transfer more tokens than they have", async () => {
await mint(owner, 100); // owner should start with 100 tokens
expect(await goflow.balanceOf(owner.address)).to.equal(100);
// the approve method should throw an error
// if the user tries to approve more tokens than they have
// NOTE: move `await` to the beginning of the expect statement
// NOTE: the error message comes from our approve method's `require` statement
await expect(goflow.approve(otherAccount.address, 200)).to.be.revertedWith('insufficient balance for approval!');
});
});
});

10
Hardhat/tsconfig.json Normal file
View File

@ -0,0 +1,10 @@
{
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}