From 98767f227c53a5c34497259635bc25d5455d0c24 Mon Sep 17 00:00:00 2001 From: Cherik Date: Thu, 5 May 2022 11:23:58 +0430 Subject: [PATCH 001/257] updte onchange functions add alert --- src/components/views/create/CreateProject.tsx | 48 ++++++++++++++----- 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/src/components/views/create/CreateProject.tsx b/src/components/views/create/CreateProject.tsx index 0daa132e6e..2e8882771f 100644 --- a/src/components/views/create/CreateProject.tsx +++ b/src/components/views/create/CreateProject.tsx @@ -97,6 +97,7 @@ const CreateProject = (props: { project?: IProjectEdition }) => { [ECreateErrFields.DESCRIPTION]: '', [ECreateErrFields.WALLET_ADDRESS]: '', }); + const [formChange, setFormChange] = useState(false); const { state: { user }, @@ -158,6 +159,17 @@ const CreateProject = (props: { project?: IProjectEdition }) => { ); }, []); + useEffect(() => { + const onberforeunload = function (event: any) { + event.returnValue = 'Write something clever here..'; + }; + if (formChange) + window.addEventListener('beforeunload', onberforeunload); + return () => { + window.removeEventListener('beforeunload', onberforeunload); + }; + }, [formChange]); + const handleInputChange = (value: string, id: string) => { if (id === ECreateErrFields.NAME) { setName(value); @@ -310,42 +322,54 @@ const CreateProject = (props: { project?: IProjectEdition }) => {
- handleInputChange(e, ECreateErrFields.NAME) - } + setValue={e => { + setFormChange(true); + handleInputChange(e, ECreateErrFields.NAME); + }} error={errors[ECreateErrFields.NAME]} /> + setValue={e => { + setFormChange(true); handleInputChange( e, ECreateErrFields.DESCRIPTION, - ) - } + ); + }} error={errors[ECreateErrFields.DESCRIPTION]} /> { + setFormChange(true); + setCategories(category); + }} /> { + setFormChange(true); + setImpactLocation(location); + }} /> { + setFormChange(true); + setImage(img); + }} setIsLoading={setIsLoading} /> + setValue={e => { + setFormChange(true); handleInputChange( e, ECreateErrFields.WALLET_ADDRESS, - ) - } + ); + }} error={errors[ECreateErrFields.WALLET_ADDRESS]} /> From 4fcf710fe35d991231904a2389c7a9eec6dd3f98 Mon Sep 17 00:00:00 2001 From: Mateo Daza Date: Mon, 9 May 2022 14:45:13 -0500 Subject: [PATCH 002/257] hotfix upgrades ethers version --- package.json | 2 +- yarn.lock | 99 ++++++++++++++++++++++++++++++++++++---------------- 2 files changed, 69 insertions(+), 32 deletions(-) diff --git a/package.json b/package.json index a4b12afd78..5473991886 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,7 @@ "axios": "^0.25.0", "bignumber.js": "^9.0.1", "deepmerge": "^4.2.2", - "ethers": "^5.5.3", + "ethers": "^5.6.5", "framer-motion": "^6.2.8", "graphql": "^16.0.1", "human-standard-token-abi": "^2.0.0", diff --git a/yarn.lock b/yarn.lock index 8cf886885d..4404f7d1a0 100644 --- a/yarn.lock +++ b/yarn.lock @@ -324,10 +324,10 @@ "@ethersproject/properties" "^5.0.3" "@ethersproject/strings" "^5.0.4" -"@ethersproject/abi@5.6.0", "@ethersproject/abi@^5.0.12", "@ethersproject/abi@^5.6.0": - version "5.6.0" - resolved "https://registry.yarnpkg.com/@ethersproject/abi/-/abi-5.6.0.tgz#ea07cbc1eec2374d32485679c12408005895e9f3" - integrity sha512-AhVByTwdXCc2YQ20v300w6KVHle9g2OFc28ZAFCPnJyEpkv1xKXjZcSTgWOlv1i+0dqlgF8RCF2Rn2KC1t+1Vg== +"@ethersproject/abi@5.6.1": + version "5.6.1" + resolved "https://registry.yarnpkg.com/@ethersproject/abi/-/abi-5.6.1.tgz#f7de888edeb56b0a657b672bdd1b3a1135cd14f7" + integrity sha512-0cqssYh6FXjlwKWBmLm3+zH2BNARoS5u/hxbz+LpQmcDB3w0W553h2btWui1/uZp2GBM/SI3KniTuMcYyHpA5w== dependencies: "@ethersproject/address" "^5.6.0" "@ethersproject/bignumber" "^5.6.0" @@ -339,10 +339,10 @@ "@ethersproject/properties" "^5.6.0" "@ethersproject/strings" "^5.6.0" -"@ethersproject/abi@5.6.1": - version "5.6.1" - resolved "https://registry.yarnpkg.com/@ethersproject/abi/-/abi-5.6.1.tgz#f7de888edeb56b0a657b672bdd1b3a1135cd14f7" - integrity sha512-0cqssYh6FXjlwKWBmLm3+zH2BNARoS5u/hxbz+LpQmcDB3w0W553h2btWui1/uZp2GBM/SI3KniTuMcYyHpA5w== +"@ethersproject/abi@^5.0.12", "@ethersproject/abi@^5.6.0": + version "5.6.0" + resolved "https://registry.yarnpkg.com/@ethersproject/abi/-/abi-5.6.0.tgz#ea07cbc1eec2374d32485679c12408005895e9f3" + integrity sha512-AhVByTwdXCc2YQ20v300w6KVHle9g2OFc28ZAFCPnJyEpkv1xKXjZcSTgWOlv1i+0dqlgF8RCF2Rn2KC1t+1Vg== dependencies: "@ethersproject/address" "^5.6.0" "@ethersproject/bignumber" "^5.6.0" @@ -507,13 +507,6 @@ resolved "https://registry.yarnpkg.com/@ethersproject/logger/-/logger-5.6.0.tgz#d7db1bfcc22fd2e4ab574cba0bb6ad779a9a3e7a" integrity sha512-BiBWllUROH9w+P21RzoxJKzqoqpkyM1pRnEKG69bulE9TSQD8SAIvTQqIMZmmCO8pUNkgLP1wndX1gKghSpBmg== -"@ethersproject/networks@5.6.1", "@ethersproject/networks@^5.6.0": - version "5.6.1" - resolved "https://registry.yarnpkg.com/@ethersproject/networks/-/networks-5.6.1.tgz#7a21ed1f83e86121737b16841961ec99ccf5c9c7" - integrity sha512-b2rrupf3kCTcc3jr9xOWBuHylSFtbpJf79Ga7QR98ienU2UqGimPGEsYMgbI29KHJfA5Us89XwGVmxrlxmSrMg== - dependencies: - "@ethersproject/logger" "^5.6.0" - "@ethersproject/networks@5.6.2": version "5.6.2" resolved "https://registry.yarnpkg.com/@ethersproject/networks/-/networks-5.6.2.tgz#2bacda62102c0b1fcee408315f2bed4f6fbdf336" @@ -521,6 +514,13 @@ dependencies: "@ethersproject/logger" "^5.6.0" +"@ethersproject/networks@^5.6.0": + version "5.6.1" + resolved "https://registry.yarnpkg.com/@ethersproject/networks/-/networks-5.6.1.tgz#7a21ed1f83e86121737b16841961ec99ccf5c9c7" + integrity sha512-b2rrupf3kCTcc3jr9xOWBuHylSFtbpJf79Ga7QR98ienU2UqGimPGEsYMgbI29KHJfA5Us89XwGVmxrlxmSrMg== + dependencies: + "@ethersproject/logger" "^5.6.0" + "@ethersproject/pbkdf2@5.6.0", "@ethersproject/pbkdf2@^5.6.0": version "5.6.0" resolved "https://registry.yarnpkg.com/@ethersproject/pbkdf2/-/pbkdf2-5.6.0.tgz#04fcc2d7c6bff88393f5b4237d906a192426685a" @@ -536,10 +536,10 @@ dependencies: "@ethersproject/logger" "^5.6.0" -"@ethersproject/providers@5.6.2", "@ethersproject/providers@^5.5.0": - version "5.6.2" - resolved "https://registry.yarnpkg.com/@ethersproject/providers/-/providers-5.6.2.tgz#b9807b1c8c6f59fa2ee4b3cf6519724d07a9f422" - integrity sha512-6/EaFW/hNWz+224FXwl8+HdMRzVHt8DpPmu5MZaIQqx/K/ELnC9eY236SMV7mleCM3NnEArFwcAAxH5kUUgaRg== +"@ethersproject/providers@5.6.4": + version "5.6.4" + resolved "https://registry.yarnpkg.com/@ethersproject/providers/-/providers-5.6.4.tgz#1a49c211b57b0b2703c320819abbbfa35c83dff7" + integrity sha512-WAdknnaZ52hpHV3qPiJmKx401BLpup47h36Axxgre9zT+doa/4GC/Ne48ICPxTm0BqndpToHjpLP1ZnaxyE+vw== dependencies: "@ethersproject/abstract-provider" "^5.6.0" "@ethersproject/abstract-signer" "^5.6.0" @@ -561,10 +561,35 @@ bech32 "1.1.4" ws "7.4.6" -"@ethersproject/providers@5.6.4": - version "5.6.4" - resolved "https://registry.yarnpkg.com/@ethersproject/providers/-/providers-5.6.4.tgz#1a49c211b57b0b2703c320819abbbfa35c83dff7" - integrity sha512-WAdknnaZ52hpHV3qPiJmKx401BLpup47h36Axxgre9zT+doa/4GC/Ne48ICPxTm0BqndpToHjpLP1ZnaxyE+vw== +"@ethersproject/providers@5.6.5": + version "5.6.5" + resolved "https://registry.yarnpkg.com/@ethersproject/providers/-/providers-5.6.5.tgz#aefecf78459817a323452e05a16d56afcf807e27" + integrity sha512-TRS+c2Ud+cMpWodmGAc9xbnYRPWzRNYt2zkCSnj58nJoamBQ6x4cUbBeo0lTC3y+6RDVIBeJv18OqsDbSktLVg== + dependencies: + "@ethersproject/abstract-provider" "^5.6.0" + "@ethersproject/abstract-signer" "^5.6.0" + "@ethersproject/address" "^5.6.0" + "@ethersproject/basex" "^5.6.0" + "@ethersproject/bignumber" "^5.6.0" + "@ethersproject/bytes" "^5.6.0" + "@ethersproject/constants" "^5.6.0" + "@ethersproject/hash" "^5.6.0" + "@ethersproject/logger" "^5.6.0" + "@ethersproject/networks" "^5.6.0" + "@ethersproject/properties" "^5.6.0" + "@ethersproject/random" "^5.6.0" + "@ethersproject/rlp" "^5.6.0" + "@ethersproject/sha2" "^5.6.0" + "@ethersproject/strings" "^5.6.0" + "@ethersproject/transactions" "^5.6.0" + "@ethersproject/web" "^5.6.0" + bech32 "1.1.4" + ws "7.4.6" + +"@ethersproject/providers@^5.5.0": + version "5.6.2" + resolved "https://registry.yarnpkg.com/@ethersproject/providers/-/providers-5.6.2.tgz#b9807b1c8c6f59fa2ee4b3cf6519724d07a9f422" + integrity sha512-6/EaFW/hNWz+224FXwl8+HdMRzVHt8DpPmu5MZaIQqx/K/ELnC9eY236SMV7mleCM3NnEArFwcAAxH5kUUgaRg== dependencies: "@ethersproject/abstract-provider" "^5.6.0" "@ethersproject/abstract-signer" "^5.6.0" @@ -623,6 +648,18 @@ elliptic "6.5.4" hash.js "1.1.7" +"@ethersproject/signing-key@5.6.1": + version "5.6.1" + resolved "https://registry.yarnpkg.com/@ethersproject/signing-key/-/signing-key-5.6.1.tgz#31b0a531520616254eb0465b9443e49515c4d457" + integrity sha512-XvqQ20DH0D+bS3qlrrgh+axRMth5kD1xuvqUQUTeezxUTXBOeR6hWz2/C6FBEu39FRytyybIWrYf7YLSAKr1LQ== + dependencies: + "@ethersproject/bytes" "^5.6.0" + "@ethersproject/logger" "^5.6.0" + "@ethersproject/properties" "^5.6.0" + bn.js "^4.11.9" + elliptic "6.5.4" + hash.js "1.1.7" + "@ethersproject/solidity@5.6.0", "@ethersproject/solidity@^5.0.9": version "5.6.0" resolved "https://registry.yarnpkg.com/@ethersproject/solidity/-/solidity-5.6.0.tgz#64657362a596bf7f5630bdc921c07dd78df06dc3" @@ -3626,12 +3663,12 @@ ethers@^5.4.7: "@ethersproject/web" "5.6.0" "@ethersproject/wordlists" "5.6.0" -ethers@^5.5.3: - version "5.6.2" - resolved "https://registry.yarnpkg.com/ethers/-/ethers-5.6.2.tgz#e75bac7f038c5e0fdde667dba62fc223924143a2" - integrity sha512-EzGCbns24/Yluu7+ToWnMca3SXJ1Jk1BvWB7CCmVNxyOeM4LLvw2OLuIHhlkhQk1dtOcj9UMsdkxUh8RiG1dxQ== +ethers@^5.6.5: + version "5.6.5" + resolved "https://registry.yarnpkg.com/ethers/-/ethers-5.6.5.tgz#3185ac7815dc640993408adf6f133ffabfbcbb63" + integrity sha512-9CTmplO9bv0s/aPw3HB3txGzKz3tUSI2EfO4dJo0W2WvaEq1ArgsEX6obV+bj5X3yY+Zgb1kAux8TDtJKe1FaA== dependencies: - "@ethersproject/abi" "5.6.0" + "@ethersproject/abi" "5.6.1" "@ethersproject/abstract-provider" "5.6.0" "@ethersproject/abstract-signer" "5.6.0" "@ethersproject/address" "5.6.0" @@ -3646,14 +3683,14 @@ ethers@^5.5.3: "@ethersproject/json-wallets" "5.6.0" "@ethersproject/keccak256" "5.6.0" "@ethersproject/logger" "5.6.0" - "@ethersproject/networks" "5.6.1" + "@ethersproject/networks" "5.6.2" "@ethersproject/pbkdf2" "5.6.0" "@ethersproject/properties" "5.6.0" - "@ethersproject/providers" "5.6.2" + "@ethersproject/providers" "5.6.5" "@ethersproject/random" "5.6.0" "@ethersproject/rlp" "5.6.0" "@ethersproject/sha2" "5.6.0" - "@ethersproject/signing-key" "5.6.0" + "@ethersproject/signing-key" "5.6.1" "@ethersproject/solidity" "5.6.0" "@ethersproject/strings" "5.6.0" "@ethersproject/transactions" "5.6.0" From 2e8472e0dcfae90d7b0eed76263cfa3d38f37a3d Mon Sep 17 00:00:00 2001 From: Ramin Date: Tue, 10 May 2022 12:20:24 +0430 Subject: [PATCH 003/257] Feat #655 implement failed modal for donation --- public/images/icons/donation.svg | 7 ++ src/components/modals/DonateModal.tsx | 1 + src/components/modals/FaliedDonation.tsx | 78 +++++++++++++++++++ .../views/donate/CryptoDonation.tsx | 6 ++ src/components/views/donate/helpers.tsx | 7 +- src/types/common.ts | 3 + 6 files changed, 100 insertions(+), 2 deletions(-) create mode 100644 public/images/icons/donation.svg create mode 100644 src/components/modals/FaliedDonation.tsx create mode 100644 src/types/common.ts diff --git a/public/images/icons/donation.svg b/public/images/icons/donation.svg new file mode 100644 index 0000000000..55b8a7831f --- /dev/null +++ b/public/images/icons/donation.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/components/modals/DonateModal.tsx b/src/components/modals/DonateModal.tsx index 539af32778..bd0cda466c 100644 --- a/src/components/modals/DonateModal.tsx +++ b/src/components/modals/DonateModal.tsx @@ -24,6 +24,7 @@ import { confirmDonation } from '@/components/views/donate/helpers'; export interface IDonateModalProps { setShowModal: (i: boolean) => void; + setShowFailedModal: (i: boolean) => void; project: IProject; token: IProjectAcceptedToken; amount: number; diff --git a/src/components/modals/FaliedDonation.tsx b/src/components/modals/FaliedDonation.tsx new file mode 100644 index 0000000000..49b7ed66e2 --- /dev/null +++ b/src/components/modals/FaliedDonation.tsx @@ -0,0 +1,78 @@ +import { FC } from 'react'; +import { + B, + brandColors, + ButtonText, + H5, + IconX, + semanticColors, +} from '@giveth/ui-design-system'; +import styled from 'styled-components'; +import { Modal } from '@/components/modals/Modal'; +import { mediaQueries } from '@/lib/constants/constants'; +import { FlexCenter } from '@/components/styled-components/Flex'; +import { IModalProps } from '@/types/common'; + +const FailedDonation: FC = ({ setShowModal }) => { + return ( + + } + > + + + + +
Sorry!
+ + Your transaction has failed. Please go back and try again. + + +
+
+ ); +}; + +const Button = styled(ButtonText)` + color: ${brandColors.deep[100]}; + margin: 44px 0; + cursor: pointer; +`; + +const Error = styled(FlexCenter)` + width: 125px; + height: 125px; + border-radius: 50%; + background: ${semanticColors.punch[300]}; + margin-top: 21px; + margin-bottom: 12px; +`; + +const Container = styled(FlexCenter)` + max-width: 500px; + padding: 0 20px; + text-align: center; + flex-direction: column; + + > h5 { + color: ${semanticColors.punch[500]}; + } + > :nth-child(3) { + color: ${brandColors.deep[700]}; + margin-top: 8px; + max-width: 280px; + } + + ${mediaQueries.mobileL} { + padding: 0 50px; + } + ${mediaQueries.tablet} { + padding: 0 108px; + } +`; + +export default FailedDonation; diff --git a/src/components/views/donate/CryptoDonation.tsx b/src/components/views/donate/CryptoDonation.tsx index 82d4339679..a522aeabcd 100644 --- a/src/components/views/donate/CryptoDonation.tsx +++ b/src/components/views/donate/CryptoDonation.tsx @@ -50,6 +50,7 @@ import useModal from '@/context/ModalProvider'; import { getERC20Info } from '@/lib/contracts'; import GIVBackToast from '@/components/views/donate/GIVBackToast'; import { DonateWrongNetwork } from '@/components/modals/DonateWrongNetwork'; +import FailedDonation from '@/components/modals/FaliedDonation'; const ethereumChain = config.PRIMARY_NETWORK; const xdaiChain = config.SECONDARY_NETWORK; @@ -109,6 +110,7 @@ const CryptoDonation = (props: { const [acceptedTokens, setAcceptedTokens] = useState(); const [acceptedChains, setAcceptedChains] = useState(); + const [showFailedModal, setShowFailedModal] = useState(false); const stopPolling = useRef(null); const tokenSymbol = selectedToken?.symbol; @@ -328,6 +330,7 @@ const CryptoDonation = (props: { )} + {showFailedModal && ( + + )} {networkId && diff --git a/src/components/views/donate/helpers.tsx b/src/components/views/donate/helpers.tsx index f5280c84f7..a60a670134 100644 --- a/src/components/views/donate/helpers.tsx +++ b/src/components/views/donate/helpers.tsx @@ -92,6 +92,7 @@ export const confirmDonation = async (props: IConfirmDonation) => { amount, token, setSuccessDonation, + setShowFailedModal, web3Context, setDonating, setDonationSaved, @@ -126,11 +127,13 @@ export const confirmDonation = async (props: IConfirmDonation) => { } catch (error: any) { setDonating(false); setDonationSaved(false); - captureException(error); const code = error.data?.code; if (code === ('INSUFFICIENT_FUNDS' || 'UNPREDICTABLE_GAS_LIMIT')) { showToastError('Insufficient Funds'); - } else showToastError(error); + } else { + setShowFailedModal(true); + showToastError(error); + } captureException(error, { tags: { section: 'confirmDonation', diff --git a/src/types/common.ts b/src/types/common.ts new file mode 100644 index 0000000000..53cd8d4e5d --- /dev/null +++ b/src/types/common.ts @@ -0,0 +1,3 @@ +export interface IModalProps { + setShowModal: (showModal: boolean) => void; +} From b35a5a28a47ffc99683ce549065b512d4fd7450d Mon Sep 17 00:00:00 2001 From: Cherik Date: Tue, 10 May 2022 12:28:34 +0430 Subject: [PATCH 004/257] install packages --- package.json | 2 ++ yarn.lock | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 5473991886..4bbcac45ee 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ "@ethersproject/units": "^5.5.0", "@giveth/ui-design-system": "^1.8.3", "@gnosis.pm/safe-apps-web3-react": "^1.3.0", + "@reduxjs/toolkit": "^1.8.1", "@sentry/nextjs": "^6.19.3", "@toruslabs/torus-embed": "^1.20.2", "@uniswap/v3-sdk": "^3.6.2-optimism-regenesis", @@ -51,6 +52,7 @@ "react-lottie": "^1.2.3", "react-places-autocomplete": "^7.3.0", "react-quill": "^2.0.0-beta.4", + "react-redux": "^8.0.1", "react-select": "^5.2.1", "react-share": "^4.4.0", "sharp": "^0.30.3", diff --git a/yarn.lock b/yarn.lock index 4404f7d1a0..5e64a5fc53 100644 --- a/yarn.lock +++ b/yarn.lock @@ -139,7 +139,7 @@ dependencies: regenerator-runtime "^0.13.4" -"@babel/runtime@^7.10.2", "@babel/runtime@^7.12.0", "@babel/runtime@^7.13.10", "@babel/runtime@^7.16.3", "@babel/runtime@^7.5.5", "@babel/runtime@^7.7.2", "@babel/runtime@^7.8.7": +"@babel/runtime@^7.10.2", "@babel/runtime@^7.12.0", "@babel/runtime@^7.12.1", "@babel/runtime@^7.13.10", "@babel/runtime@^7.16.3", "@babel/runtime@^7.5.5", "@babel/runtime@^7.7.2", "@babel/runtime@^7.8.7", "@babel/runtime@^7.9.2": version "7.17.9" resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.17.9.tgz#d19fbf802d01a8cb6cf053a64e472d42c434ba72" integrity sha512-lSiBBvodq29uShpWGNbgFdKYNiFDo5/HIYsaCEY9ff4sb10x9jizo2+pRrSyF4jKZCXqgzuqBOQKbUm90gQwJg== @@ -1074,6 +1074,16 @@ resolved "https://registry.yarnpkg.com/@polka/url/-/url-1.0.0-next.21.tgz#5de5a2385a35309427f6011992b544514d559aa1" integrity sha512-a5Sab1C4/icpTZVzZc5Ghpz88yQtGOyNqYXcZgOssB2uuAr+wF/MvN6bgtW32q7HHrvBki+BsZ0OuNv6EV3K9g== +"@reduxjs/toolkit@^1.8.1": + version "1.8.1" + resolved "https://registry.yarnpkg.com/@reduxjs/toolkit/-/toolkit-1.8.1.tgz#94ee1981b8cf9227cda40163a04704a9544c9a9f" + integrity sha512-Q6mzbTpO9nOYRnkwpDlFOAbQnd3g7zj7CtHAZWz5SzE5lcV97Tf8f3SzOO8BoPOMYBFgfZaqTUZqgGu+a0+Fng== + dependencies: + immer "^9.0.7" + redux "^4.1.2" + redux-thunk "^2.4.1" + reselect "^4.1.5" + "@rushstack/eslint-patch@1.0.8": version "1.0.8" resolved "https://registry.yarnpkg.com/@rushstack/eslint-patch/-/eslint-patch-1.0.8.tgz#be3e914e84eacf16dbebd311c0d0b44aa1174c64" @@ -1349,7 +1359,7 @@ resolved "https://registry.yarnpkg.com/@types/google.maps/-/google.maps-3.48.5.tgz#ab2ef4add490a108cdb5149d3df81dafb159528e" integrity sha512-sI3EOhGHvzbitC/iLOf2nQ+TijsXqbV2nQi9twpRWy0p6q6vbwRnIy7PQKjmpFQewjTVNa1MfY2BL76MU1lOWA== -"@types/hoist-non-react-statics@*": +"@types/hoist-non-react-statics@*", "@types/hoist-non-react-statics@^3.3.1": version "3.3.1" resolved "https://registry.yarnpkg.com/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.1.tgz#1124aafe5118cb591977aeb1ceaaed1070eb039f" integrity sha512-iMIqiko6ooLrTh1joXodJK5X9xeEALT1kM5G3ZLhD3hszxBdIEd5C75U834D9mLcINgD4OyZf5uQXjkuYydWvA== @@ -1529,6 +1539,11 @@ "@types/react" "*" csstype "^3.0.2" +"@types/use-sync-external-store@^0.0.3": + version "0.0.3" + resolved "https://registry.yarnpkg.com/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz#b6725d5f4af24ace33b36fafd295136e75509f43" + integrity sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA== + "@typescript-eslint/eslint-plugin@^5.3.1": version "5.18.0" resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.18.0.tgz#950df411cec65f90d75d6320a03b2c98f6c3af7d" @@ -4276,6 +4291,11 @@ immediate@~3.0.5: resolved "https://registry.yarnpkg.com/immediate/-/immediate-3.0.6.tgz#9db1dbd0faf8de6fbe0f5dd5e56bb606280de69b" integrity sha1-nbHb0Pr43m++D13V5Wu2BigN5ps= +immer@^9.0.7: + version "9.0.12" + resolved "https://registry.yarnpkg.com/immer/-/immer-9.0.12.tgz#2d33ddf3ee1d247deab9d707ca472c8c942a0f20" + integrity sha512-lk7UNmSbAukB5B6dh9fnh5D0bJTOFKxVg2cyJWTYrWRfhLrLMBquONcUs3aFq507hNoIZEDDh8lb8UtOizSMhA== + import-fresh@^3.0.0, import-fresh@^3.1.0, import-fresh@^3.2.1: version "3.3.0" resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.3.0.tgz#37162c25fcb9ebaa2e6e53d5b4d88ce17d9e0c2b" @@ -5704,6 +5724,11 @@ react-is@^16.13.1, react-is@^16.7.0: resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4" integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ== +react-is@^18.0.0: + version "18.1.0" + resolved "https://registry.yarnpkg.com/react-is/-/react-is-18.1.0.tgz#61aaed3096d30eacf2a2127118b5b41387d32a67" + integrity sha512-Fl7FuabXsJnV5Q1qIOQwx/sagGF18kogb4gpfcG4gjLBWO0WDiiz1ko/ExayuxE7InyQkBLkxRFG5oxY6Uu3Kg== + react-lottie@^1.2.3: version "1.2.3" resolved "https://registry.yarnpkg.com/react-lottie/-/react-lottie-1.2.3.tgz#8544b96939e088658072eea5e12d912cdaa3acc1" @@ -5729,6 +5754,18 @@ react-quill@^2.0.0-beta.4: lodash "^4.17.4" quill "^1.3.7" +react-redux@^8.0.1: + version "8.0.1" + resolved "https://registry.yarnpkg.com/react-redux/-/react-redux-8.0.1.tgz#2bc029f5ada9b443107914c373a2750f6bc0f40c" + integrity sha512-LMZMsPY4DYdZfLJgd7i79n5Kps5N9XVLCJJeWAaPYTV+Eah2zTuBjTxKtNEbjiyitbq80/eIkm55CYSLqAub3w== + dependencies: + "@babel/runtime" "^7.12.1" + "@types/hoist-non-react-statics" "^3.3.1" + "@types/use-sync-external-store" "^0.0.3" + hoist-non-react-statics "^3.3.2" + react-is "^18.0.0" + use-sync-external-store "^1.0.0" + react-refresh@0.8.3: version "0.8.3" resolved "https://registry.yarnpkg.com/react-refresh/-/react-refresh-0.8.3.tgz#721d4657672d400c5e3c75d063c4a85fb2d5d68f" @@ -5826,6 +5863,18 @@ recompose@^0.26.0: hoist-non-react-statics "^2.3.1" symbol-observable "^1.0.4" +redux-thunk@^2.4.1: + version "2.4.1" + resolved "https://registry.yarnpkg.com/redux-thunk/-/redux-thunk-2.4.1.tgz#0dd8042cf47868f4b29699941de03c9301a75714" + integrity sha512-OOYGNY5Jy2TWvTL1KgAlVy6dcx3siPJ1wTq741EPyUKfn6W6nChdICjZwCd0p8AZBs5kWpZlbkXW2nE/zjUa+Q== + +redux@^4.1.2: + version "4.2.0" + resolved "https://registry.yarnpkg.com/redux/-/redux-4.2.0.tgz#46f10d6e29b6666df758780437651eeb2b969f13" + integrity sha512-oSBmcKKIuIR4ME29/AeNUnl5L+hvBq7OaJWzaptTQJAntaPvxIJqfnjbaEiCzzaIz+XmVILfqAM3Ob0aXLPfjA== + dependencies: + "@babel/runtime" "^7.9.2" + regenerator-runtime@0.13.4: version "0.13.4" resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.13.4.tgz#e96bf612a3362d12bb69f7e8f74ffeab25c7ac91" @@ -5864,6 +5913,11 @@ require-main-filename@^2.0.0: resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-2.0.0.tgz#d0b329ecc7cc0f61649f62215be69af54aa8989b" integrity sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg== +reselect@^4.1.5: + version "4.1.5" + resolved "https://registry.yarnpkg.com/reselect/-/reselect-4.1.5.tgz#852c361247198da6756d07d9296c2b51eddb79f6" + integrity sha512-uVdlz8J7OO+ASpBYoz1Zypgx0KasCY20H+N8JD13oUMtPvSHQuscrHop4KbXrbsBcdB9Ds7lVK7eRkBIfO43vQ== + resolve-from@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-4.0.0.tgz#4abcd852ad32dd7baabfe9b40e00a36db5f392e6" @@ -6643,6 +6697,11 @@ use-subscription@1.5.1: dependencies: object-assign "^4.1.1" +use-sync-external-store@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/use-sync-external-store/-/use-sync-external-store-1.1.0.tgz#3343c3fe7f7e404db70f8c687adf5c1652d34e82" + integrity sha512-SEnieB2FPKEVne66NpXPd1Np4R1lTNKfjuy3XdIoPQKYBAFdzbzSZlSn1KJZUiihQLQC5Znot4SBz1EOTBwQAQ== + utf-8-validate@^5.0.2: version "5.0.9" resolved "https://registry.yarnpkg.com/utf-8-validate/-/utf-8-validate-5.0.9.tgz#ba16a822fbeedff1a58918f2a6a6b36387493ea3" From c114b264533eb89057d015787b2a433a0cd7b031 Mon Sep 17 00:00:00 2001 From: Cherik Date: Tue, 10 May 2022 15:29:56 +0430 Subject: [PATCH 005/257] temp --- pages/_app.tsx | 21 ++++--- pages/test.tsx | 27 ++++++++ src/stores/store.ts | 13 ++++ src/stores/subgraph.store.ts | 115 +++++++++++++++++++++++++++++++++++ 4 files changed, 167 insertions(+), 9 deletions(-) create mode 100644 src/stores/store.ts create mode 100644 src/stores/subgraph.store.ts diff --git a/pages/_app.tsx b/pages/_app.tsx index 7067746597..b982a5f94b 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -7,9 +7,9 @@ import { ExternalProvider, Web3Provider } from '@ethersproject/providers'; import NProgress from 'nprogress'; import { useRouter } from 'next/router'; +import { Provider } from 'react-redux'; import { NftsProvider } from '@/context/positions.context'; import { TokenDistroProvider } from '@/context/tokenDistro.context'; -import { SubgraphProvider } from '@/context/subgraph.context'; import { PriceProvider } from '@/context/price.context'; import { GeneralProvider } from '@/context/general.context'; import { useApollo } from '@/apollo/apolloClient'; @@ -19,6 +19,7 @@ import { HeaderWrapper } from '@/components/Header/HeaderWrapper'; import { FooterWrapper } from '@/components/Footer/FooterWrapper'; import '../styles/globals.css'; +import { store } from '@/stores/store'; import type { AppProps } from 'next/app'; function getLibrary(provider: ExternalProvider) { @@ -57,10 +58,11 @@ function MyApp({ Component, pageProps }: AppProps) { content='width=device-width, initial-scale=1.0' /> - - - - + + + + + {/* */} @@ -74,10 +76,11 @@ function MyApp({ Component, pageProps }: AppProps) { - - - - + {/* */} + + + + ); diff --git a/pages/test.tsx b/pages/test.tsx index 982a774b4c..39b12ca1a2 100644 --- a/pages/test.tsx +++ b/pages/test.tsx @@ -1,9 +1,20 @@ import Head from 'next/head'; import styled from 'styled-components'; import { GetServerSideProps } from 'next'; +import { useSelector, useDispatch } from 'react-redux'; +import { useWeb3React } from '@web3-react/core'; +import { useEffect } from 'react'; import { gToast, ToastType } from '@/components/toasts'; +import { RootState } from '@/stores/store'; +import { updateXDaiValues } from '@/stores/subgraph.store'; const TestRoute = () => { + const xDaiValues = useSelector( + (state: RootState) => state.subgraph.xDaiValues, + ); + const dispatch = useDispatch(); + const { library } = useWeb3React(); + const notify = () => gToast('Testeeee', { type: ToastType.SUCCESS, @@ -12,12 +23,28 @@ const TestRoute = () => { dismissLabel: 'OK :D', position: 'bottom-center', }); + + console.log('xDaiValues', xDaiValues); + useEffect(() => { + if (!library) return; + library.on('block', (evt: any) => { + console.log('evt', evt); + // dispatch(updateXDaiValues()); + }); + return () => { + library.removeAllListeners('block'); + }; + }, [library]); + return ( <> Terms of use | Giveth + + +

Your transaction has failed!

+ Please go back and try again. +
+ {txUrl && ( + + )} ); }; -const Button = styled(ButtonText)` - color: ${brandColors.deep[100]}; - margin: 44px 0; - cursor: pointer; -`; +const Content = styled(Lead)` + border-radius: 16px; + background: ${semanticColors.punch[100]}; + padding: 30px 20px; + color: ${semanticColors.punch[700]}; + border: 1px solid ${semanticColors.punch[700]}; + margin-top: 42px; + margin-bottom: 48px; + > p { + margin: 0 0 5px; + } -const Error = styled(FlexCenter)` - width: 125px; - height: 125px; - border-radius: 50%; - background: ${semanticColors.punch[300]}; - margin-top: 21px; - margin-bottom: 12px; + ${mediaQueries.mobileL} { + padding: 38px 50px; + } + ${mediaQueries.tablet} { + padding: 38px 93px; + } `; const Container = styled(FlexCenter)` max-width: 500px; - padding: 0 20px; + padding: 0 15px; text-align: center; flex-direction: column; - > h5 { + > :nth-child(2) { color: ${semanticColors.punch[500]}; - } - > :nth-child(3) { - color: ${brandColors.deep[700]}; - margin-top: 8px; + margin-bottom: 40px; max-width: 280px; + font-size: 12px; + font-weight: 700; } ${mediaQueries.mobileL} { - padding: 0 50px; - } - ${mediaQueries.tablet} { - padding: 0 108px; + padding: 0 24px; } `; diff --git a/src/components/modals/Modal.tsx b/src/components/modals/Modal.tsx index f4ab73ee19..56c422ba5e 100644 --- a/src/components/modals/Modal.tsx +++ b/src/components/modals/Modal.tsx @@ -29,6 +29,7 @@ export interface IModal extends ModalWrapperProps { headerTitle?: string; headerIcon?: ReactNode; customTheme?: ETheme; + headerColor?: string; } export const Modal: React.FC = ({ @@ -41,6 +42,7 @@ export const Modal: React.FC = ({ headerIcon, customTheme, fullScreen = false, + headerColor, }) => { const el = useRef(document.createElement('div')); const { theme } = useGeneral(); @@ -83,6 +85,7 @@ export const Modal: React.FC = ({ icon={headerIcon} closeModal={() => setShowModal(false)} position={headerTitlePosition} + color={headerColor} /> ( diff --git a/src/components/modals/ModalHeader.tsx b/src/components/modals/ModalHeader.tsx index 0d73a543c8..c47553699c 100644 --- a/src/components/modals/ModalHeader.tsx +++ b/src/components/modals/ModalHeader.tsx @@ -1,6 +1,6 @@ import React, { ReactNode } from 'react'; import styled from 'styled-components'; -import { H6, IconX } from '@giveth/ui-design-system'; +import { brandColors, H6, IconX } from '@giveth/ui-design-system'; import { Flex } from '@/components/styled-components/Flex'; export type ModalHeaderTitlePosition = 'center' | 'left'; @@ -12,6 +12,7 @@ export interface IModalHeader { icon?: ReactNode; closeModal: () => void; position?: ModalHeaderTitlePosition; + color?: string; } export const ModalHeader: React.FC = ({ @@ -21,16 +22,18 @@ export const ModalHeader: React.FC = ({ icon, closeModal, position = 'center', + color, }) => { return !hiddenHeader ? ( {icon}
{title}
{!hiddenClose && ( - + )}
@@ -41,12 +44,13 @@ export const ModalHeader: React.FC = ({ ) : null; }; -export const ModalHeaderRow = styled(Flex)` +export const ModalHeaderRow = styled(Flex)<{ color?: string }>` gap: 14px; min-height: 48px; padding: 24px 24px 8px; position: relative; align-items: center; + color: ${props => props.color || 'inherit'}; `; const CloseModalButton = styled.div` diff --git a/src/components/views/donate/CryptoDonation.tsx b/src/components/views/donate/CryptoDonation.tsx index a522aeabcd..3f3414c7fe 100644 --- a/src/components/views/donate/CryptoDonation.tsx +++ b/src/components/views/donate/CryptoDonation.tsx @@ -34,7 +34,12 @@ import InlineToast from '@/components/toasts/InlineToast'; import { EProjectStatus } from '@/apollo/types/gqlEnums'; import { client } from '@/apollo/apolloClient'; import { PROJECT_ACCEPTED_TOKENS } from '@/apollo/gql/gqlProjects'; -import { formatBalance, pollEvery, showToastError } from '@/lib/helpers'; +import { + formatBalance, + formatTxLink, + pollEvery, + showToastError, +} from '@/lib/helpers'; import { IProjectAcceptedToken, IProjectAcceptedTokensGQL, @@ -111,6 +116,7 @@ const CryptoDonation = (props: { useState(); const [acceptedChains, setAcceptedChains] = useState(); const [showFailedModal, setShowFailedModal] = useState(false); + const [txHash, setTxHash] = useState(); const stopPolling = useRef(null); const tokenSymbol = selectedToken?.symbol; @@ -331,6 +337,7 @@ const CryptoDonation = (props: { setShowModal={setShowDonateModal} setSuccessDonation={setSuccessDonation} setShowFailedModal={setShowFailedModal} + setTxHash={setTxHash} project={project} token={selectedToken} amount={amountTyped} @@ -342,7 +349,10 @@ const CryptoDonation = (props: { /> )} {showFailedModal && ( - + )} diff --git a/src/components/views/donate/helpers.tsx b/src/components/views/donate/helpers.tsx index a60a670134..d5b46e711a 100644 --- a/src/components/views/donate/helpers.tsx +++ b/src/components/views/donate/helpers.tsx @@ -97,6 +97,7 @@ export const confirmDonation = async (props: IConfirmDonation) => { setDonating, setDonationSaved, givBackEligible, + setTxHash, } = props; const { library } = web3Context; @@ -116,6 +117,7 @@ export const confirmDonation = async (props: IConfirmDonation) => { const txCallbacks = { onTxHash: async (txHash: string) => { await saveDonation({ txHash, toAddress, ...props }); + setTxHash(txHash); setDonationSaved(true); }, onReceipt: (txHash: string) => { @@ -130,6 +132,10 @@ export const confirmDonation = async (props: IConfirmDonation) => { const code = error.data?.code; if (code === ('INSUFFICIENT_FUNDS' || 'UNPREDICTABLE_GAS_LIMIT')) { showToastError('Insufficient Funds'); + } else if (error.replacement && error.cancelled === true) { + setTxHash(error.replacement.hash); + setShowFailedModal(true); + showToastError('Transaction cancelled!'); } else { setShowFailedModal(true); showToastError(error); From cd0083202a62d2486174764344db61bcef44765f Mon Sep 17 00:00:00 2001 From: Ramin Date: Thu, 12 May 2022 00:44:10 +0430 Subject: [PATCH 012/257] fix typo in file name --- .../modals/{FaliedDonation.tsx => FailedDonation.tsx} | 4 ++-- src/components/views/donate/CryptoDonation.tsx | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) rename src/components/modals/{FaliedDonation.tsx => FailedDonation.tsx} (95%) diff --git a/src/components/modals/FaliedDonation.tsx b/src/components/modals/FailedDonation.tsx similarity index 95% rename from src/components/modals/FaliedDonation.tsx rename to src/components/modals/FailedDonation.tsx index 0608095229..41d6b38436 100644 --- a/src/components/modals/FaliedDonation.tsx +++ b/src/components/modals/FailedDonation.tsx @@ -4,10 +4,10 @@ import styled from 'styled-components'; import { Modal } from '@/components/modals/Modal'; import { mediaQueries } from '@/lib/constants/constants'; import { FlexCenter } from '@/components/styled-components/Flex'; -import { IModalProps } from '@/types/common'; +import { IModal } from '@/types/common'; import ExternalLink from '@/components/ExternalLink'; -interface IProps extends IModalProps { +interface IProps extends IModal { txUrl?: string; } diff --git a/src/components/views/donate/CryptoDonation.tsx b/src/components/views/donate/CryptoDonation.tsx index 3f3414c7fe..395c6797c5 100644 --- a/src/components/views/donate/CryptoDonation.tsx +++ b/src/components/views/donate/CryptoDonation.tsx @@ -55,7 +55,7 @@ import useModal from '@/context/ModalProvider'; import { getERC20Info } from '@/lib/contracts'; import GIVBackToast from '@/components/views/donate/GIVBackToast'; import { DonateWrongNetwork } from '@/components/modals/DonateWrongNetwork'; -import FailedDonation from '@/components/modals/FaliedDonation'; +import FailedDonation from '@/components/modals/FailedDonation'; const ethereumChain = config.PRIMARY_NETWORK; const xdaiChain = config.SECONDARY_NETWORK; From 0b9abb490bd9a92d63eea1cf575fedf1b146f1eb Mon Sep 17 00:00:00 2001 From: Amin Latifi Date: Thu, 12 May 2022 12:04:45 +0430 Subject: [PATCH 013/257] Added CULT stream support to TokenDistroHelper.ts --- src/lib/contractHelper/TokenDistroHelper.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/lib/contractHelper/TokenDistroHelper.ts b/src/lib/contractHelper/TokenDistroHelper.ts index 00196f9d6f..49500f88e4 100644 --- a/src/lib/contractHelper/TokenDistroHelper.ts +++ b/src/lib/contractHelper/TokenDistroHelper.ts @@ -88,6 +88,10 @@ export class TokenDistroHelper { allocatedTokens = userBalance.foxAllocatedTokens; claimed = userBalance.foxClaimed; break; + case StreamType.CULT: + allocatedTokens = userBalance.cultAllocatedTokens; + claimed = userBalance.cultClaimed; + break; default: allocatedTokens = userBalance.allocatedTokens; claimed = userBalance.claimed; From f5da5ba33573fc5f9ff0e1b47806cc4ac11afec0 Mon Sep 17 00:00:00 2001 From: Cherik Date: Thu, 12 May 2022 12:20:51 +0430 Subject: [PATCH 014/257] add subgraph api --- src/stores/subgraph-api-slice.ts | 45 ++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/stores/subgraph-api-slice.ts diff --git a/src/stores/subgraph-api-slice.ts b/src/stores/subgraph-api-slice.ts new file mode 100644 index 0000000000..b805fd5491 --- /dev/null +++ b/src/stores/subgraph-api-slice.ts @@ -0,0 +1,45 @@ +import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'; +import { ISubgraphValue } from '@/context/subgraph.context'; +import { SubgraphQueryBuilder } from '@/lib/subgraph/subgraphQueryBuilder'; +import { transformSubgraphData } from '@/lib/subgraph/subgraphDataTransform'; + +interface props { + chain?: number; + userAddress?: string | null; +} + +export const subgraphApiSlice = createApi({ + reducerPath: 'subgraph', + baseQuery: fetchBaseQuery({ + baseUrl: 'https://api.thegraph.com/subgraphs/name/mohammadranjbarz', + }), + endpoints(builder) { + return { + getSubgraphValues: builder.query({ + query(props) { + const reqBody = { + query: SubgraphQueryBuilder.getXDaiQuery( + props.userAddress ?? '', + ), + }; + // throw new Error('boroooo'); + return { + url: `/giv-economy-xdai-develop`, + body: JSON.stringify(reqBody), + method: 'POST', + }; + }, + transformResponse: ( + response: { data: ISubgraphValue }, + meta, + arg, + ) => { + console.log('meta', meta); + return transformSubgraphData(response.data); + }, + }), + }; + }, +}); + +export const { useGetSubgraphValuesQuery } = subgraphApiSlice; From 9b0f491ef006df2f5f654a9c6e65527d141b456b Mon Sep 17 00:00:00 2001 From: Cherik Date: Thu, 12 May 2022 12:21:35 +0430 Subject: [PATCH 015/257] add subgraphapi to store --- pages/_app.tsx | 31 ++++++++++++++++--------------- pages/test.tsx | 28 ++++++++++++++++++---------- src/stores/store.ts | 8 ++++++-- src/stores/subgraph.store.ts | 4 ++-- 4 files changed, 42 insertions(+), 29 deletions(-) diff --git a/pages/_app.tsx b/pages/_app.tsx index b982a5f94b..418e63b27e 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -20,6 +20,7 @@ import { FooterWrapper } from '@/components/Footer/FooterWrapper'; import '../styles/globals.css'; import { store } from '@/stores/store'; +import { SubgraphProvider } from '@/context/subgraph.context'; import type { AppProps } from 'next/app'; function getLibrary(provider: ExternalProvider) { @@ -62,21 +63,21 @@ function MyApp({ Component, pageProps }: AppProps) { - {/* */} - - - - - - - - - - - - - - {/* */} + + + + + + + + + + + + + + + diff --git a/pages/test.tsx b/pages/test.tsx index 39b12ca1a2..9106f92dc7 100644 --- a/pages/test.tsx +++ b/pages/test.tsx @@ -1,19 +1,22 @@ import Head from 'next/head'; import styled from 'styled-components'; import { GetServerSideProps } from 'next'; -import { useSelector, useDispatch } from 'react-redux'; +// import { useSelector, useDispatch } from 'react-redux'; import { useWeb3React } from '@web3-react/core'; import { useEffect } from 'react'; import { gToast, ToastType } from '@/components/toasts'; -import { RootState } from '@/stores/store'; -import { updateXDaiValues } from '@/stores/subgraph.store'; +import { useGetSubgraphValuesQuery } from '@/stores/subgraph-api-slice'; +// import { RootState } from '@/stores/store'; const TestRoute = () => { - const xDaiValues = useSelector( - (state: RootState) => state.subgraph.xDaiValues, - ); - const dispatch = useDispatch(); - const { library } = useWeb3React(); + // const xDaiValues = useSelector( + // (state: RootState) => state.subgraph.xDaiValues, + // ); + const { library, chainId, account } = useWeb3React(); + const { data, isLoading, error, refetch } = useGetSubgraphValuesQuery({ + chain: chainId, + userAddress: account, + }); const notify = () => gToast('Testeeee', { @@ -24,7 +27,7 @@ const TestRoute = () => { position: 'bottom-center', }); - console.log('xDaiValues', xDaiValues); + // console.log('xDaiValues', xDaiValues); useEffect(() => { if (!library) return; library.on('block', (evt: any) => { @@ -35,6 +38,7 @@ const TestRoute = () => { library.removeAllListeners('block'); }; }, [library]); + console.log('****data', data); return ( <> @@ -42,7 +46,11 @@ const TestRoute = () => { Terms of use | Giveth - diff --git a/src/stores/store.ts b/src/stores/store.ts index 576c79ed7d..b73a81c2c5 100644 --- a/src/stores/store.ts +++ b/src/stores/store.ts @@ -1,9 +1,13 @@ import { configureStore } from '@reduxjs/toolkit'; -import subgraphReducer from './subgraph.store'; +import { subgraphApiSlice } from './subgraph-api-slice'; +// import subgraphReducer from './subgraph.store'; export const store = configureStore({ reducer: { - subgraph: subgraphReducer, + [subgraphApiSlice.reducerPath]: subgraphApiSlice.reducer, + }, + middleware: getDefaultMiddleware => { + return getDefaultMiddleware().concat(subgraphApiSlice.middleware); }, }); diff --git a/src/stores/subgraph.store.ts b/src/stores/subgraph.store.ts index 36a2f47f64..b076b98a11 100644 --- a/src/stores/subgraph.store.ts +++ b/src/stores/subgraph.store.ts @@ -93,14 +93,14 @@ export const subgraphSlice = createSlice({ // which detects changes to a "draft state" and produces a brand new // immutable state based off those changes // state.value += 1; - console.log('state', state); + // console.log('state', state); }, updateXDaiValues: state => { // state.value -= 1; }, updateMainnetValues: (state, action: PayloadAction) => { // state.value -= 1; - state.mainnetValues = fetchMainnetInfo(action.payload); + // state.mainnetValues = fetchMainnetInfo(action.payload); }, incrementByAmount: (state, action: PayloadAction) => { // state.value += action.payload; From 6c0fb2ebe7b726d326be632620d6b9b1843f0bbc Mon Sep 17 00:00:00 2001 From: Amin Latifi Date: Thu, 12 May 2022 12:30:16 +0430 Subject: [PATCH 016/257] Added cult token support in AmountBoxWithPrice.tsx --- src/components/AmountBoxWithPrice.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/components/AmountBoxWithPrice.tsx b/src/components/AmountBoxWithPrice.tsx index 8ae6271dd7..32f6da50ca 100644 --- a/src/components/AmountBoxWithPrice.tsx +++ b/src/components/AmountBoxWithPrice.tsx @@ -8,6 +8,7 @@ import { } from './AmountBoxWithPrice.sc'; import { IconGIV } from '@/components/Icons/GIV'; import { IconFox } from '@/components/Icons/Fox'; +import { IconCult } from '@/components/Icons/Cult'; interface IGIVBoxWithPriceProps { amount: ethers.BigNumber; @@ -19,6 +20,8 @@ const getTokenIconBySymbol = (tokenSymbol: string) => { switch (tokenSymbol) { case 'FOX': return ; + case 'CULT': + return ; case 'GIV': default: return ; From 883b1892e9e143bf0a4bb2d6e4074324794e67a3 Mon Sep 17 00:00:00 2001 From: alireza-sharifpour Date: Thu, 12 May 2022 13:14:09 +0430 Subject: [PATCH 017/257] Added new eslint rule for named-imports --- .eslintrc | 3 ++- src/components/RichTextInput.tsx | 1 + src/lib/helpers.ts | 1 + 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.eslintrc b/.eslintrc index c73227bfec..95523ba685 100644 --- a/.eslintrc +++ b/.eslintrc @@ -23,7 +23,8 @@ { "endOfLine": "auto" } - ] + ], + "import/named": "error" }, "settings": { "import/resolver": { diff --git a/src/components/RichTextInput.tsx b/src/components/RichTextInput.tsx index 0e1d031400..690b97192f 100644 --- a/src/components/RichTextInput.tsx +++ b/src/components/RichTextInput.tsx @@ -1,4 +1,5 @@ import React, { useEffect, useState } from 'react'; +// eslint-disable-next-line import/named import ReactQuill, { Quill } from 'react-quill'; import QuillImageDropAndPaste from 'quill-image-drop-and-paste'; import styled from 'styled-components'; diff --git a/src/lib/helpers.ts b/src/lib/helpers.ts index 5e86c7b9dc..f72faf60ac 100644 --- a/src/lib/helpers.ts +++ b/src/lib/helpers.ts @@ -1,4 +1,5 @@ import { promisify } from 'util'; +// eslint-disable-next-line import/named import { unescape } from 'lodash'; import { parseUnits, parseEther } from '@ethersproject/units'; import { keccak256 } from '@ethersproject/keccak256'; From f1bdcb5626a33a118091dbc9c9690f207afdaf62 Mon Sep 17 00:00:00 2001 From: Ramin Date: Thu, 12 May 2022 13:41:29 +0430 Subject: [PATCH 018/257] #689 Fix from our blog not showing --- src/components/views/homepage/HomeFromBlog.tsx | 2 +- src/components/views/project/ProjectDonateCard.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/components/views/homepage/HomeFromBlog.tsx b/src/components/views/homepage/HomeFromBlog.tsx index 80cc23d608..d6fc15549c 100644 --- a/src/components/views/homepage/HomeFromBlog.tsx +++ b/src/components/views/homepage/HomeFromBlog.tsx @@ -14,7 +14,7 @@ const HomeFromBlog = () => { useEffect(() => { const getPosts = async () => { const medium = await fetch( - 'https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/giveth', + 'https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/giveth/', ); const posts = await medium.json(); setMediumPosts(posts?.items?.slice(0, 2)); diff --git a/src/components/views/project/ProjectDonateCard.tsx b/src/components/views/project/ProjectDonateCard.tsx index be9dd95e01..8ed6dae549 100644 --- a/src/components/views/project/ProjectDonateCard.tsx +++ b/src/components/views/project/ProjectDonateCard.tsx @@ -18,8 +18,8 @@ import { IconHelp, } from '@giveth/ui-design-system'; import { motion } from 'framer-motion'; - import { captureException } from '@sentry/nextjs'; + import ShareLikeBadge from '@/components/badges/ShareLikeBadge'; import { Shadow } from '@/components/styled-components/Shadow'; import CategoryBadge from '@/components/badges/CategoryBadge'; From 50d1a564154a003b87de01294158d49d66fe7551 Mon Sep 17 00:00:00 2001 From: Ramin Date: Sun, 15 May 2022 02:49:36 +0430 Subject: [PATCH 019/257] #693 add donation status to tables --- src/apollo/gql/gqlUser.ts | 1 + src/apollo/types/gqlEnums.ts | 6 +++ src/apollo/types/types.ts | 7 ++- src/components/views/donate/DonateIndex.tsx | 16 ++----- .../views/project/ProjectDonationTable.tsx | 45 +++++++++---------- .../donationsTab/DonationsTable.tsx | 4 +- 6 files changed, 42 insertions(+), 37 deletions(-) diff --git a/src/apollo/gql/gqlUser.ts b/src/apollo/gql/gqlUser.ts index 149f8921fd..0a01e36191 100644 --- a/src/apollo/gql/gqlUser.ts +++ b/src/apollo/gql/gqlUser.ts @@ -97,6 +97,7 @@ export const FETCH_USER_DONATIONS = gql` slug } createdAt + status } totalCount } diff --git a/src/apollo/types/gqlEnums.ts b/src/apollo/types/gqlEnums.ts index 56ab71e522..2d654ef406 100644 --- a/src/apollo/types/gqlEnums.ts +++ b/src/apollo/types/gqlEnums.ts @@ -24,3 +24,9 @@ export enum EDirection { export enum EDonationType { POIGNART = 'poignArt', } + +export enum EDonationStatus { + PENDING = 'pending', + VERIFIED = 'verified', + FAILED = 'failed', +} diff --git a/src/apollo/types/types.ts b/src/apollo/types/types.ts index 62efb117b9..7bec9ac703 100644 --- a/src/apollo/types/types.ts +++ b/src/apollo/types/types.ts @@ -1,4 +1,8 @@ -import { EDonationType, EProjectStatus } from '@/apollo/types/gqlEnums'; +import { + EDonationStatus, + EDonationType, + EProjectStatus, +} from '@/apollo/types/gqlEnums'; export interface IProject { id?: string; @@ -112,6 +116,7 @@ export interface IDonation { createdAt: string; donationType?: EDonationType; anonymous?: boolean; + status: EDonationStatus; } export interface IWalletDonation extends IDonation { diff --git a/src/components/views/donate/DonateIndex.tsx b/src/components/views/donate/DonateIndex.tsx index 34f8ed2e29..3f3d3f3f47 100644 --- a/src/components/views/donate/DonateIndex.tsx +++ b/src/components/views/donate/DonateIndex.tsx @@ -1,6 +1,5 @@ import React, { useState } from 'react'; import { useWeb3React } from '@web3-react/core'; -import { H4, brandColors } from '@giveth/ui-design-system'; import styled from 'styled-components'; import { ISuccessDonation } from './CryptoDonation'; @@ -37,13 +36,10 @@ const ProjectsIndex = (props: IProjectBySlug) => { givBackEligible={givBackEligible!} /> ) : ( - <> -

Donate With

- - + )} @@ -81,10 +77,6 @@ const Right = styled.div<{ isMobile: boolean }>` padding: 65px 32px 32px; border-radius: ${props => (props.isMobile ? '16px' : '0 16px 16px 0')}; min-height: 620px; - > h4 { - color: ${brandColors.deep[700]}; - font-weight: bold; - } `; export default ProjectsIndex; diff --git a/src/components/views/project/ProjectDonationTable.tsx b/src/components/views/project/ProjectDonationTable.tsx index 5be7924593..c359979468 100644 --- a/src/components/views/project/ProjectDonationTable.tsx +++ b/src/components/views/project/ProjectDonationTable.tsx @@ -5,10 +5,7 @@ import { B, brandColors, H6, - IconArrowBottom, - IconArrowTop, IconExternalLink, - IconSort16, neutralColors, P, SublineBold, @@ -24,6 +21,7 @@ import { smallFormatDate, formatTxLink } from '@/lib/helpers'; import config from '@/configuration'; import { EDirection, EDonationType } from '@/apollo/types/gqlEnums'; import ExternalLink from '@/components/ExternalLink'; +import SortIcon from '@/components/SortIcon'; const itemPerPage = 10; @@ -38,18 +36,6 @@ interface IOrder { direction: EDirection; } -const injectSortIcon = (order: IOrder, title: EOrderBy) => { - return order.by === title ? ( - order.direction === EDirection.DESC ? ( - - ) : ( - - ) - ) : ( - - ); -}; - interface IProjectDonationTable { donations: IDonation[]; id?: string; @@ -72,10 +58,10 @@ const ProjectDonationTable = ({ const [activeTab, setActiveTab] = useState(0); const [searchTerm, setSearchTerm] = useState(''); - const orderChangeHandler = (orderby: EOrderBy) => { - if (orderby === order.by) { + const orderChangeHandler = (orderBy: EOrderBy) => { + if (orderBy === order.by) { setOrder({ - by: orderby, + by: orderBy, direction: order.direction === EDirection.ASC ? EDirection.DESC @@ -83,7 +69,7 @@ const ProjectDonationTable = ({ }); } else { setOrder({ - by: orderby, + by: orderBy, direction: EDirection.DESC, }); } @@ -147,11 +133,17 @@ const ProjectDonationTable = ({ } > Donated at - {injectSortIcon(order, EOrderBy.CreationDate)} + Donor + + Status + Network @@ -164,7 +156,10 @@ const ProjectDonationTable = ({ } > Amount - {injectSortIcon(order, EOrderBy.TokenAmount)} + @@ -172,7 +167,10 @@ const ProjectDonationTable = ({ } > USD Value - {injectSortIcon(order, EOrderBy.UsdAmount)} + {pageDonations.map(donation => ( @@ -194,6 +192,7 @@ const ProjectDonationTable = ({ donation.user?.firstName}

+ {donation.status}

{donation.transactionNetworkId === @@ -305,7 +304,7 @@ const DonationTableContainer = styled.div` margin-top: 12px; display: grid; width: 100%; - grid-template-columns: 1.25fr 2fr 1.25fr 1fr 1fr 1fr; + grid-template-columns: 1.25fr 2fr 1fr 1.25fr 1fr 1fr 1fr; min-width: 800px; `; diff --git a/src/components/views/userPublicProfile/donationsTab/DonationsTable.tsx b/src/components/views/userPublicProfile/donationsTab/DonationsTable.tsx index 06050331f8..513addeb8a 100644 --- a/src/components/views/userPublicProfile/donationsTab/DonationsTable.tsx +++ b/src/components/views/userPublicProfile/donationsTab/DonationsTable.tsx @@ -39,6 +39,7 @@ const DonationTable: FC = ({ Project + Status Currency changeOrder(EOrderBy.TokenAmount)}> Amount @@ -62,6 +63,7 @@ const DonationTable: FC = ({ + {donation.status} {donation.currency} @@ -111,7 +113,7 @@ const TableCell = styled(P)<{ bold?: boolean }>` const DonationTableContainer = styled.div` display: grid; - grid-template-columns: 1fr 4fr 1fr 1fr 1fr; + grid-template-columns: 1fr 4fr 1fr 1fr 1fr 1fr; overflow: auto; min-width: 900px; margin: 0 10px; From 6bb3100b14e6f52302d913a28602c2325801c89c Mon Sep 17 00:00:00 2001 From: Ramin Date: Sun, 15 May 2022 02:51:12 +0430 Subject: [PATCH 020/257] change saving and updating donation service --- src/apollo/gql/gqlDonations.ts | 37 +++++++ src/components/views/donate/DonationTypes.tsx | 2 + src/components/views/donate/helpers.tsx | 12 ++- .../views/project/ProjectDonations.tsx | 6 +- src/lib/helpers.ts | 4 +- src/services/donation.ts | 99 ++++++------------- 6 files changed, 81 insertions(+), 79 deletions(-) diff --git a/src/apollo/gql/gqlDonations.ts b/src/apollo/gql/gqlDonations.ts index e5c1fe7c1c..124650c222 100644 --- a/src/apollo/gql/gqlDonations.ts +++ b/src/apollo/gql/gqlDonations.ts @@ -31,6 +31,7 @@ export const FETCH_PROJECT_DONATIONS = gql` transactionNetworkId createdAt donationType + status } totalCount } @@ -95,3 +96,39 @@ export const SAVE_DONATION = gql` ) } `; + +export const CREATE_DONATION = gql` + mutation ( + $transactionId: String! + $transactionNetworkId: Float! + $nonce: Float! + $amount: Float! + $token: String! + $projectId: Float! + $transakId: String + $tokenAddress: String + $anonymous: Boolean + ) { + createDonation( + transactionId: $transactionId + transactionNetworkId: $transactionNetworkId + nonce: $nonce + amount: $amount + token: $token + projectId: $projectId + transakId: $transakId + tokenAddress: $tokenAddress + anonymous: $anonymous + ) + } +`; + +export const UPDATE_DONATION_STATUS = gql` + mutation ($status: String!, $donationId: Float!) { + updateDonationStatus(status: $status, donationId: $donationId) { + id + status + verifyErrorMessage + } + } +`; diff --git a/src/components/views/donate/DonationTypes.tsx b/src/components/views/donate/DonationTypes.tsx index acec091af2..10044b9654 100644 --- a/src/components/views/donate/DonationTypes.tsx +++ b/src/components/views/donate/DonationTypes.tsx @@ -1,5 +1,6 @@ import React, { useState } from 'react'; import styled from 'styled-components'; +import { H4 } from '@giveth/ui-design-system'; import CryptoDonation, { ISuccessDonation, @@ -18,6 +19,7 @@ const DonationTypes = (props: { return ( <> +

Donate With

{ const { library } = web3Context; const { walletAddress } = project; const { address } = token; + let donationId = 0; try { const toAddress = isAddressENS(walletAddress!) @@ -115,12 +117,13 @@ export const confirmDonation = async (props: IConfirmDonation) => { }; const txCallbacks = { - onTxHash: async (txHash: string) => { - await saveDonation({ txHash, toAddress, ...props }); + onTxHash: async (txHash: string, nonce: number) => { + donationId = await saveDonation({ nonce, txHash, ...props }); setTxHash(txHash); setDonationSaved(true); }, - onReceipt: (txHash: string) => { + onReceipt: async (txHash: string) => { + updateDonation(donationId, EDonationStatus.VERIFIED); setSuccessDonation({ txHash, givBackEligible }); }, }; @@ -136,6 +139,7 @@ export const confirmDonation = async (props: IConfirmDonation) => { setTxHash(error.replacement.hash); setShowFailedModal(true); showToastError('Transaction cancelled!'); + updateDonation(donationId, EDonationStatus.FAILED); } else { setShowFailedModal(true); showToastError(error); diff --git a/src/components/views/project/ProjectDonations.tsx b/src/components/views/project/ProjectDonations.tsx index 85ea4d7689..681acc8a02 100644 --- a/src/components/views/project/ProjectDonations.tsx +++ b/src/components/views/project/ProjectDonations.tsx @@ -6,6 +6,7 @@ import { IProject } from '@/apollo/types/types'; import { IDonationsByProjectId } from '@/apollo/types/gqlTypes'; import ProjectTotalFundCard from './ProjectTotalFundCard'; import ProjectDonationTable from './ProjectDonationTable'; +import { FlexCenter } from '@/components/styled-components/Flex'; const ProjectDonations = (props: { donationsByProjectId: IDonationsByProjectId; @@ -49,13 +50,10 @@ const ProjectDonations = (props: { ); }; -const MessageContainer = styled.div` +const MessageContainer = styled(FlexCenter)` height: 200px; width: 100%; - display: flex; flex-direction: column; - justify-content: center; - align-items: center; gap: 32px; `; diff --git a/src/lib/helpers.ts b/src/lib/helpers.ts index f72faf60ac..7a40b0df2b 100644 --- a/src/lib/helpers.ts +++ b/src/lib/helpers.ts @@ -172,7 +172,7 @@ export async function sendTransaction( web3: Web3Provider, params: { to: string; value: string }, txCallbacks: { - onTxHash: (hash: string) => void; + onTxHash: (hash: string, nonce: number) => void; onReceipt: (receipt: any) => void; }, contractAddress: string, @@ -196,7 +196,7 @@ export async function sendTransaction( tx = await fromSigner.sendTransaction(txParams); } - txCallbacks.onTxHash(tx.hash); + txCallbacks.onTxHash(tx.hash, tx.nonce); const receipt = await tx.wait(); if (receipt.status) { txCallbacks.onReceipt(tx.hash); diff --git a/src/services/donation.ts b/src/services/donation.ts index 4fc048c4fd..67b4a11052 100644 --- a/src/services/donation.ts +++ b/src/services/donation.ts @@ -1,54 +1,60 @@ // import transakSDK from '@transak/transak-sdk' import { captureException } from '@sentry/nextjs'; -import { SAVE_DONATION } from '@/apollo/gql/gqlDonations'; +import { + CREATE_DONATION, + UPDATE_DONATION_STATUS, +} from '@/apollo/gql/gqlDonations'; import { client } from '@/apollo/apolloClient'; import { IConfirmDonation } from '@/components/views/donate/helpers'; interface IOnTxHash extends IConfirmDonation { txHash: string; - toAddress: string; + nonce: number; } +export const updateDonation = (donationId: number, status: string) => { + client + .mutate({ + mutation: UPDATE_DONATION_STATUS, + variables: { donationId, status }, + }) + .catch((err: unknown) => + captureException(err, { + tags: { + section: 'updateDonation', + }, + }), + ); +}; + export async function saveDonation(props: IOnTxHash) { - const { - web3Context, - toAddress, - txHash: transactionId, - amount, - token, - project, - anonymous, - } = props; + const { web3Context, txHash, amount, token, project, anonymous, nonce } = + props; - const { account: fromAddress, chainId } = web3Context; - const { address: tokenAddress, symbol } = token; + const { chainId } = web3Context; + const { address, symbol } = token; const projectId = Number(project.id); let donationId = 0; try { const { data } = await client.mutate({ - mutation: SAVE_DONATION, + mutation: CREATE_DONATION, variables: { - chainId, - fromAddress, - toAddress, - transactionId, + transactionId: txHash, transactionNetworkId: chainId, + nonce, amount, token: symbol, projectId, - transakId: null, - transakStatus: null, - tokenAddress, + tokenAddress: address, anonymous, }, }); - const { saveDonation } = data; - donationId = saveDonation; + donationId = data.createDonation; } catch (error) { captureException(error, { tags: { - section: 'saveDonation', + section: 'createDonation', }, }); throw error; @@ -57,51 +63,6 @@ export async function saveDonation(props: IOnTxHash) { return donationId; } -export async function saveDonationFromTransak( - fromAddress: string, - toAddress: string, - amount: number, - token: string, - projectId: number, - transakId: string, - transakStatus: string, -) { - const saveDonationErrors = []; - let donationId: any = 0; - try { - const { data } = await client.mutate({ - mutation: SAVE_DONATION, - variables: { - chainId: 1, - fromAddress, - toAddress, - transactionId: null, - transactionNetworkId: 1, - amount, - token, - projectId, - transakId, - transakStatus, - }, - }); - const { saveDonation: saveDonationId } = data; - donationId = saveDonationId; - } catch (error) { - console.log({ error }); - saveDonationErrors.push(error); - captureException(error, { - tags: { - section: 'saveDonationFromTransak', - }, - }); - } - return { - donationId, - saveDonationErrors, - savedDonation: saveDonationErrors.length === 0, - }; -} - // export async function startTransakDonation({ project, setSuccess }) { // const request = await fetch(`/api/transak`) // const response = await request.json() From f304a0cd9e290fb686ed06096a2dc30206b86255 Mon Sep 17 00:00:00 2001 From: Amin Latifi Date: Sun, 15 May 2022 12:00:22 +0430 Subject: [PATCH 021/257] Used unipoolHelper in calculating APR Refs #695 --- src/components/cards/Stake.tsx | 11 ++++-- src/hooks/useStakingPool.tsx | 10 +++--- src/lib/contractHelper/UnipoolHelper.ts | 2 +- src/lib/stakingPool.ts | 48 +++++++++++++------------ 4 files changed, 40 insertions(+), 31 deletions(-) diff --git a/src/components/cards/Stake.tsx b/src/components/cards/Stake.tsx index 3167dcb275..74a967135d 100644 --- a/src/components/cards/Stake.tsx +++ b/src/components/cards/Stake.tsx @@ -33,6 +33,7 @@ import { useSubgraph } from '@/context'; import { useTokenDistro } from '@/context/tokenDistro.context'; import { networkProviders } from '@/helpers/networkProvider'; import { StakingType } from '@/types/config'; +import { UnipoolHelper } from '@/lib/contractHelper/UnipoolHelper'; const InvestCardContainer = styled(Card)` ::before { @@ -145,22 +146,28 @@ const InvestCard: FC = ({ index }) => { const promiseQueue: Promise[] = []; config.XDAI_CONFIG.pools.forEach(poolStakingConfig => { + const unipool = xDaiValues[poolStakingConfig.type]; + const unipoolHelper = unipool && new UnipoolHelper(unipool); + const promise: Promise = getLPStakingAPR( poolStakingConfig, config.XDAI_NETWORK_NUMBER, networkProviders[config.XDAI_NETWORK_NUMBER], - xDaiValues[poolStakingConfig.type], + unipoolHelper, ); promiseQueue.push(promise); }); config.MAINNET_CONFIG.pools.forEach(poolStakingConfig => { if (poolStakingConfig.type === StakingType.UNISWAPV3) return; + const unipool = mainnetValues[poolStakingConfig.type]; + const unipoolHelper = unipool && new UnipoolHelper(unipool); + const promise: Promise = getLPStakingAPR( poolStakingConfig, config.MAINNET_NETWORK_NUMBER, networkProviders[config.MAINNET_NETWORK_NUMBER], - mainnetValues[poolStakingConfig.type], + unipoolHelper, ); promiseQueue.push(promise); }); diff --git a/src/hooks/useStakingPool.tsx b/src/hooks/useStakingPool.tsx index f6c9af5537..008f7f24bc 100644 --- a/src/hooks/useStakingPool.tsx +++ b/src/hooks/useStakingPool.tsx @@ -55,14 +55,15 @@ export const useStakingPool = ( providerNetwork === network && unipoolIsDefined ) { + const unipoolHelper = unipool && new UnipoolHelper(unipool); const promise: Promise = type === StakingType.GIV_LM - ? getGivStakingAPR(LM_ADDRESS, network, unipool) + ? getGivStakingAPR(LM_ADDRESS, network, unipoolHelper) : getLPStakingAPR( poolStakingConfig, network, library, - unipool, + unipoolHelper, ); promise.then(setApr); } else { @@ -83,12 +84,11 @@ export const useStakingPool = ( }, [library, chainId, unipoolIsDefined, providerNetwork]); useEffect(() => { - const unipoolInfo = currentValues[regenFarmType || type]; - const unipoolHelper = unipoolInfo && new UnipoolHelper(unipoolInfo); + const unipoolHelper = unipool && new UnipoolHelper(unipool); setUserStakeInfo( getUserStakeInfo(type, regenFarmType, balances, unipoolHelper), ); - }, [type, regenFarmType, currentValues, balances]); + }, [type, regenFarmType, balances, unipool]); return { apr, ...userStakeInfo, diff --git a/src/lib/contractHelper/UnipoolHelper.ts b/src/lib/contractHelper/UnipoolHelper.ts index 06cb98b35f..77ae0d8ab9 100644 --- a/src/lib/contractHelper/UnipoolHelper.ts +++ b/src/lib/contractHelper/UnipoolHelper.ts @@ -9,7 +9,7 @@ const toBN = (value: ethers.BigNumberish): BigNumber => { }; export class UnipoolHelper { - private readonly totalSupply: BigNumber; + readonly totalSupply: BigNumber; private readonly lastUpdateTime: number; private readonly periodFinish: number; private readonly rewardPerTokenStored: BigNumber; diff --git a/src/lib/stakingPool.ts b/src/lib/stakingPool.ts index 9b79940b80..3d4b12c676 100644 --- a/src/lib/stakingPool.ts +++ b/src/lib/stakingPool.ts @@ -18,7 +18,7 @@ import config from '../configuration'; import { APR } from '@/types/poolInfo'; import { UnipoolHelper } from '@/lib/contractHelper/UnipoolHelper'; import { Zero } from '@/helpers/number'; -import { IBalances, IUnipool } from '@/types/subgraph'; +import { IBalances } from '@/types/subgraph'; import { getGasPreference } from '@/lib/helpers'; import LM_Json from '../artifacts/UnipoolTokenDistributor.json'; @@ -41,7 +41,7 @@ const toBigNumber = (eb: ethers.BigNumber): BigNumber => export const getGivStakingAPR = async ( lmAddress: string, network: number, - unipool: IUnipool | undefined, + unipool: UnipoolHelper | undefined, ): Promise => { let apr: BigNumber = Zero; @@ -51,10 +51,7 @@ export const getGivStakingAPR = async ( apr = totalSupply.isZero() ? Zero - : toBigNumber(rewardRate) - .div(totalSupply.toString()) - .times('31536000') - .times('100'); + : rewardRate.div(totalSupply).times('31536000').times('100'); } return apr; @@ -64,7 +61,7 @@ export const getLPStakingAPR = async ( poolStakingConfig: PoolStakingConfig, network: number, provider: JsonRpcProvider | null, - unipool: IUnipool | undefined, + unipoolHelper: UnipoolHelper | undefined, ): Promise => { if (!provider) { return Zero; @@ -74,14 +71,14 @@ export const getLPStakingAPR = async ( poolStakingConfig as BalancerPoolStakingConfig, network, provider, - unipool, + unipoolHelper, ); } else { return getSimplePoolStakingAPR( poolStakingConfig, network, provider, - unipool, + unipoolHelper, ); } }; @@ -90,7 +87,7 @@ const getBalancerPoolStakingAPR = async ( balancerPoolStakingConfig: BalancerPoolStakingConfig, network: number, provider: JsonRpcProvider, - unipool: IUnipool | undefined, + unipool: UnipoolHelper | undefined, ): Promise => { const { LM_ADDRESS, POOL_ADDRESS, VAULT_ADDRESS, POOL_ID } = balancerPoolStakingConfig; @@ -121,8 +118,8 @@ const getBalancerPoolStakingAPR = async ( poolContract.getNormalizedWeights(), ]); - let totalSupply: ethers.BigNumber; - let rewardRate: ethers.BigNumber; + let totalSupply: BigNumber; + let rewardRate: BigNumber; if (unipool) { totalSupply = unipool.totalSupply; @@ -131,6 +128,9 @@ const getBalancerPoolStakingAPR = async ( [totalSupply, rewardRate] = await Promise.all([ lmContract.totalSupply(), lmContract.rewardRate(), + ]).then(([_totalSupply, _rewardRate]) => [ + toBigNumber(_totalSupply as ethers.BigNumber), + toBigNumber(_rewardRate as ethers.BigNumber), ]); } @@ -150,8 +150,8 @@ const getBalancerPoolStakingAPR = async ( apr = totalSupply.isZero() ? null - : toBigNumber(rewardRate) - .div(totalSupply.toString()) + : rewardRate + .div(totalSupply) .times('31536000') .times('100') .times(lp); @@ -169,7 +169,7 @@ const getSimplePoolStakingAPR = async ( poolStakingConfig: SimplePoolStakingConfig | RegenPoolStakingConfig, network: number, provider: JsonRpcProvider, - unipool: IUnipool | undefined, + unipoolHelper: UnipoolHelper | undefined, ): Promise => { const { LM_ADDRESS, POOL_ADDRESS } = poolStakingConfig; const givTokenAddress = config.NETWORKS_CONFIG[network].TOKEN_ADDRESS; @@ -184,9 +184,8 @@ const getSimplePoolStakingAPR = async ( : givTokenAddress; const lmContract = new Contract(LM_ADDRESS, LM_ABI, provider); - let reserves; - let totalSupply: ethers.BigNumber; - let rewardRate: ethers.BigNumber; + let totalSupply: BigNumber; + let rewardRate: BigNumber; const poolContract = new Contract(POOL_ADDRESS, UNI_ABI, provider); let apr = null; try { @@ -199,13 +198,16 @@ const getSimplePoolStakingAPR = async ( poolContract.token0(), poolContract.totalSupply(), ]); - if (unipool) { - totalSupply = unipool.totalSupply; - rewardRate = unipool.rewardRate; + if (unipoolHelper) { + totalSupply = unipoolHelper.totalSupply; + rewardRate = unipoolHelper.rewardRate; } else { [totalSupply, rewardRate] = await Promise.all([ lmContract.totalSupply(), lmContract.rewardRate(), + ]).then(([_totalSupply, _rewardRate]) => [ + toBigNumber(_totalSupply as ethers.BigNumber), + toBigNumber(_rewardRate as ethers.BigNumber), ]); } let tokenReseve = toBigNumber( @@ -220,8 +222,8 @@ const getSimplePoolStakingAPR = async ( .div(tokenReseve); apr = totalSupply.isZero() ? null - : toBigNumber(rewardRate) - .div(totalSupply.toString()) + : rewardRate + .div(totalSupply) .times('31536000') .times('100') .times(lp) From ae683a0c16f2ba9146d7175bc470696dfc4efab6 Mon Sep 17 00:00:00 2001 From: Amin Latifi Date: Sun, 15 May 2022 12:08:52 +0430 Subject: [PATCH 022/257] Fixed a parameter passing error --- src/components/cards/Govern.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/components/cards/Govern.tsx b/src/components/cards/Govern.tsx index 2174b387d9..3c4cb0a8d6 100644 --- a/src/components/cards/Govern.tsx +++ b/src/components/cards/Govern.tsx @@ -33,6 +33,7 @@ import { useTokenDistro } from '@/context/tokenDistro.context'; import { useSubgraph } from '@/context'; import { StakingType } from '@/types/config'; import useClaim from '@/context/claim.context'; +import { UnipoolHelper } from '@/lib/contractHelper/UnipoolHelper'; const GovernCardContainer = styled(Card)` padding-left: 254px; @@ -144,10 +145,13 @@ const GovernCard: FC = ({ index }) => { useEffect(() => { const cb = () => { + const unipool = xDaiValues[StakingType.GIV_LM]; + const unipoolHelper = unipool && new UnipoolHelper(unipool); + getGivStakingAPR( config.XDAI_CONFIG.GIV.LM_ADDRESS, config.XDAI_NETWORK_NUMBER, - xDaiValues[StakingType.GIV_LM], + unipoolHelper, ) .then(_apr => { mounted.current && setApr(_apr); From a5ecea1418015927bdbd5963385dbc9214f3afb9 Mon Sep 17 00:00:00 2001 From: Ramin Date: Sun, 15 May 2022 16:20:41 +0430 Subject: [PATCH 023/257] refactor project donation table --- .../views/project/ProjectDonationTable.tsx | 87 ++++++++----------- 1 file changed, 34 insertions(+), 53 deletions(-) diff --git a/src/components/views/project/ProjectDonationTable.tsx b/src/components/views/project/ProjectDonationTable.tsx index 5be7924593..6f1300a583 100644 --- a/src/components/views/project/ProjectDonationTable.tsx +++ b/src/components/views/project/ProjectDonationTable.tsx @@ -24,6 +24,8 @@ import { smallFormatDate, formatTxLink } from '@/lib/helpers'; import config from '@/configuration'; import { EDirection, EDonationType } from '@/apollo/types/gqlEnums'; import ExternalLink from '@/components/ExternalLink'; +import ETHIcon from '/public/images/currencies/eth/24.svg'; +import GnosisIcon from '/public/images/currencies/gnosisChain/24.svg'; const itemPerPage = 10; @@ -146,24 +148,18 @@ const ProjectDonationTable = ({ orderChangeHandler(EOrderBy.CreationDate) } > - Donated at + Donated at {injectSortIcon(order, EOrderBy.CreationDate)} - - Donor - - - Network - - - Currency - + Donor + Network + Currency orderChangeHandler(EOrderBy.TokenAmount) } > - Amount + Amount {injectSortIcon(order, EOrderBy.TokenAmount)} - USD Value + USD Value {injectSortIcon(order, EOrderBy.UsdAmount)} {pageDonations.map(donation => ( -

- {smallFormatDate( - new Date(donation.createdAt), - )} -

+ {smallFormatDate( + new Date(donation.createdAt), + )}
-

- {donation.donationType === - EDonationType.POIGNART - ? 'PoignART' - : donation.anonymous - ? 'Anonymous' - : donation.user?.name || - donation.user?.firstName} -

+ {donation.donationType === + EDonationType.POIGNART + ? 'PoignART' + : donation.anonymous + ? 'Anonymous' + : donation.user?.name || + donation.user?.firstName}
+ chain logo

{donation.transactionNetworkId === - config.XDAI_NETWORK_NUMBER ? ( - - Gnosis chain logo -

Gnosis

- - ) : ( - - Ethereum chain logo -

Ethereum

-
- )} + config.XDAI_NETWORK_NUMBER + ? 'Gnosis' + : 'Ethereum'}

@@ -309,10 +294,11 @@ const DonationTableContainer = styled.div` min-width: 800px; `; -const TableHeader = styled(Flex)` +const TableHeader = styled(B)` height: 40px; border-bottom: 1px solid ${neutralColors.gray[400]}; align-items: center; + display: flex; ${props => props.onClick && `cursor: pointer; @@ -345,9 +331,4 @@ const CurrencyBadge = styled(SublineBold)` color: ${neutralColors.gray[700]}; `; -const NetworkCell = styled.div` - display: flex; - gap: 8px; -`; - export default ProjectDonationTable; From 03fe99f9eaea69dc3905a796ec326ab4fe5a52f6 Mon Sep 17 00:00:00 2001 From: alireza-sharifpour Date: Mon, 16 May 2022 11:11:16 +0430 Subject: [PATCH 024/257] Added new ProjectCard Design and Fixed issues in mobile devices --- src/components/modals/Modal.tsx | 2 +- src/components/project-card/ProjectCard.tsx | 212 ++++++++++++------ .../project-card/ProjectCardBadges.tsx | 16 +- 3 files changed, 152 insertions(+), 78 deletions(-) diff --git a/src/components/modals/Modal.tsx b/src/components/modals/Modal.tsx index 1a2c03694b..d0a0dd5397 100644 --- a/src/components/modals/Modal.tsx +++ b/src/components/modals/Modal.tsx @@ -75,7 +75,7 @@ export const Modal: FC = ({ }; return createPortal( - + e.stopPropagation()}> setShowModal(false)} /> { totalDonations, updatedAt, organization, + verified, } = project; const [isHover, setIsHover] = useState(false); @@ -56,83 +60,143 @@ const ProjectCard = (props: IProjectCard) => { const name = adminUser?.name; return ( - setIsHover(true)} - onMouseLeave={() => setIsHover(false)} - > - - - - - - - {title} - {adminUser && !isForeignOrg ? ( - - {name || '\u200C'} - - ) : ( - -
-
- )} - {htmlToText(description)} - - - Raised: ${Math.ceil(totalDonations as number)} - - - Last updated:{calcBiggestUnitDifferenceTime(updatedAt)} - - - - - - - - - - -
-
+ + setIsHover(true)} + onMouseLeave={() => setIsHover(false)} + > + + + + + + + {isHover && ( + + Last updated: + {calcBiggestUnitDifferenceTime(updatedAt)} + + )} + + {title} + + {adminUser && !isForeignOrg ? ( + + {name || '\u200C'} + + ) : ( + +
+
+ )} + {htmlToText(description)} + + + ${Math.ceil(totalDonations as number)} + + Raised + +
+ + {verified && ( + <> + + + VERIFIED + + + + + + GIVBACK ELIGIBLE + + + )} + + + + + + +
+
+ ); }; const DonateButton = styled(ButtonLink)` flex: 1; `; -const LearnMoreButton = styled(OutlineLinkButton)` - flex: 1; + +const CustomizedDonateButton = styled(DonateButton)` + margin: 25px 0; + ${mediaQueries.desktop} { + margin: 25px 12px; + } +`; + +const PriceText = styled(B)` + display: inline; + color: ${neutralColors.gray[800]}; +`; + +const RaisedText = styled(Subline)` + display: inline; + color: ${neutralColors.gray[700]}; +`; + +const VerifiedText = styled(Subline)` + color: ${semanticColors.jade[500]}; +`; + +const GivBackText = styled(Subline)` + color: ${brandColors.giv[500]}; +`; + +const GivBackIconContainer = styled.div` + display: flex; + align-items: center; + transform: scale(0.8); +`; + +const BadgesContainer = styled(Flex)` + min-height: 22px; +`; + +const LastUpdatedContainer = styled(Subline)` + display: inline; + background-color: ${neutralColors.gray[300]}; + color: ${neutralColors.gray[700]}; + padding: 2px 8px; + border-radius: 4px; `; const ActionButtons = styled(Row)` gap: 16px; `; -const Captions = styled(Flex)` - justify-content: space-between; - margin-bottom: 24px; - color: ${neutralColors.gray[700]}; - text-overflow: ellipsis; +const Hr = styled.hr` + border: 1px solid ${neutralColors.gray[300]}; `; const Description = styled(P)` - height: 120px; + height: 75px; overflow: hidden; color: ${neutralColors.gray[800]}; margin-bottom: 16px; @@ -143,11 +207,14 @@ const CardBody = styled.div` position: absolute; left: 0; right: 0; - top: ${(props: { isHover: boolean }) => - props.isHover ? '124px' : '200px'}; + top: 200px; background-color: ${neutralColors.gray[100]}; transition: top 0.3s ease; border-radius: 0 12px 12px 12px; + ${mediaQueries.desktop} { + top: ${(props: { isHover: boolean }) => + props.isHover ? '114px' : '200px'}; + } `; const Author = styled(GLink)` @@ -156,8 +223,9 @@ const Author = styled(GLink)` display: block; `; -const Title = styled(H6)` - color: ${brandColors.deep[700]}; +const Title = styled(H6)<{ isHover?: boolean }>` + color: ${props => + props.isHover ? brandColors.pinky[500] : brandColors.deep[700]}; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; @@ -179,8 +247,8 @@ const Wrapper = styled.div` overflow: hidden; box-shadow: ${Shadow.Neutral[400]}; height: 536px; - - ${mediaQueries.tablet} { + cursor: pointer; + ${mediaQueries.desktop} { height: 472px; } `; diff --git a/src/components/project-card/ProjectCardBadges.tsx b/src/components/project-card/ProjectCardBadges.tsx index fdeba30421..49c1ec873c 100644 --- a/src/components/project-card/ProjectCardBadges.tsx +++ b/src/components/project-card/ProjectCardBadges.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useState, MouseEvent } from 'react'; import { brandColors, IconHeart16, @@ -36,7 +36,7 @@ const ProjectCardBadges = (props: IProjectCardBadges) => { const [showModal, setShowModal] = useState(false); const { project } = props; - const { verified, traceCampaignId, slug, id: projectId } = project; + const { traceCampaignId, slug, id: projectId } = project; const [reaction, setReaction] = useState(project.reaction); const [totalReactions, setTotalReactions] = useState( @@ -44,7 +44,8 @@ const ProjectCardBadges = (props: IProjectCardBadges) => { ); const [loading, setLoading] = useState(false); - const likeUnlikeProject = async () => { + const likeUnlikeProject = async (e: MouseEvent) => { + e.stopPropagation(); if (!isSignedIn) { showSignWithWallet(); return; @@ -99,7 +100,7 @@ const ProjectCardBadges = (props: IProjectCardBadges) => { )} - {verified && } + {/* {verified && } */} {traceCampaignId && } @@ -113,7 +114,12 @@ const ProjectCardBadges = (props: IProjectCardBadges) => { )} - setShowModal(true)}> + { + e.stopPropagation(); + setShowModal(true); + }} + > From 77d264547f136cce09bbebd26c9edc0b103e86fc Mon Sep 17 00:00:00 2001 From: alireza-sharifpour Date: Mon, 16 May 2022 11:25:49 +0430 Subject: [PATCH 025/257] Removed verified.svg and added IconVerified component instead --- public/images/verified.svg | 3 --- src/components/badges/VerificationBadge.tsx | 11 +++++++---- src/components/project-card/ProjectCardBadges.tsx | 5 +---- 3 files changed, 8 insertions(+), 11 deletions(-) delete mode 100644 public/images/verified.svg diff --git a/public/images/verified.svg b/public/images/verified.svg deleted file mode 100644 index 0bb77ef131..0000000000 --- a/public/images/verified.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/components/badges/VerificationBadge.tsx b/src/components/badges/VerificationBadge.tsx index 0138f9ad5b..c40599db7e 100644 --- a/src/components/badges/VerificationBadge.tsx +++ b/src/components/badges/VerificationBadge.tsx @@ -1,18 +1,21 @@ import Image from 'next/image'; -import { Overline } from '@giveth/ui-design-system'; +import { IconVerified, Overline } from '@giveth/ui-design-system'; import styled from 'styled-components'; import { FlexCenter } from '../styled-components/Flex'; import TraceIcon from '/public//images/trace.svg'; -import VerifiedIcon from '/public//images/verified.svg'; const VerificationBadge = (props: { verified?: boolean; trace?: boolean }) => { const { verified, trace } = props; const text = verified ? 'VERIFIED' : trace ? 'TRACE' : ''; - const icon = verified ? VerifiedIcon : trace ? TraceIcon : ''; + return ( - badge icon + {verified ? ( + + ) : trace ? ( + badge icon + ) : null} {text} ); diff --git a/src/components/project-card/ProjectCardBadges.tsx b/src/components/project-card/ProjectCardBadges.tsx index 49c1ec873c..364a0804e9 100644 --- a/src/components/project-card/ProjectCardBadges.tsx +++ b/src/components/project-card/ProjectCardBadges.tsx @@ -99,10 +99,7 @@ const ProjectCardBadges = (props: IProjectCardBadges) => { )} - - {/* {verified && } */} - {traceCampaignId && } - + {traceCampaignId && } {Number(totalReactions) > 0 && ( From fe79ff24bdc2574382c2cc02bc9f6dcdd79a160f Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:17:45 +0430 Subject: [PATCH 026/257] remove subgraph provider --- pages/_app.tsx | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/pages/_app.tsx b/pages/_app.tsx index 418e63b27e..4b71962bed 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -20,7 +20,6 @@ import { FooterWrapper } from '@/components/Footer/FooterWrapper'; import '../styles/globals.css'; import { store } from '@/stores/store'; -import { SubgraphProvider } from '@/context/subgraph.context'; import type { AppProps } from 'next/app'; function getLibrary(provider: ExternalProvider) { @@ -63,21 +62,19 @@ function MyApp({ Component, pageProps }: AppProps) { - - - - - - - - - - - - - - - + + + + + + + + + + + + + From a37784779a3d22606b2eae0bb8b3903fcd3820cf Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:43:38 +0430 Subject: [PATCH 027/257] change subgraph types to seralizable types --- src/types/subgraph.ts | 154 +++++++++++++++++++++--------------------- 1 file changed, 76 insertions(+), 78 deletions(-) diff --git a/src/types/subgraph.ts b/src/types/subgraph.ts index 8bc564043d..31da0c011f 100644 --- a/src/types/subgraph.ts +++ b/src/types/subgraph.ts @@ -1,78 +1,76 @@ -import { constants, ethers } from 'ethers'; - export interface IBalances { - balance: ethers.BigNumber; - allocatedTokens: ethers.BigNumber; - claimed: ethers.BigNumber; - rewardPerTokenPaidGivLm: ethers.BigNumber; - rewardsGivLm: ethers.BigNumber; - rewardPerTokenPaidSushiSwap: ethers.BigNumber; - rewardsSushiSwap: ethers.BigNumber; - rewardPerTokenPaidHoneyswap: ethers.BigNumber; - rewardsHoneyswap: ethers.BigNumber; - rewardPerTokenPaidBalancer: ethers.BigNumber; - rewardsBalancer: ethers.BigNumber; - rewardPerTokenPaidUniswapV2GivDai: ethers.BigNumber; - rewardsUniswapV2GivDai: ethers.BigNumber; - givback: ethers.BigNumber; - givbackLiquidPart: ethers.BigNumber; - balancerLp: ethers.BigNumber; - balancerLpStaked: ethers.BigNumber; - uniswapV2GivDaiLp: ethers.BigNumber; - uniswapV2GivDaiLpStaked: ethers.BigNumber; - sushiswapLp: ethers.BigNumber; - sushiSwapLpStaked: ethers.BigNumber; - honeyswapLp: ethers.BigNumber; - honeyswapLpStaked: ethers.BigNumber; - givStaked: ethers.BigNumber; + balance: string; + allocatedTokens: string; + claimed: string; + rewardPerTokenPaidGivLm: string; + rewardsGivLm: string; + rewardPerTokenPaidSushiSwap: string; + rewardsSushiSwap: string; + rewardPerTokenPaidHoneyswap: string; + rewardsHoneyswap: string; + rewardPerTokenPaidBalancer: string; + rewardsBalancer: string; + rewardPerTokenPaidUniswapV2GivDai: string; + rewardsUniswapV2GivDai: string; + givback: string; + givbackLiquidPart: string; + balancerLp: string; + balancerLpStaked: string; + uniswapV2GivDaiLp: string; + uniswapV2GivDaiLpStaked: string; + sushiswapLp: string; + sushiSwapLpStaked: string; + honeyswapLp: string; + honeyswapLpStaked: string; + givStaked: string; allocationCount: number; givDropClaimed: boolean; - foxAllocatedTokens: ethers.BigNumber; - foxClaimed: ethers.BigNumber; - rewardPerTokenPaidFoxHnyLm: ethers.BigNumber; - rewardsFoxHnyLm: ethers.BigNumber; - foxHnyLp: ethers.BigNumber; - foxHnyLpStaked: ethers.BigNumber; + foxAllocatedTokens: string; + foxClaimed: string; + rewardPerTokenPaidFoxHnyLm: string; + rewardsFoxHnyLm: string; + foxHnyLp: string; + foxHnyLpStaked: string; } export const ZeroBalances: IBalances = { - balance: constants.Zero, - allocatedTokens: constants.Zero, - claimed: constants.Zero, - rewardPerTokenPaidGivLm: constants.Zero, - rewardsGivLm: constants.Zero, - rewardPerTokenPaidSushiSwap: constants.Zero, - rewardsSushiSwap: constants.Zero, - rewardPerTokenPaidHoneyswap: constants.Zero, - rewardsHoneyswap: constants.Zero, - rewardPerTokenPaidBalancer: constants.Zero, - rewardsBalancer: constants.Zero, - rewardPerTokenPaidUniswapV2GivDai: constants.Zero, - rewardsUniswapV2GivDai: constants.Zero, - givback: constants.Zero, - givbackLiquidPart: constants.Zero, - balancerLp: constants.Zero, - balancerLpStaked: constants.Zero, - uniswapV2GivDaiLp: constants.Zero, - uniswapV2GivDaiLpStaked: constants.Zero, - sushiswapLp: constants.Zero, - sushiSwapLpStaked: constants.Zero, - honeyswapLp: constants.Zero, - honeyswapLpStaked: constants.Zero, - givStaked: constants.Zero, + balance: '0', + allocatedTokens: '0', + claimed: '0', + rewardPerTokenPaidGivLm: '0', + rewardsGivLm: '0', + rewardPerTokenPaidSushiSwap: '0', + rewardsSushiSwap: '0', + rewardPerTokenPaidHoneyswap: '0', + rewardsHoneyswap: '0', + rewardPerTokenPaidBalancer: '0', + rewardsBalancer: '0', + rewardPerTokenPaidUniswapV2GivDai: '0', + rewardsUniswapV2GivDai: '0', + givback: '0', + givbackLiquidPart: '0', + balancerLp: '0', + balancerLpStaked: '0', + uniswapV2GivDaiLp: '0', + uniswapV2GivDaiLpStaked: '0', + sushiswapLp: '0', + sushiSwapLpStaked: '0', + honeyswapLp: '0', + honeyswapLpStaked: '0', + givStaked: '0', allocationCount: 0, givDropClaimed: false, - foxAllocatedTokens: constants.Zero, - foxClaimed: constants.Zero, - rewardPerTokenPaidFoxHnyLm: constants.Zero, - rewardsFoxHnyLm: constants.Zero, - foxHnyLp: constants.Zero, - foxHnyLpStaked: constants.Zero, + foxAllocatedTokens: '0', + foxClaimed: '0', + rewardPerTokenPaidFoxHnyLm: '0', + rewardsFoxHnyLm: '0', + foxHnyLp: '0', + foxHnyLpStaked: '0', }; export interface ITokenAllocation { - amount: ethers.BigNumber; + amount: string; distributor: string; recipient: string; timestamp: string; @@ -81,27 +79,27 @@ export interface ITokenAllocation { export interface ITokenDistroInfo { contractAddress: string; - initialAmount: ethers.BigNumber; - lockedAmount: ethers.BigNumber; - totalTokens: ethers.BigNumber; - startTime: Date; - cliffTime: Date; - endTime: Date; + initialAmount: string; + lockedAmount: string; + totalTokens: string; + startTime: number; + cliffTime: number; + endTime: number; } export interface IUnipool { - totalSupply: ethers.BigNumber; + totalSupply: string; lastUpdateTime: number; periodFinish: number; - rewardPerTokenStored: ethers.BigNumber; - rewardRate: ethers.BigNumber; + rewardPerTokenStored: string; + rewardRate: string; } export interface IUniswapV3Position { tokenId: number; token0: string; token1: string; - liquidity: ethers.BigNumber; + liquidity: string; tickLower: number; tickUpper: number; owner: string; @@ -110,21 +108,21 @@ export interface IUniswapV3Position { } export interface IInfinitePositionReward { - lastRewardAmount: ethers.BigNumber; + lastRewardAmount: string; lastUpdateTimeStamp: number; } export interface IUniswapV3Pool { token0: string; token1: string; - sqrtPriceX96: ethers.BigNumber; + sqrtPriceX96: string; tick: number; - liquidity: ethers.BigNumber; + liquidity: string; } export interface IUniswapV2Pair { token0: string; token1: string; - reserve0: ethers.BigNumber; - reserve1: ethers.BigNumber; + reserve0: string; + reserve1: string; } From 35f8fc258b64fa4d74a038e38157691ee7526cce Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:44:11 +0430 Subject: [PATCH 028/257] update RegenStreamCard to use redux --- src/components/RegenStreamCard.tsx | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/components/RegenStreamCard.tsx b/src/components/RegenStreamCard.tsx index b7e15b61c1..6b1f544e99 100644 --- a/src/components/RegenStreamCard.tsx +++ b/src/components/RegenStreamCard.tsx @@ -16,6 +16,7 @@ import { import { constants, ethers } from 'ethers'; import BigNumber from 'bignumber.js'; import styled from 'styled-components'; +import { useSelector } from 'react-redux'; import { useTokenDistro } from '@/context/tokenDistro.context'; import { durationToString } from '@/lib/helpers'; import { @@ -25,12 +26,12 @@ import { } from '@/components/homeTabs/GIVstream.sc'; import { IconWithTooltip } from '@/components/IconWithToolTip'; import { RegenStreamConfig, StreamType } from '@/types/config'; -import { useSubgraph } from '@/context'; -import { formatWeiHelper } from '@/helpers/number'; +import { BN, formatWeiHelper } from '@/helpers/number'; import { IconFox } from '@/components/Icons/Fox'; import { Flex } from './styled-components/Flex'; import { HarvestAllModal } from './modals/HarvestAll'; import { usePrice } from '@/context/price.context'; +import { RootState } from '@/stores/store'; interface RegenStreamProps { network: number; @@ -61,9 +62,9 @@ export const RegenStreamCard: FC = ({ const [claimedAmount, setClaimedAmount] = useState( constants.Zero, ); - const { - currentValues: { balances }, - } = useSubgraph(); + const { balances } = useSelector( + (state: RootState) => state.subgraph.currentValues, + ); const tokenDistroHelper = regenTokenDistroHelpers[streamConfig.type]; const { getTokenPrice } = usePrice(); @@ -89,8 +90,8 @@ export const RegenStreamCard: FC = ({ useEffect(() => { switch (streamConfig.type) { case StreamType.FOX: - setLockedAmount(balances.foxAllocatedTokens); - setClaimedAmount(balances.foxClaimed); + setLockedAmount(BN(balances.foxAllocatedTokens)); + setClaimedAmount(BN(balances.foxClaimed)); break; default: setLockedAmount(ethers.constants.Zero); From e60a605f22258ad8a49c8d5ec98fc093beb81e79 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:44:30 +0430 Subject: [PATCH 029/257] update GovernCard to use redux --- src/components/cards/Govern.tsx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/components/cards/Govern.tsx b/src/components/cards/Govern.tsx index 2174b387d9..93611184b2 100644 --- a/src/components/cards/Govern.tsx +++ b/src/components/cards/Govern.tsx @@ -5,6 +5,7 @@ import { utils, BigNumber as EthersBigNumber, constants } from 'ethers'; import styled from 'styled-components'; import { H2, H5, Lead } from '@giveth/ui-design-system'; import { captureException } from '@sentry/nextjs'; +import { useSelector } from 'react-redux'; import { APRRow, ArrowButton, @@ -30,9 +31,9 @@ import { formatEthHelper, formatWeiHelper, Zero } from '@/helpers/number'; import { getGivStakingAPR } from '@/lib/stakingPool'; import { APR } from '@/types/poolInfo'; import { useTokenDistro } from '@/context/tokenDistro.context'; -import { useSubgraph } from '@/context'; import { StakingType } from '@/types/config'; import useClaim from '@/context/claim.context'; +import { RootState } from '@/stores/store'; const GovernCardContainer = styled(Card)` padding-left: 254px; @@ -107,7 +108,9 @@ const GovernCard: FC = ({ index }) => { const [earnEstimate, setEarnEstimate] = useState(Zero); const [apr, setApr] = useState(null); const { givTokenDistroHelper } = useTokenDistro(); - const { xDaiValues } = useSubgraph(); + const xDaiValues = useSelector( + (state: RootState) => state.subgraph.xDaiValues, + ); useEffect(() => { let _stacked = 0; From 86a121f224619d521ad4dc50830976b5f0f890dd Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:45:09 +0430 Subject: [PATCH 030/257] update InvestCard to use redux --- src/components/cards/Stake.tsx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/components/cards/Stake.tsx b/src/components/cards/Stake.tsx index 3167dcb275..a389beb2c2 100644 --- a/src/components/cards/Stake.tsx +++ b/src/components/cards/Stake.tsx @@ -4,6 +4,7 @@ import styled from 'styled-components'; import { BigNumber as EthersBigNumber, constants, utils } from 'ethers'; import BigNumber from 'bignumber.js'; import { H2, H5, Lead } from '@giveth/ui-design-system'; +import { useSelector } from 'react-redux'; import { InputWithUnit } from '../input/index'; import { Flex } from '../styled-components/Flex'; import { @@ -29,10 +30,10 @@ import config from '@/configuration'; import { formatEthHelper, formatWeiHelper, Zero } from '@/helpers/number'; import { APR } from '@/types/poolInfo'; import { getLPStakingAPR } from '@/lib/stakingPool'; -import { useSubgraph } from '@/context'; import { useTokenDistro } from '@/context/tokenDistro.context'; import { networkProviders } from '@/helpers/networkProvider'; import { StakingType } from '@/types/config'; +import { RootState } from '@/stores/store'; const InvestCardContainer = styled(Card)` ::before { @@ -95,7 +96,9 @@ const InvestCard: FC = ({ index }) => { const [earnEstimate, setEarnEstimate] = useState(Zero); const [APR, setAPR] = useState(Zero); const { givTokenDistroHelper } = useTokenDistro(); - const { mainnetValues, xDaiValues } = useSubgraph(); + const { xDaiValues, mainnetValues } = useSelector( + (state: RootState) => state.subgraph, + ); useEffect(() => { if (totalAmount) { From ed9425bbd88d2e95017caecfd136a43815cf3697 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:46:46 +0430 Subject: [PATCH 031/257] update TabGIV to use redux --- src/components/homeTabs/GIVbacks.tsx | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/components/homeTabs/GIVbacks.tsx b/src/components/homeTabs/GIVbacks.tsx index 6a1285891f..646b665da8 100644 --- a/src/components/homeTabs/GIVbacks.tsx +++ b/src/components/homeTabs/GIVbacks.tsx @@ -7,6 +7,7 @@ import { } from '@giveth/ui-design-system'; import BigNumber from 'bignumber.js'; import { useWeb3React } from '@web3-react/core'; +import { useSelector } from 'react-redux'; import { Flex } from '../styled-components/Flex'; import { GIVbacksTopContainer, @@ -34,27 +35,29 @@ import { useTokenDistro } from '@/context/tokenDistro.context'; import config from '@/configuration'; import { HarvestAllModal } from '../modals/HarvestAll'; import { getNowUnixMS } from '@/helpers/time'; -import { useSubgraph } from '@/context'; import { formatDate } from '@/lib/helpers'; import { GIVBackExplainModal } from '../modals/GIVBackExplain'; import { TopInnerContainer } from './commons'; import links from '@/lib/constants/links'; import { Col, Container, Row } from '@/components/Grid'; import Routes from '@/lib/constants/Routes'; +import { RootState } from '@/stores/store'; +import { BN } from '@/helpers/number'; export const TabGIVbacksTop = () => { const [showHarvestModal, setShowHarvestModal] = useState(false); const [showGivBackExplain, setShowGivBackExplain] = useState(false); const [givBackStream, setGivBackStream] = useState(0); const { givTokenDistroHelper } = useTokenDistro(); - const { - currentValues: { balances }, - } = useSubgraph(); + const { balances } = useSelector( + (state: RootState) => state.subgraph.currentValues, + ); const { chainId } = useWeb3React(); useEffect(() => { + const _givback = BN(balances.givback); setGivBackStream( - givTokenDistroHelper.getStreamPartTokenPerWeek(balances.givback), + givTokenDistroHelper.getStreamPartTokenPerWeek(_givback), ); }, [balances, givTokenDistroHelper]); @@ -78,14 +81,14 @@ export const TabGIVbacksTop = () => { { setShowHarvestModal(true); }} subButtonLabel={ - balances?.givbackLiquidPart?.isZero() + BN(balances?.givbackLiquidPart)?.isZero() ? "Why don't I have GIVbacks?" : undefined } From f7c12173f7506d736c917621c9e6e784965b2706 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:47:16 +0430 Subject: [PATCH 032/257] update TabGIVstream to use redux --- src/components/homeTabs/GIVstream.tsx | 38 ++++++++++++++++----------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/src/components/homeTabs/GIVstream.tsx b/src/components/homeTabs/GIVstream.tsx index 4cb259987b..d79157e79e 100644 --- a/src/components/homeTabs/GIVstream.tsx +++ b/src/components/homeTabs/GIVstream.tsx @@ -18,6 +18,7 @@ import { constants, ethers } from 'ethers'; import BigNumber from 'bignumber.js'; import { Zero } from '@ethersproject/constants'; import { useWeb3React } from '@web3-react/core'; +import { useSelector } from 'react-redux'; import { Bar, FlowRateRow, @@ -52,13 +53,12 @@ import { } from './GIVstream.sc'; import { IconWithTooltip } from '../IconWithToolTip'; import { getHistory } from '@/services/subgraph.service'; -import { formatWeiHelper } from '@/helpers/number'; +import { BN, formatWeiHelper } from '@/helpers/number'; import config from '@/configuration'; import { durationToString } from '@/lib/helpers'; import { NetworkSelector } from '@/components/NetworkSelector'; import { useTokenDistro } from '@/context/tokenDistro.context'; import { HarvestAllModal } from '../modals/HarvestAll'; -import { useSubgraph } from '@/context'; import { ITokenAllocation } from '@/types/subgraph'; import { IconGIV } from '../Icons/GIV'; import { givEconomySupportedNetworks } from '@/lib/constants/constants'; @@ -66,27 +66,32 @@ import { Flex } from '../styled-components/Flex'; import Pagination from '../Pagination'; import { Container, Row, Col } from '@/components/Grid'; import GivEconomyProjectCards from '../cards/GivEconomyProjectCards'; +import { RootState } from '@/stores/store'; export const TabGIVstreamTop = () => { const [showModal, setShowModal] = useState(false); const [rewardLiquidPart, setRewardLiquidPart] = useState(constants.Zero); const [rewardStream, setRewardStream] = useState(0); const { givTokenDistroHelper } = useTokenDistro(); - const { - currentValues: { balances }, - } = useSubgraph(); + const { balances } = useSelector( + (state: RootState) => state.subgraph.currentValues, + ); const { allocatedTokens, claimed, givback } = balances; const { chainId } = useWeb3React(); useEffect(() => { + const _allocatedTokens = BN(allocatedTokens); + const _givback = BN(givback); + const _claimed = BN(claimed); + setRewardLiquidPart( givTokenDistroHelper - .getLiquidPart(allocatedTokens.sub(givback)) - .sub(claimed), + .getLiquidPart(_allocatedTokens.sub(_givback)) + .sub(_claimed), ); setRewardStream( givTokenDistroHelper.getStreamPartTokenPerWeek( - allocatedTokens.sub(givback), + _allocatedTokens.sub(givback), ), ); }, [allocatedTokens, claimed, givback, givTokenDistroHelper]); @@ -147,15 +152,18 @@ export const TabGIVstreamBottom = () => { const [streamAmount, setStreamAmount] = useState( new BigNumber(0), ); - const { - currentValues: { balances }, - } = useSubgraph(); + const { balances } = useSelector( + (state: RootState) => state.subgraph.currentValues, + ); const increaseSecRef = useRef(null); useEffect(() => { + const _allocatedTokens = BN(balances.allocatedTokens); + const _givback = BN(balances.givback); + setStreamAmount( givTokenDistroHelper.getStreamPartTokenPerWeek( - balances.allocatedTokens.sub(balances.givback), + _allocatedTokens.sub(_givback), ), ); }, [balances.allocatedTokens, balances.givback, givTokenDistroHelper]); @@ -335,9 +343,9 @@ export const GIVstreamHistory: FC = () => { >([]); const [loading, setLoading] = useState(true); const [page, setPage] = useState(0); - const { - currentValues: { balances }, - } = useSubgraph(); + const { balances } = useSelector( + (state: RootState) => state.subgraph.currentValues, + ); const { allocationCount } = balances; const { givTokenDistroHelper } = useTokenDistro(); From 7212d1bc00aa746cc1d0387b43a4b1d2cb24c5c2 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:47:53 +0430 Subject: [PATCH 033/257] update RewardMenu to use redux --- src/components/menu/RewardMenu.tsx | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/src/components/menu/RewardMenu.tsx b/src/components/menu/RewardMenu.tsx index 73ae362ab9..603af8438c 100644 --- a/src/components/menu/RewardMenu.tsx +++ b/src/components/menu/RewardMenu.tsx @@ -16,20 +16,21 @@ import { Zero } from '@ethersproject/constants'; import Link from 'next/link'; import { constants } from 'ethers'; import { useWeb3React } from '@web3-react/core'; +import { useSelector } from 'react-redux'; import { Flex } from '../styled-components/Flex'; import { MenuContainer } from './Menu.sc'; import { switchNetworkHandler } from '@/lib/wallet'; import config from '@/configuration'; import { useTokenDistro } from '@/context/tokenDistro.context'; -import { formatWeiHelper } from '@/helpers/number'; +import { BN, formatWeiHelper } from '@/helpers/number'; import { WhatisStreamModal } from '@/components/modals/WhatisStream'; -import { useSubgraph } from '@/context'; import { getGivStakingConfig } from '@/helpers/networkProvider'; import { UnipoolHelper } from '@/lib/contractHelper/UnipoolHelper'; import { getUserStakeInfo } from '@/lib/stakingPool'; import { ETheme, useGeneral } from '@/context/general.context'; import Routes from '@/lib/constants/Routes'; import { networkInfo } from '@/lib/helpers'; +import { RootState } from '@/stores/store'; interface IRewardMenu { showWhatIsGIVstreamModal: boolean; @@ -45,27 +46,31 @@ export const RewardMenu = ({ const [givStreamLiquidPart, setGIVstreamLiquidPart] = useState(Zero); const [flowRateNow, setFlowRateNow] = useState(0); + const currentValues = useSelector( + (state: RootState) => state.subgraph.currentValues, + ); const { givTokenDistroHelper } = useTokenDistro(); - const { currentValues } = useSubgraph(); const { chainId } = useWeb3React(); const { theme } = useGeneral(); - const { balances } = currentValues; - const { allocatedTokens, claimed, givbackLiquidPart } = balances; + const { givbackLiquidPart } = currentValues.balances; const { networkName } = networkInfo(chainId); useEffect(() => { + const _allocatedTokens = BN(currentValues.balances.allocatedTokens); + const _givbackLiquidPart = BN(currentValues.balances.givbackLiquidPart); + const _claimed = BN(currentValues.balances.claimed); setGIVstreamLiquidPart( givTokenDistroHelper - .getLiquidPart(allocatedTokens.sub(givbackLiquidPart)) - .sub(claimed), + .getLiquidPart(_allocatedTokens.sub(_givbackLiquidPart)) + .sub(_claimed), ); setFlowRateNow( givTokenDistroHelper.getStreamPartTokenPerWeek( - allocatedTokens.sub(givbackLiquidPart), + _allocatedTokens.sub(_givbackLiquidPart), ), ); - }, [allocatedTokens, claimed, givbackLiquidPart, givTokenDistroHelper]); + }, [currentValues, givTokenDistroHelper]); useEffect(() => { let pools; @@ -91,7 +96,7 @@ export const RewardMenu = ({ getUserStakeInfo( type, undefined, - balances, + currentValues.balances, unipoolHelper, ).earned, ); @@ -101,7 +106,7 @@ export const RewardMenu = ({ givTokenDistroHelper.getLiquidPart(_farmRewards), ); } - }, [balances, currentValues, chainId, givTokenDistroHelper]); + }, [currentValues, chainId, givTokenDistroHelper]); useEffect(() => { setIsMounted(true); From b4268ce32b4cb35861e34ce033acc17238761b0c Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:48:10 +0430 Subject: [PATCH 034/257] update HarvestAllModal to use redux --- src/components/modals/HarvestAll.tsx | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/components/modals/HarvestAll.tsx b/src/components/modals/HarvestAll.tsx index 51f60e4486..7a04b60db9 100644 --- a/src/components/modals/HarvestAll.tsx +++ b/src/components/modals/HarvestAll.tsx @@ -14,6 +14,7 @@ import { ethers } from 'ethers'; import BigNumber from 'bignumber.js'; import { useWeb3React } from '@web3-react/core'; import { captureException } from '@sentry/nextjs'; +import { useSelector } from 'react-redux'; import { IModal, Modal } from './Modal'; import LoadingAnimation from '@/animations/loading.json'; import { @@ -21,8 +22,7 @@ import { RegenStreamConfig, StreamType, } from '@/types/config'; -import { formatWeiHelper, Zero } from '@/helpers/number'; -import { useSubgraph } from '@/context/subgraph.context'; +import { BN, formatWeiHelper, Zero } from '@/helpers/number'; import { useTokenDistro } from '@/context/tokenDistro.context'; import { harvestTokens } from '@/lib/stakingPool'; import { claimUnstakeStake } from '@/lib/stakingNFT'; @@ -63,6 +63,7 @@ import { IconWithTooltip } from '../IconWithToolTip'; import { AmountBoxWithPrice } from '@/components/AmountBoxWithPrice'; import { usePrice } from '@/context/price.context'; import { getPoolIconWithName } from '../cards/BaseStakingCard'; +import { RootState } from '@/stores/store'; interface IHarvestAllModalProps extends IModal { title: string; @@ -99,9 +100,9 @@ export const HarvestAllModal: FC = ({ }) => { const [state, setState] = useState(HarvestStates.HARVEST); const tokenSymbol = regenStreamConfig?.rewardTokenSymbol || 'GIV'; - const { - currentValues: { balances }, - } = useSubgraph(); + const { balances } = useSelector( + (state: RootState) => state.subgraph.currentValues, + ); const { getTokenDistroHelper } = useTokenDistro(); const { givPrice, getTokenPrice } = usePrice(); const { account, library } = useWeb3React(); @@ -129,12 +130,12 @@ export const HarvestAllModal: FC = ({ [getTokenDistroHelper, regenStreamConfig], ); const givback = useMemo(() => { - return regenStreamConfig ? ethers.constants.Zero : balances.givback; + return regenStreamConfig ? ethers.constants.Zero : BN(balances.givback); }, [regenStreamConfig, balances.givback]); const givbackLiquidPart = useMemo(() => { return regenStreamConfig ? ethers.constants.Zero - : balances.givbackLiquidPart; + : BN(balances.givbackLiquidPart); }, [regenStreamConfig, balances.givbackLiquidPart]); const tokenPrice = useMemo(() => { return regenStreamConfig @@ -143,6 +144,7 @@ export const HarvestAllModal: FC = ({ }, [getTokenPrice, givPrice, network, regenStreamConfig]); useEffect(() => { + const bnAllocatedTokens = BN(balances.allocatedTokens); if (earned) { setRewardLiquidPart(tokenDistroHelper.getLiquidPart(earned)); setEarnedStream( @@ -154,13 +156,13 @@ export const HarvestAllModal: FC = ({ if (regenStreamConfig) { switch (regenStreamConfig.type) { case StreamType.FOX: - lockedAmount = balances.foxAllocatedTokens; + lockedAmount = BN(balances.foxAllocatedTokens); break; default: lockedAmount = ethers.constants.Zero; } } else { - lockedAmount = balances.allocatedTokens.sub(givback); + lockedAmount = bnAllocatedTokens.sub(givback); } setRewardStream( tokenDistroHelper.getStreamPartTokenPerWeek(lockedAmount), From add6b4b72452d1970aff1e67aa061432c0ddb309 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:48:49 +0430 Subject: [PATCH 035/257] update V3StakeModal to use redux --- src/components/modals/V3Stake.tsx | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/components/modals/V3Stake.tsx b/src/components/modals/V3Stake.tsx index 4e0354a55d..362534a681 100644 --- a/src/components/modals/V3Stake.tsx +++ b/src/components/modals/V3Stake.tsx @@ -12,13 +12,14 @@ import styled from 'styled-components'; import { BigNumber, constants } from 'ethers'; import { useWeb3React } from '@web3-react/core'; import { captureException } from '@sentry/nextjs'; +import { useSelector } from 'react-redux'; import { IModal, Modal } from './Modal'; import { CancelButton, HarvestButton, HelpRow, Pending } from './HarvestAll.sc'; import { Flex } from '../styled-components/Flex'; import { PoolStakingConfig } from '@/types/config'; import { StakingPoolImages } from '../StakingPoolImages'; import V3StakingCard from '../cards/PositionCard'; -import { useLiquidityPositions, useSubgraph } from '@/context'; +import { useLiquidityPositions } from '@/context'; import LoadingAnimation from '@/animations/loading.json'; import { exit, getReward, transfer } from '@/lib/stakingNFT'; import { @@ -29,6 +30,8 @@ import { import { useTokenDistro } from '@/context/tokenDistro.context'; import { getUniswapV3StakerContract } from '@/lib/contracts'; import { StakeState } from '@/lib/staking'; +import { RootState } from '@/stores/store'; +import { BN } from '@/helpers/number'; const loadingAnimationOptions = { loop: true, @@ -49,9 +52,9 @@ export const V3StakeModal: FC = ({ isUnstakingModal, setShowModal, }) => { - const { - currentValues: { balances }, - } = useSubgraph(); + const { balances } = useSelector( + (state: RootState) => state.subgraph.currentValues, + ); const { givTokenDistroHelper } = useTokenDistro(); const { chainId, library, account } = useWeb3React(); const { unstakedPositions, stakedPositions, currentIncentive } = @@ -111,7 +114,7 @@ export const V3StakeModal: FC = ({ const handleAction = async (tokenId: number) => { const uniswapV3StakerContract = getUniswapV3StakerContract(library); if (!library || !uniswapV3StakerContract) return; - + const bnGIVback = BN(balances.givback); const _reward = await getReward( tokenId, uniswapV3StakerContract, @@ -125,9 +128,7 @@ export const V3StakeModal: FC = ({ setReward(liquidReward); setStream(BigNumber.from(streamPerWeek.toFixed(0))); setClaimableNow(givTokenDistroHelper.getUserClaimableNow(balances)); - setGivBackLiquidPart( - givTokenDistroHelper.getLiquidPart(balances.givback), - ); + setGivBackLiquidPart(givTokenDistroHelper.getLiquidPart(bnGIVback)); // setStakeStatus(StakeState.UNSTAKING); }; From aa2c553825d216f4cf9eae265a3e8436a5eea1f5 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:49:09 +0430 Subject: [PATCH 036/257] update GIVdropHarvestModal to use redux --- src/components/modals/GIVdropHarvestModal.tsx | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/components/modals/GIVdropHarvestModal.tsx b/src/components/modals/GIVdropHarvestModal.tsx index 97103a9ccc..e31044f265 100644 --- a/src/components/modals/GIVdropHarvestModal.tsx +++ b/src/components/modals/GIVdropHarvestModal.tsx @@ -14,6 +14,7 @@ import Lottie from 'react-lottie'; import styled from 'styled-components'; import { useWeb3React } from '@web3-react/core'; import { captureException } from '@sentry/nextjs'; +import { useSelector } from 'react-redux'; import { IModal, Modal } from './Modal'; import { ConfirmedInnerModal, @@ -32,7 +33,7 @@ import { RateRow, TooltipContent, } from './HarvestAll.sc'; -import { formatWeiHelper } from '@/helpers/number'; +import { BN, formatWeiHelper } from '@/helpers/number'; import { IconWithTooltip } from '../IconWithToolTip'; import { AmountBoxWithPrice } from '../AmountBoxWithPrice'; import { useTokenDistro } from '@/context/tokenDistro.context'; @@ -44,8 +45,8 @@ import { showFailedClaim, } from '../toasts/claim'; import config from '@/configuration'; -import { useSubgraph } from '@/context'; import { usePrice } from '@/context/price.context'; +import { RootState } from '@/stores/store'; import type { TransactionResponse } from '@ethersproject/providers'; const loadingAnimationOptions = { @@ -91,20 +92,19 @@ export const GIVdropHarvestModal: FC = ({ ClaimState.UNKNOWN, ); const { givTokenDistroHelper } = useTokenDistro(); - const { - currentValues: { balances }, - } = useSubgraph(); + const { balances } = useSelector( + (state: RootState) => state.subgraph.currentValues, + ); const { givPrice } = usePrice(); const { account, library } = useWeb3React(); useEffect(() => { + const bnGIVback = BN(balances.givback); setClaimableNow(givTokenDistroHelper.getUserClaimableNow(balances)); - setGivBackLiquidPart( - givTokenDistroHelper.getLiquidPart(balances.givback), - ); + setGivBackLiquidPart(givTokenDistroHelper.getLiquidPart(bnGIVback)); setGivBackStream( - givTokenDistroHelper.getStreamPartTokenPerWeek(balances.givback), + givTokenDistroHelper.getStreamPartTokenPerWeek(bnGIVback), ); }, [balances, givTokenDistroHelper]); @@ -249,7 +249,7 @@ export const GIVdropHarvestModal: FC = ({ )} - {!balances.givback.isZero() && ( + {!BN(balances.givback).isZero() && ( <> Claimable from GIVbacks From 3d8edb0b01f33c72ff2c8768d650df30055b0aa2 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:49:46 +0430 Subject: [PATCH 037/257] update NftsProvider to use redux --- src/context/positions.context.tsx | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/context/positions.context.tsx b/src/context/positions.context.tsx index 097cf4eac0..8db61ad2b3 100644 --- a/src/context/positions.context.tsx +++ b/src/context/positions.context.tsx @@ -14,13 +14,14 @@ import { Token } from '@uniswap/sdk-core'; import BigNumber from 'bignumber.js'; import { useWeb3React } from '@web3-react/core'; import { captureException } from '@sentry/nextjs'; +import { useSelector } from 'react-redux'; import { LiquidityPosition } from '@/types/nfts'; import config from '@/configuration'; import { StakingType, UniswapV3PoolStakingConfig } from '@/types/config'; import { getUniswapV3TokenURI } from '@/services/subgraph.service'; import { Zero } from '@/helpers/number'; import { IUniswapV3Position } from '@/types/subgraph'; -import { useSubgraph } from '.'; +import { RootState } from '@/stores/store'; const ERC721NftContext = createContext<{ stakedPositions: LiquidityPosition[]; @@ -43,10 +44,12 @@ const { INCENTIVE_REWARD_AMOUNT, INCENTIVE_START_TIME, INCENTIVE_END_TIME } = uniswapV3PoolStakingConfig || {}; export const NftsProvider: FC<{ children: ReactNode }> = ({ children }) => { - const network = config.MAINNET_NETWORK_NUMBER; - const { mainnetValues } = useSubgraph(); + const mainnetValues = useSelector( + (state: RootState) => state.subgraph.mainnetValues, + ); const { chainId, library } = useWeb3React(); + const network = config.MAINNET_NETWORK_NUMBER; const { userStakedPositions, userNotStakedPositions, From 1d11f6c057fb603ca6ef0aa222aaa9643e4384af Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:50:16 +0430 Subject: [PATCH 038/257] update PriceProvider to use redux --- src/context/price.context.tsx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/context/price.context.tsx b/src/context/price.context.tsx index 84007deddd..4fa9ad6991 100644 --- a/src/context/price.context.tsx +++ b/src/context/price.context.tsx @@ -9,10 +9,11 @@ import { import BigNumber from 'bignumber.js'; import { useWeb3React } from '@web3-react/core'; import { captureException } from '@sentry/nextjs'; +import { useSelector } from 'react-redux'; import { Zero } from '@/helpers/number'; -import { useSubgraph } from '@/context/subgraph.context'; import config from '@/configuration'; import { useLiquidityPositions } from '@/context/positions.context'; +import { RootState } from '@/stores/store'; export interface IPriceContext { givPrice: BigNumber; @@ -64,7 +65,9 @@ PriceContext.displayName = 'PriceContext'; export const PriceProvider: FC = ({ children }) => { const { chainId } = useWeb3React(); - const { xDaiValues } = useSubgraph(); + const xDaiValues = useSelector( + (state: RootState) => state.subgraph.xDaiValues, + ); const { pool } = useLiquidityPositions(); const [currentPrice, setCurrentPrice] = useState(Zero); From 89f7fdb2faf4d7bdde38e00d455d6512a9f2622f Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:50:54 +0430 Subject: [PATCH 039/257] update TokenDistroProvider to use redux --- src/context/tokenDistro.context.tsx | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/context/tokenDistro.context.tsx b/src/context/tokenDistro.context.tsx index 0b5bd71781..5aec1b2903 100644 --- a/src/context/tokenDistro.context.tsx +++ b/src/context/tokenDistro.context.tsx @@ -6,12 +6,13 @@ import { useEffect, useState, } from 'react'; -import { Zero, AddressZero } from '@ethersproject/constants'; +import { AddressZero } from '@ethersproject/constants'; import { useWeb3React } from '@web3-react/core'; +import { useSelector } from 'react-redux'; import config from '@/configuration'; import { TokenDistroHelper } from '@/lib/contractHelper/TokenDistroHelper'; -import { useSubgraph } from '@/context/subgraph.context'; import { StreamType } from '@/types/config'; +import { RootState } from '@/stores/store'; export interface IRegenTokenDistroHelpers { [key: string]: TokenDistroHelper; @@ -26,12 +27,12 @@ export interface ITokenDistroContext { const defaultTokenDistroHelper = new TokenDistroHelper({ contractAddress: AddressZero, - initialAmount: Zero, - lockedAmount: Zero, - totalTokens: Zero, - startTime: new Date(), - cliffTime: new Date(), - endTime: new Date(), + initialAmount: '0', + lockedAmount: '0', + totalTokens: '0', + startTime: 0, + cliffTime: 0, + endTime: 0, }); export const TokenDistroContext = createContext({ @@ -45,8 +46,6 @@ TokenDistroContext.displayName = 'TokenDistroContext'; export const TokenDistroProvider: FC = ({ children }) => { const { chainId } = useWeb3React(); - const { mainnetValues, xDaiValues } = useSubgraph(); - const [currentGivTokenDistroInfo, setCurrentGivTokenDistroInfo] = useState(defaultTokenDistroHelper); const [mainnetGivTokenDistro, setMainnetGivTokenDistro] = @@ -61,6 +60,10 @@ export const TokenDistroProvider: FC = ({ children }) => { const [xDaiRegenTokenDistroHelpers, setXDaiRegenTokenDistroHelpers] = useState({}); + const { mainnetValues, xDaiValues } = useSelector( + (state: RootState) => state.subgraph, + ); + useEffect(() => { if (mainnetValues?.tokenDistroInfo) setMainnetGivTokenDistro( From 722e00ca8a1fee08ee08b66b7bc1b1398f259239 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:51:59 +0430 Subject: [PATCH 040/257] add store --- src/stores/hooks.ts | 6 ++ src/stores/store.ts | 17 +++-- src/stores/subgraph-api-slice.ts | 45 ------------- src/stores/subgraph.store.ts | 107 ++++++++++++++++++++++++------- 4 files changed, 101 insertions(+), 74 deletions(-) create mode 100644 src/stores/hooks.ts delete mode 100644 src/stores/subgraph-api-slice.ts diff --git a/src/stores/hooks.ts b/src/stores/hooks.ts new file mode 100644 index 0000000000..520e84ed52 --- /dev/null +++ b/src/stores/hooks.ts @@ -0,0 +1,6 @@ +import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'; +import type { RootState, AppDispatch } from './store'; + +// Use throughout your app instead of plain `useDispatch` and `useSelector` +export const useAppDispatch = () => useDispatch(); +export const useAppSelector: TypedUseSelectorHook = useSelector; diff --git a/src/stores/store.ts b/src/stores/store.ts index b73a81c2c5..42d78ca51c 100644 --- a/src/stores/store.ts +++ b/src/stores/store.ts @@ -1,13 +1,10 @@ -import { configureStore } from '@reduxjs/toolkit'; -import { subgraphApiSlice } from './subgraph-api-slice'; -// import subgraphReducer from './subgraph.store'; +import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit'; +// import { subgraphApiSlice } from './subgraph-api-slice'; +import subgraphReducer from './subgraph.store'; export const store = configureStore({ reducer: { - [subgraphApiSlice.reducerPath]: subgraphApiSlice.reducer, - }, - middleware: getDefaultMiddleware => { - return getDefaultMiddleware().concat(subgraphApiSlice.middleware); + subgraph: subgraphReducer, }, }); @@ -15,3 +12,9 @@ export const store = configureStore({ export type RootState = ReturnType; // Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState} export type AppDispatch = typeof store.dispatch; +export type AppThunk = ThunkAction< + ReturnType, + RootState, + unknown, + Action +>; diff --git a/src/stores/subgraph-api-slice.ts b/src/stores/subgraph-api-slice.ts deleted file mode 100644 index b805fd5491..0000000000 --- a/src/stores/subgraph-api-slice.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'; -import { ISubgraphValue } from '@/context/subgraph.context'; -import { SubgraphQueryBuilder } from '@/lib/subgraph/subgraphQueryBuilder'; -import { transformSubgraphData } from '@/lib/subgraph/subgraphDataTransform'; - -interface props { - chain?: number; - userAddress?: string | null; -} - -export const subgraphApiSlice = createApi({ - reducerPath: 'subgraph', - baseQuery: fetchBaseQuery({ - baseUrl: 'https://api.thegraph.com/subgraphs/name/mohammadranjbarz', - }), - endpoints(builder) { - return { - getSubgraphValues: builder.query({ - query(props) { - const reqBody = { - query: SubgraphQueryBuilder.getXDaiQuery( - props.userAddress ?? '', - ), - }; - // throw new Error('boroooo'); - return { - url: `/giv-economy-xdai-develop`, - body: JSON.stringify(reqBody), - method: 'POST', - }; - }, - transformResponse: ( - response: { data: ISubgraphValue }, - meta, - arg, - ) => { - console.log('meta', meta); - return transformSubgraphData(response.data); - }, - }), - }; - }, -}); - -export const { useGetSubgraphValuesQuery } = subgraphApiSlice; diff --git a/src/stores/subgraph.store.ts b/src/stores/subgraph.store.ts index b076b98a11..e76a3155c0 100644 --- a/src/stores/subgraph.store.ts +++ b/src/stores/subgraph.store.ts @@ -1,4 +1,4 @@ -import { createSlice, PayloadAction } from '@reduxjs/toolkit'; +import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'; import { captureException } from '@sentry/nextjs'; import { IBalances, @@ -47,6 +47,7 @@ const initialState = { currentValues: defaultSubgraphValue, mainnetValues: defaultSubgraphValue, xDaiValues: defaultSubgraphValue, + status: 'idle', }; const fetchMainnetInfo = async (userAddress = '') => { @@ -63,6 +64,7 @@ const fetchMainnetInfo = async (userAddress = '') => { section: 'fetchMainnetSubgraph', }, }); + return defaultSubgraphValue; } }; @@ -80,36 +82,97 @@ const fetchXDaiInfo = async (userAddress = '') => { section: 'fetchxDaiSubgraph', }, }); + return defaultSubgraphValue; } }; +export const fetchXDaiInfoAsync = createAsyncThunk( + 'subgraph/fetchXDaiInfo', + async (userAddress: string) => { + const response = await fetchXDaiInfo(userAddress); + // The value we return becomes the `fulfilled` action payload + console.log(response); + return response; + }, +); + +export const fetchMainnetInfoAsync = createAsyncThunk( + 'subgraph/fetchMainnetInfo', + async (userAddress: string) => { + const response = await fetchXDaiInfo(userAddress); + // The value we return becomes the `fulfilled` action payload + console.log(response); + return response; + }, +); + +interface ICurrentInfo { + userAddress: string; + chainId: number; +} + +export const fetchCurrentInfoAsync = createAsyncThunk( + 'subgraph/fetchCurrentInfo', + async (props: ICurrentInfo) => { + const response = + props.chainId === config.MAINNET_NETWORK_NUMBER + ? await fetchMainnetInfo(props.userAddress) + : await fetchXDaiInfo(props.userAddress); + // The value we return becomes the `fulfilled` action payload + console.log(response); + return { response, chainId: props.chainId }; + }, +); + export const subgraphSlice = createSlice({ name: 'subgraph', initialState, - reducers: { - log: state => { - // Redux Toolkit allows us to write "mutating" logic in reducers. It - // doesn't actually mutate the state because it uses the Immer library, - // which detects changes to a "draft state" and produces a brand new - // immutable state based off those changes - // state.value += 1; - // console.log('state', state); - }, - updateXDaiValues: state => { - // state.value -= 1; - }, - updateMainnetValues: (state, action: PayloadAction) => { - // state.value -= 1; - // state.mainnetValues = fetchMainnetInfo(action.payload); - }, - incrementByAmount: (state, action: PayloadAction) => { - // state.value += action.payload; - }, + reducers: {}, + extraReducers: builder => { + builder + .addCase(fetchCurrentInfoAsync.pending, state => { + state.status = 'loading'; + }) + .addCase(fetchCurrentInfoAsync.fulfilled, (state, action) => { + state.status = 'idle'; + state.currentValues = action.payload.response; + if (action.payload.chainId === config.MAINNET_NETWORK_NUMBER) { + state.mainnetValues = action.payload.response; + } + if (action.payload.chainId === config.XDAI_NETWORK_NUMBER) { + state.xDaiValues = action.payload.response; + } + }) + .addCase(fetchCurrentInfoAsync.rejected, state => { + state.status = 'failed'; + }); + builder + .addCase(fetchXDaiInfoAsync.pending, state => { + state.status = 'loading'; + }) + .addCase(fetchXDaiInfoAsync.fulfilled, (state, action) => { + state.status = 'idle'; + state.xDaiValues = action.payload; + }) + .addCase(fetchXDaiInfoAsync.rejected, state => { + state.status = 'failed'; + }); + builder + .addCase(fetchMainnetInfoAsync.pending, state => { + state.status = 'loading'; + }) + .addCase(fetchMainnetInfoAsync.fulfilled, (state, action) => { + state.status = 'idle'; + state.mainnetValues = action.payload; + }) + .addCase(fetchMainnetInfoAsync.rejected, state => { + state.status = 'failed'; + }); }, }); // Action creators are generated for each case reducer function -export const { updateMainnetValues, updateXDaiValues, incrementByAmount } = - subgraphSlice.actions; +// export const { updateMainnetValues, updateXDaiValues, incrementByAmount } = +// subgraphSlice.actions; export default subgraphSlice.reducer; From bd6b2de5f2628f38c21926ef571713b6e1d9ed12 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:52:11 +0430 Subject: [PATCH 041/257] update transformBalanceInfo --- src/lib/subgraph/subgraphDataTransform.ts | 99 +++++++++++------------ 1 file changed, 46 insertions(+), 53 deletions(-) diff --git a/src/lib/subgraph/subgraphDataTransform.ts b/src/lib/subgraph/subgraphDataTransform.ts index 64526650c0..306f41397c 100644 --- a/src/lib/subgraph/subgraphDataTransform.ts +++ b/src/lib/subgraph/subgraphDataTransform.ts @@ -12,50 +12,43 @@ import { } from '@/types/subgraph'; import { RegenFarmType, StakingType, StreamType } from '@/types/config'; -const BN = ethers.BigNumber.from; - const transformBalanceInfo = (info: any): IBalances => { if (!info) return ZeroBalances; - const balance = BN(info.balance || 0); - const allocatedTokens = BN(info.allocatedTokens || 0); - const claimed = BN(info.claimed || 0); - const rewardPerTokenPaidGivLm = BN(info.rewardPerTokenPaidGivLm || 0); - const rewardsGivLm = BN(info.rewardsGivLm || 0); - const rewardPerTokenPaidSushiSwap = BN( - info.rewardPerTokenPaidSushiSwap || 0, - ); - const rewardsSushiSwap = BN(info.rewardsSushiSwap || 0); - const rewardPerTokenPaidHoneyswap = BN( - info.rewardPerTokenPaidHoneyswap || 0, - ); - const rewardsHoneyswap = BN(info.rewardsHoneyswap || 0); - const rewardPerTokenPaidBalancer = BN(info.rewardPerTokenPaidBalancer || 0); - const rewardsBalancer = BN(info.rewardsBalancer || 0); - const rewardPerTokenPaidUniswapV2GivDai = BN( - info.rewardPerTokenPaidUniswapV2GivDai || 0, - ); - const rewardsUniswapV2GivDai = BN(info.rewardsUniswapV2GivDai || 0); - const givback = BN(info.givback || 0); - const givbackLiquidPart = BN(info.givbackLiquidPart || 0); - const balancerLp = BN(info.balancerLp || 0); - const balancerLpStaked = BN(info.balancerLpStaked || 0); - const uniswapV2GivDaiLp = BN(info.uniswapV2GivDaiLp || 0); - const uniswapV2GivDaiLpStaked = BN(info.uniswapV2GivDaiLpStaked || 0); - const sushiswapLp = BN(info.sushiswapLp || 0); - const sushiSwapLpStaked = BN(info.sushiSwapLpStaked || 0); - const honeyswapLp = BN(info.honeyswapLp || 0); - const honeyswapLpStaked = BN(info.honeyswapLpStaked || 0); - const givStaked = BN(info.givStaked || 0); + const balance = info.balance || 0; + const allocatedTokens = info.allocatedTokens || 0; + const claimed = info.claimed || 0; + const rewardPerTokenPaidGivLm = info.rewardPerTokenPaidGivLm || 0; + const rewardsGivLm = info.rewardsGivLm || 0; + const rewardPerTokenPaidSushiSwap = info.rewardPerTokenPaidSushiSwap || 0; + const rewardsSushiSwap = info.rewardsSushiSwap || 0; + const rewardPerTokenPaidHoneyswap = info.rewardPerTokenPaidHoneyswap || 0; + const rewardsHoneyswap = info.rewardsHoneyswap || 0; + const rewardPerTokenPaidBalancer = info.rewardPerTokenPaidBalancer || 0; + const rewardsBalancer = info.rewardsBalancer || 0; + const rewardPerTokenPaidUniswapV2GivDai = + info.rewardPerTokenPaidUniswapV2GivDai || 0; + const rewardsUniswapV2GivDai = info.rewardsUniswapV2GivDai || 0; + const givback = info.givback || 0; + const givbackLiquidPart = info.givbackLiquidPart || 0; + const balancerLp = info.balancerLp || 0; + const balancerLpStaked = info.balancerLpStaked || 0; + const uniswapV2GivDaiLp = info.uniswapV2GivDaiLp || 0; + const uniswapV2GivDaiLpStaked = info.uniswapV2GivDaiLpStaked || 0; + const sushiswapLp = info.sushiswapLp || 0; + const sushiSwapLpStaked = info.sushiSwapLpStaked || 0; + const honeyswapLp = info.honeyswapLp || 0; + const honeyswapLpStaked = info.honeyswapLpStaked || 0; + const givStaked = info.givStaked || 0; const allocationCount = Number(info.allocationCount || 0); const givDropClaimed = Boolean(info.givDropClaimed); - const foxAllocatedTokens = BN(info.foxAllocatedTokens || 0); - const foxClaimed = BN(info.foxClaimed || 0); - const rewardPerTokenPaidFoxHnyLm = BN(info.rewardPerTokenPaidFoxHnyLm || 0); - const rewardsFoxHnyLm = BN(info.rewardsFoxHnyLm || 0); - const foxHnyLp = BN(info.foxHnyLp || 0); - const foxHnyLpStaked = BN(info.foxHnyLpStaked || 0); + const foxAllocatedTokens = info.foxAllocatedTokens || 0; + const foxClaimed = info.foxClaimed || 0; + const rewardPerTokenPaidFoxHnyLm = info.rewardPerTokenPaidFoxHnyLm || 0; + const rewardsFoxHnyLm = info.rewardsFoxHnyLm || 0; + const foxHnyLp = info.foxHnyLp || 0; + const foxHnyLpStaked = info.foxHnyLpStaked || 0; return { balance, @@ -101,14 +94,14 @@ const transformTokenDistroInfo = (info: any): ITokenDistroInfo | undefined => { const _cliffTime = info.cliffTime; const _duration = info.duration; - const startTime = new Date(+(_startTime.toString() + '000')); - const cliffTime = new Date(+(_cliffTime.toString() + '000')); + const startTime = +(_startTime.toString() + '000'); + const cliffTime = +(_cliffTime.toString() + '000'); const duration = +(_duration.toString() + '000'); - const endTime = new Date(startTime.getTime() + duration); - const initialAmount = BN(info.initialAmount); - const lockedAmount = BN(info.lockedAmount); - const totalTokens = BN(info.totalTokens); + const endTime = startTime + duration; + const initialAmount = info.initialAmount; + const lockedAmount = info.lockedAmount; + const totalTokens = info.totalTokens; return { contractAddress: info.id, @@ -123,9 +116,9 @@ const transformTokenDistroInfo = (info: any): ITokenDistroInfo | undefined => { const transformUniswapV3Pool = (info: any): IUniswapV3Pool | undefined => { if (!info) return undefined; - const sqrtPriceX96 = BN(info.sqrtPriceX96); + const sqrtPriceX96 = info.sqrtPriceX96; const tick = Number(info.tick); - const liquidity = BN(info.liquidity); + const liquidity = info.liquidity; const token0 = info.token0; const token1 = info.token1; return { @@ -143,9 +136,9 @@ const transformUnipoolInfo = (info: any): IUnipool | undefined => { const _lastUpdateTime = info?.lastUpdateTime || '0'; const _periodFinish = info?.periodFinish || '0'; - const totalSupply = BN(info?.totalSupply || 0); - const rewardPerTokenStored = BN(info?.rewardPerTokenStored || 0); - const rewardRate = BN(info?.rewardRate || 0); + const totalSupply = info?.totalSupply || 0; + const rewardPerTokenStored = info?.rewardPerTokenStored || 0; + const rewardRate = info?.rewardRate || 0; const lastUpdateTime = Number(_lastUpdateTime) * 1000; const periodFinish = Number(_periodFinish) * 1000; @@ -162,7 +155,7 @@ const transformUniswapPositions = (info: any): any => { if (!info) return {}; const mapper = (info: any): IUniswapV3Position => { const tokenId = Number(info?.tokenId || 0); - const liquidity = BN(info?.liquidity); + const liquidity = info?.liquidity; const tickLower = Number(info?.tickLower); const tickUpper = Number(info?.tickUpper); const staked = Boolean(info?.staked); @@ -201,7 +194,7 @@ const transformUniswapPositions = (info: any): any => { if (infinitePositionRewardInfo && infinitePositionInfo) { const infinitePositionReward: IInfinitePositionReward = { - lastRewardAmount: BN(infinitePositionRewardInfo.lastRewardAmount), + lastRewardAmount: infinitePositionRewardInfo.lastRewardAmount, lastUpdateTimeStamp: Number( infinitePositionRewardInfo.lastUpdateTimeStamp, ), @@ -222,8 +215,8 @@ const transformUniswapV2Pair = (info: any): IUniswapV2Pair | undefined => { const token0 = info?.token0 || ethers.constants.AddressZero; const token1 = info?.token1 || ethers.constants.AddressZero; - const reserve0 = BN(info?.reserve0 || 1); - const reserve1 = BN(info?.reserve1 || 1); + const reserve0 = info?.reserve0 || 1; + const reserve1 = info?.reserve1 || 1; return { token0, From 0c750d034be1611da19742952171c01ae7deede8 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:52:28 +0430 Subject: [PATCH 042/257] move BN to number helper --- src/helpers/number.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/helpers/number.ts b/src/helpers/number.ts index 6667d4c979..fb70ebbac7 100644 --- a/src/helpers/number.ts +++ b/src/helpers/number.ts @@ -3,6 +3,7 @@ import { ethers } from 'ethers'; import config from '@/configuration'; export const Zero = new BigNumber(0); +export const BN = ethers.BigNumber.from; export const formatEthHelper = ( amount: BigNumber.Value, From 20331fddca9162c83ad0cf43f8cadaa2752cb507 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:53:46 +0430 Subject: [PATCH 043/257] update TokenDistroHelper --- src/lib/contractHelper/TokenDistroHelper.ts | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/lib/contractHelper/TokenDistroHelper.ts b/src/lib/contractHelper/TokenDistroHelper.ts index 00196f9d6f..5a2396ddb9 100644 --- a/src/lib/contractHelper/TokenDistroHelper.ts +++ b/src/lib/contractHelper/TokenDistroHelper.ts @@ -4,6 +4,7 @@ import { Zero } from '@ethersproject/constants'; import { getNowUnixMS } from '@/helpers/time'; import { IBalances, ITokenDistroInfo } from '@/types/subgraph'; import { StreamType } from '@/types/config'; +import { BN } from '@/helpers/number'; export class TokenDistroHelper { public readonly contractAddress: string; @@ -28,12 +29,12 @@ export class TokenDistroHelper { readonly streamType?: StreamType, ) { this.contractAddress = contractAddress; - this.initialAmount = initialAmount; - this.lockedAmount = lockedAmount; - this.totalTokens = totalTokens; - this.startTime = startTime; - this.cliffTime = cliffTime; - this.endTime = endTime; + this.initialAmount = BN(initialAmount); + this.lockedAmount = BN(lockedAmount); + this.totalTokens = BN(totalTokens); + this.startTime = new Date(startTime); + this.cliffTime = new Date(cliffTime); + this.endTime = new Date(endTime); this.duration = this.endTime.getTime() - this.startTime.getTime(); } @@ -86,14 +87,14 @@ export class TokenDistroHelper { switch (this.streamType) { case StreamType.FOX: allocatedTokens = userBalance.foxAllocatedTokens; - claimed = userBalance.foxClaimed; + claimed = BN(userBalance.foxClaimed); break; default: allocatedTokens = userBalance.allocatedTokens; - claimed = userBalance.claimed; + claimed = BN(userBalance.claimed); } - return this.getLiquidPart(allocatedTokens).sub(claimed); + return this.getLiquidPart(BN(allocatedTokens)).sub(claimed); } public get GlobalReleasePercentage(): number { From c1c76d20d808eae00d8ca874b7e39d8c13af15b3 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:54:17 +0430 Subject: [PATCH 044/257] update stakingPool library --- src/lib/stakingPool.ts | 64 ++++++++++++++++++++++-------------------- 1 file changed, 33 insertions(+), 31 deletions(-) diff --git a/src/lib/stakingPool.ts b/src/lib/stakingPool.ts index 78ba860f7b..b7bb25208e 100644 --- a/src/lib/stakingPool.ts +++ b/src/lib/stakingPool.ts @@ -17,7 +17,7 @@ import { import config from '../configuration'; import { APR } from '@/types/poolInfo'; import { UnipoolHelper } from '@/lib/contractHelper/UnipoolHelper'; -import { Zero } from '@/helpers/number'; +import { BN, Zero } from '@/helpers/number'; import { IBalances, IUnipool } from '@/types/subgraph'; import { getGasPreference } from '@/lib/helpers'; @@ -46,8 +46,8 @@ export const getGivStakingAPR = async ( let apr: BigNumber = Zero; if (unipool) { - const totalSupply = unipool.totalSupply; - const rewardRate = unipool.rewardRate; + const totalSupply = BN(unipool.totalSupply); + const rewardRate = BN(unipool.rewardRate); apr = totalSupply.isZero() ? Zero @@ -125,8 +125,8 @@ const getBalancerPoolStakingAPR = async ( let rewardRate: ethers.BigNumber; if (unipool) { - totalSupply = unipool.totalSupply; - rewardRate = unipool.rewardRate; + totalSupply = BN(unipool.totalSupply); + rewardRate = BN(unipool.rewardRate); } else { [totalSupply, rewardRate] = await Promise.all([ lmContract.totalSupply(), @@ -200,8 +200,8 @@ const getSimplePoolStakingAPR = async ( poolContract.totalSupply(), ]); if (unipool) { - totalSupply = unipool.totalSupply; - rewardRate = unipool.rewardRate; + totalSupply = BN(unipool.totalSupply); + rewardRate = BN(unipool.rewardRate); } else { [totalSupply, rewardRate] = await Promise.all([ lmContract.totalSupply(), @@ -256,44 +256,46 @@ export const getUserStakeInfo = ( if (regenFarmType) { switch (regenFarmType) { case RegenFarmType.FOX_HNY: - rewards = balance.rewardsFoxHnyLm; - rewardPerTokenPaid = balance.rewardPerTokenPaidFoxHnyLm; - stakedAmount = balance.foxHnyLpStaked; - notStakedAmount = balance.foxHnyLp; + rewards = BN(balance.rewardsFoxHnyLm); + rewardPerTokenPaid = BN(balance.rewardPerTokenPaidFoxHnyLm); + stakedAmount = BN(balance.foxHnyLpStaked); + notStakedAmount = BN(balance.foxHnyLp); break; default: } } else { switch (type) { case StakingType.SUSHISWAP: - rewards = balance.rewardsSushiSwap; - rewardPerTokenPaid = balance.rewardPerTokenPaidSushiSwap; - stakedAmount = balance.sushiSwapLpStaked; - notStakedAmount = balance.sushiswapLp; + rewards = BN(balance.rewardsSushiSwap); + rewardPerTokenPaid = BN(balance.rewardPerTokenPaidSushiSwap); + stakedAmount = BN(balance.sushiSwapLpStaked); + notStakedAmount = BN(balance.sushiswapLp); break; case StakingType.HONEYSWAP: - rewards = balance.rewardsHoneyswap; - rewardPerTokenPaid = balance.rewardPerTokenPaidHoneyswap; - stakedAmount = balance.honeyswapLpStaked; - notStakedAmount = balance.honeyswapLp; + rewards = BN(balance.rewardsHoneyswap); + rewardPerTokenPaid = BN(balance.rewardPerTokenPaidHoneyswap); + stakedAmount = BN(balance.honeyswapLpStaked); + notStakedAmount = BN(balance.honeyswapLp); break; case StakingType.BALANCER: - rewards = balance.rewardsBalancer; - rewardPerTokenPaid = balance.rewardPerTokenPaidBalancer; - stakedAmount = balance.balancerLpStaked; - notStakedAmount = balance.balancerLp; + rewards = BN(balance.rewardsBalancer); + rewardPerTokenPaid = BN(balance.rewardPerTokenPaidBalancer); + stakedAmount = BN(balance.balancerLpStaked); + notStakedAmount = BN(balance.balancerLp); break; case StakingType.UNISWAPV2: - rewards = balance.rewardsUniswapV2GivDai; - rewardPerTokenPaid = balance.rewardPerTokenPaidUniswapV2GivDai; - stakedAmount = balance.uniswapV2GivDaiLpStaked; - notStakedAmount = balance.uniswapV2GivDaiLp; + rewards = BN(balance.rewardsUniswapV2GivDai); + rewardPerTokenPaid = BN( + balance.rewardPerTokenPaidUniswapV2GivDai, + ); + stakedAmount = BN(balance.uniswapV2GivDaiLpStaked); + notStakedAmount = BN(balance.uniswapV2GivDaiLp); break; case StakingType.GIV_LM: - rewards = balance.rewardsGivLm; - rewardPerTokenPaid = balance.rewardPerTokenPaidGivLm; - stakedAmount = balance.givStaked; - notStakedAmount = balance.balance; + rewards = BN(balance.rewardsGivLm); + rewardPerTokenPaid = BN(balance.rewardPerTokenPaidGivLm); + stakedAmount = BN(balance.givStaked); + notStakedAmount = BN(balance.balance); break; default: } From 04d5c422a3818eb6f78a9e3409355a6a389d10c4 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:55:06 +0430 Subject: [PATCH 045/257] update useStakingPool and BaseCard --- src/components/cards/BaseStakingCard.tsx | 14 ++++++++--- src/components/cards/StakingPoolCard.tsx | 4 +-- src/components/cards/StakingPositionCard.tsx | 4 +-- src/hooks/useStakingPool.tsx | 26 +++++++++++--------- 4 files changed, 28 insertions(+), 20 deletions(-) diff --git a/src/components/cards/BaseStakingCard.tsx b/src/components/cards/BaseStakingCard.tsx index f83399012f..3d7cf3abe3 100644 --- a/src/components/cards/BaseStakingCard.tsx +++ b/src/components/cards/BaseStakingCard.tsx @@ -16,7 +16,7 @@ import { StakingType, } from '@/types/config'; import { IconWithTooltip } from '../IconWithToolTip'; -import { formatEthHelper, formatWeiHelper } from '@/helpers/number'; +import { BN, formatEthHelper, formatWeiHelper } from '@/helpers/number'; import { StakingPoolContainer, StakingPoolExchangeRow, @@ -66,6 +66,7 @@ import StakingCardIntro from './StakingCardIntro'; import { getNowUnixMS } from '@/helpers/time'; import FarmCountDown from '../FarmCountDown'; import { Flex } from '../styled-components/Flex'; +import { IStakeInfo } from '@/hooks/useStakingPool'; export enum StakeCardState { NORMAL, @@ -91,7 +92,7 @@ export const getPoolIconWithName = (pool: string) => { }; interface IBaseStakingCardProps { poolStakingConfig: PoolStakingConfig | RegenPoolStakingConfig; - stakeInfo: any; + stakeInfo: IStakeInfo; notif?: ReactNode; } @@ -134,7 +135,12 @@ const BaseStakingCard: FC = ({ const isInactive = !active || type === StakingType.UNISWAPV3; - const { apr, earned, stakedLpAmount, userNotStakedAmount } = stakeInfo; + const { + apr, + earned, + stakedAmount: stakedLpAmount, + notStakedAmount: userNotStakedAmount, + } = stakeInfo; const regenStreamConfig = useMemo(() => { if (!regenStreamType) return undefined; @@ -347,7 +353,7 @@ const BaseStakingCard: FC = ({ label='STAKE' size='small' disabled={ - userNotStakedAmount.isZero() || + BN(userNotStakedAmount).isZero() || isInactive } onClick={() => setShowStakeModal(true)} diff --git a/src/components/cards/StakingPoolCard.tsx b/src/components/cards/StakingPoolCard.tsx index 24d6cdeefe..956ede6b47 100644 --- a/src/components/cards/StakingPoolCard.tsx +++ b/src/components/cards/StakingPoolCard.tsx @@ -19,9 +19,9 @@ const StakingPoolCard: FC = ({ const stakeInfo = { apr: apr, - userNotStakedAmount: notStakedAmount, + notStakedAmount: notStakedAmount, earned: earned, - stakedLpAmount: stakedAmount, + stakedAmount: stakedAmount, }; return ( diff --git a/src/components/cards/StakingPositionCard.tsx b/src/components/cards/StakingPositionCard.tsx index 3dc075a88b..0230c12ac3 100644 --- a/src/components/cards/StakingPositionCard.tsx +++ b/src/components/cards/StakingPositionCard.tsx @@ -34,9 +34,9 @@ const StakingPositionCard: FC = ({ const stakeInfo = { apr: apr, - userNotStakedAmount: BigNumber.from(unstakedPositions.length), + notStakedAmount: BigNumber.from(unstakedPositions.length), earned: rewardBalance, - stakedLpAmount: BigNumber.from(stakedPositions.length), + stakedAmount: BigNumber.from(stakedPositions.length), }; useEffect(() => { diff --git a/src/hooks/useStakingPool.tsx b/src/hooks/useStakingPool.tsx index 9aeba5d8ee..cd268362cb 100644 --- a/src/hooks/useStakingPool.tsx +++ b/src/hooks/useStakingPool.tsx @@ -3,12 +3,12 @@ import BigNumber from 'bignumber.js'; import { ethers } from 'ethers'; import { useWeb3React } from '@web3-react/core'; +import { useSelector } from 'react-redux'; import { getGivStakingAPR, getLPStakingAPR, getUserStakeInfo, } from '@/lib/stakingPool'; -import { useSubgraph } from '@/context'; import { PoolStakingConfig, RegenPoolStakingConfig, @@ -17,33 +17,35 @@ import { import { APR, UserStakeInfo } from '@/types/poolInfo'; import { UnipoolHelper } from '@/lib/contractHelper/UnipoolHelper'; import { Zero } from '@/helpers/number'; +import { RootState } from '@/stores/store'; -export const useStakingPool = ( - poolStakingConfig: PoolStakingConfig | RegenPoolStakingConfig, - network: number, -): { +export interface IStakeInfo { apr: BigNumber | null; earned: ethers.BigNumber; stakedAmount: ethers.BigNumber; notStakedAmount: ethers.BigNumber; -} => { - const { library, chainId } = useWeb3React(); - const { currentValues } = useSubgraph(); - - const { balances } = currentValues; +} +export const useStakingPool = ( + poolStakingConfig: PoolStakingConfig | RegenPoolStakingConfig, + network: number, +): IStakeInfo => { const [apr, setApr] = useState(null); const [userStakeInfo, setUserStakeInfo] = useState({ earned: ethers.constants.Zero, notStakedAmount: ethers.constants.Zero, stakedAmount: ethers.constants.Zero, }); - const stakePoolInfoPoll = useRef(null); + const { library, chainId } = useWeb3React(); + const currentValues = useSelector( + (state: RootState) => state.subgraph.currentValues, + ); + + const { balances } = currentValues; const { type, LM_ADDRESS, regenFarmType } = poolStakingConfig as RegenPoolStakingConfig; - const unipool = currentValues[regenFarmType || type]; const unipoolIsDefined = !!unipool; const providerNetwork = library?.network?.chainId; From 311c64ec56875206a1215ef072c51abc85c5d6ff Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:55:19 +0430 Subject: [PATCH 046/257] remove useSubgraph export --- src/context/index.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/context/index.tsx b/src/context/index.tsx index ac3585e78a..57b7813067 100644 --- a/src/context/index.tsx +++ b/src/context/index.tsx @@ -1,4 +1,3 @@ -import { useSubgraph } from '@/context/subgraph.context'; import { useLiquidityPositions } from '@/context/positions.context'; -export { useSubgraph, useLiquidityPositions }; +export { useLiquidityPositions }; From 4d1896c334c95575f1010d0a75a5e50861bbd08e Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 16 May 2022 15:55:42 +0430 Subject: [PATCH 047/257] update test page --- pages/test.tsx | 47 +++++++++++++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 18 deletions(-) diff --git a/pages/test.tsx b/pages/test.tsx index 9106f92dc7..02c383dbbc 100644 --- a/pages/test.tsx +++ b/pages/test.tsx @@ -3,9 +3,12 @@ import styled from 'styled-components'; import { GetServerSideProps } from 'next'; // import { useSelector, useDispatch } from 'react-redux'; import { useWeb3React } from '@web3-react/core'; -import { useEffect } from 'react'; +// import { useEffect } from 'react'; +import { useSelector } from 'react-redux'; import { gToast, ToastType } from '@/components/toasts'; -import { useGetSubgraphValuesQuery } from '@/stores/subgraph-api-slice'; +import { useAppDispatch } from '@/stores/hooks'; +import { fetchXDaiInfoAsync } from '@/stores/subgraph.store'; +import { RootState } from '@/stores/store'; // import { RootState } from '@/stores/store'; const TestRoute = () => { @@ -13,10 +16,14 @@ const TestRoute = () => { // (state: RootState) => state.subgraph.xDaiValues, // ); const { library, chainId, account } = useWeb3React(); - const { data, isLoading, error, refetch } = useGetSubgraphValuesQuery({ - chain: chainId, - userAddress: account, - }); + const dispatch = useAppDispatch(); + const xDaiValues = useSelector( + (state: RootState) => state.subgraph.xDaiValues, + ); + // const { data, isLoading, error, refetch } = useGetSubgraphValuesQuery({ + // chain: chainId, + // userAddress: account, + // }); const notify = () => gToast('Testeeee', { @@ -28,17 +35,19 @@ const TestRoute = () => { }); // console.log('xDaiValues', xDaiValues); - useEffect(() => { - if (!library) return; - library.on('block', (evt: any) => { - console.log('evt', evt); - // dispatch(updateXDaiValues()); - }); - return () => { - library.removeAllListeners('block'); - }; - }, [library]); - console.log('****data', data); + // useEffect(() => { + // if (!library) return; + // library.on('block', (evt: any) => { + // console.log('evt', evt); + // // dispatch(updateXDaiValues()); + // }); + // return () => { + // library.removeAllListeners('block'); + // }; + // }, [library]); + // console.log('****data', data); + + console.log('xDaiValues', xDaiValues); return ( <> @@ -48,7 +57,9 @@ const TestRoute = () => { + ); diff --git a/src/features/user/user.queries.ts b/src/features/user/user.queries.ts index 7b0a12fefe..a44ea1351c 100644 --- a/src/features/user/user.queries.ts +++ b/src/features/user/user.queries.ts @@ -1,4 +1,4 @@ -export const getUserByAddress = `query UserByAddress($address: String!) { +export const GET_USER_BY_ADDRESS = `query UserByAddress($address: String!) { userByAddress(address: $address) { id firstName diff --git a/src/features/user/user.slice.ts b/src/features/user/user.slice.ts index 00fdf77284..e8e24a432d 100644 --- a/src/features/user/user.slice.ts +++ b/src/features/user/user.slice.ts @@ -1,6 +1,6 @@ import { createSlice, PayloadAction } from '@reduxjs/toolkit'; import { IUser } from '@/apollo/types/types'; -import { fetchUserByAddress } from './user.thunks'; +import { fetchUserByAddress, signToGetToken } from './user.thunks'; import StorageLabel from '@/lib/localStorage'; const initialState: { @@ -37,19 +37,26 @@ export const userSlice = createSlice({ }, }, extraReducers: builder => { - builder.addCase( - fetchUserByAddress.fulfilled, - ( - state, - action: PayloadAction<{ - data: { - userByAddress: IUser; - }; - }>, - ) => { - state.userData = action.payload.data?.userByAddress; - }, - ); + builder + .addCase( + fetchUserByAddress.fulfilled, + ( + state, + action: PayloadAction<{ + data: { + userByAddress: IUser; + }; + }>, + ) => { + state.userData = action.payload.data?.userByAddress; + }, + ) + .addCase(signToGetToken.fulfilled, (state, action) => { + console.log('SignIn Action', action); + state.token = action.payload; + localStorage.setItem(StorageLabel.TOKEN, action.payload); + state.isSignedIn = true; + }); }, }); export const { setIsEnabled, setIsSignedIn, setToken, signOut } = diff --git a/src/features/user/user.thunks.ts b/src/features/user/user.thunks.ts index 69112bd11d..f15d47de20 100644 --- a/src/features/user/user.thunks.ts +++ b/src/features/user/user.thunks.ts @@ -1,10 +1,35 @@ import { createAsyncThunk } from '@reduxjs/toolkit'; import gqlRequest from '@/helpers/gqlRequest'; -import { getUserByAddress } from './user.queries'; +import { GET_USER_BY_ADDRESS } from './user.queries'; +import { ISignToGetToken } from './user.types'; +import { signMessage } from '@/lib/helpers'; +import { getToken } from '@/services/token'; +import { RootState } from '../store'; export const fetchUserByAddress = createAsyncThunk( 'user/fetchUser', async (address: string) => { - return gqlRequest(getUserByAddress, { address }); + return gqlRequest(GET_USER_BY_ADDRESS, { address }); + }, +); + +export const signToGetToken = createAsyncThunk( + 'user/signToGetToken', + async ( + { message, address, chainId, signer }: ISignToGetToken, + { getState }, + ) => { + const signedMessage = await signMessage( + message, + address, + chainId, + signer, + ); + console.log('signedMessage', signedMessage); + if (!signedMessage) { + Promise.reject(new Error('signIn failed')); + } + const { user } = getState() as { user: RootState['user'] }; + return getToken(address, signedMessage, chainId, user); }, ); diff --git a/src/features/user/user.types.ts b/src/features/user/user.types.ts new file mode 100644 index 0000000000..aaf3412f2f --- /dev/null +++ b/src/features/user/user.types.ts @@ -0,0 +1,6 @@ +export interface ISignToGetToken { + message: string; + address: string | undefined | null; + chainId?: number; + signer?: any; +} From 77aa27cb0222b7a14209f912c019501c946ddcaf Mon Sep 17 00:00:00 2001 From: Mateo Daza Date: Fri, 20 May 2022 10:53:56 -0500 Subject: [PATCH 115/257] removes authorization before saving token --- src/apollo/apolloClient.ts | 2 +- src/context/UserProvider.tsx | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/apollo/apolloClient.ts b/src/apollo/apolloClient.ts index 73eee94f95..798f028e97 100644 --- a/src/apollo/apolloClient.ts +++ b/src/apollo/apolloClient.ts @@ -29,9 +29,9 @@ function createApolloClient() { const currentToken: string | null = !ssrMode ? localStorage.getItem(StorageLabel.TOKEN) : null; - const mutation: any = { Authorization: currentToken ? `Bearer ${currentToken}` : '', + authVersion: '2', }; if (userWalletAddress) mutation['wallet-address'] = userWalletAddress; return { diff --git a/src/context/UserProvider.tsx b/src/context/UserProvider.tsx index e6b4a877b3..ed752bc1d9 100644 --- a/src/context/UserProvider.tsx +++ b/src/context/UserProvider.tsx @@ -16,7 +16,6 @@ import { GET_USER_BY_ADDRESS } from '@/apollo/gql/gqlUser'; import { compareAddresses, showToastError, - signMessage, postData, createSiweMessage, } from '@/lib/helpers'; @@ -164,14 +163,15 @@ export const UserProvider = (props: { children: ReactNode }) => { if (!signature) return false; const token = await getToken(signature, message, nonce); - const authorizedToken = await authorizeToken(token.jwt); + // const authorizedToken = await authorizeToken(token.jwt); + const authorizedToken = token.jwt; await apolloClient.resetStore(); setToken(authorizedToken); setUser({ ...user, token: authorizedToken }); - return authorizedToken; }; + // Trying out, not needed as every query/mutation authorizes the token on backend const authorizeToken = async (jwt: string) => { const authorization = await postData( `${config.MICROSERVICES.authentication}/authorization`, From 4f4f6730f9154a69cb36ecc9d732655d02a1da9f Mon Sep 17 00:00:00 2001 From: alireza-sharifpour Date: Sun, 22 May 2022 10:40:47 +0430 Subject: [PATCH 116/257] Added user address to localStorage and handled signToGetToken error --- src/features/user/user.slice.ts | 4 ++++ src/features/user/user.thunks.ts | 10 +++++----- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/features/user/user.slice.ts b/src/features/user/user.slice.ts index e8e24a432d..86e0180cef 100644 --- a/src/features/user/user.slice.ts +++ b/src/features/user/user.slice.ts @@ -54,6 +54,10 @@ export const userSlice = createSlice({ .addCase(signToGetToken.fulfilled, (state, action) => { console.log('SignIn Action', action); state.token = action.payload; + localStorage.setItem( + StorageLabel.USER, + action.meta.arg.address || '', + ); localStorage.setItem(StorageLabel.TOKEN, action.payload); state.isSignedIn = true; }); diff --git a/src/features/user/user.thunks.ts b/src/features/user/user.thunks.ts index f15d47de20..e8266d3690 100644 --- a/src/features/user/user.thunks.ts +++ b/src/features/user/user.thunks.ts @@ -25,11 +25,11 @@ export const signToGetToken = createAsyncThunk( chainId, signer, ); - console.log('signedMessage', signedMessage); - if (!signedMessage) { - Promise.reject(new Error('signIn failed')); + if (signedMessage) { + const { user } = getState() as { user: RootState['user'] }; + return getToken(address, signedMessage, chainId, user); + } else { + return Promise.reject('Signing failed'); } - const { user } = getState() as { user: RootState['user'] }; - return getToken(address, signedMessage, chainId, user); }, ); From bfcd6c4ff94a814593a5043e2a239ef103f6ea41 Mon Sep 17 00:00:00 2001 From: alireza-sharifpour Date: Sun, 22 May 2022 10:44:54 +0430 Subject: [PATCH 117/257] Added UserController to _app.tsx --- pages/_app.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/pages/_app.tsx b/pages/_app.tsx index 7465c79165..c08cf7f6cf 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -66,6 +66,7 @@ function MyApp({ Component, pageProps }: AppProps) { + From 3e6de6bf6c3f90744c851ce940915d5181ee240d Mon Sep 17 00:00:00 2001 From: alireza-sharifpour Date: Sun, 22 May 2022 10:53:12 +0430 Subject: [PATCH 118/257] Removed message from sign ISignToGetToken --- pages/test.tsx | 16 ++++++++++------ src/features/user/user.thunks.ts | 7 ++----- src/features/user/user.types.ts | 1 - 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/pages/test.tsx b/pages/test.tsx index cde148f33a..2c0caf544d 100644 --- a/pages/test.tsx +++ b/pages/test.tsx @@ -2,14 +2,10 @@ import Head from 'next/head'; import styled from 'styled-components'; import { GetServerSideProps } from 'next'; import { useWeb3React } from '@web3-react/core'; -import { useEffect } from 'react'; import { gToast, ToastType } from '@/components/toasts'; import { useAppDispatch, useAppSelector } from '@/features/hooks'; import { fetchXDaiInfoAsync } from '@/features/subgraph/subgraph.thunks'; -import { - fetchUserByAddress, - signToGetToken, -} from '@/features/user/user.thunks'; +import { signToGetToken } from '@/features/user/user.thunks'; const TestRoute = () => { // const xDaiValues = useSelector( @@ -47,7 +43,15 @@ const TestRoute = () => { // }; // }, [library]); // console.log('****data', data); - + function handleSignIn() { + dispatch( + signToGetToken({ + address: account, + chainId, + signer: library?.getSigner(), + }), + ); + } return ( <> diff --git a/src/features/user/user.thunks.ts b/src/features/user/user.thunks.ts index e8266d3690..4c91e01ba9 100644 --- a/src/features/user/user.thunks.ts +++ b/src/features/user/user.thunks.ts @@ -15,12 +15,9 @@ export const fetchUserByAddress = createAsyncThunk( export const signToGetToken = createAsyncThunk( 'user/signToGetToken', - async ( - { message, address, chainId, signer }: ISignToGetToken, - { getState }, - ) => { + async ({ address, chainId, signer }: ISignToGetToken, { getState }) => { const signedMessage = await signMessage( - message, + process.env.NEXT_PUBLIC_OUR_SECRET as string, address, chainId, signer, diff --git a/src/features/user/user.types.ts b/src/features/user/user.types.ts index aaf3412f2f..f5e5f52160 100644 --- a/src/features/user/user.types.ts +++ b/src/features/user/user.types.ts @@ -1,5 +1,4 @@ export interface ISignToGetToken { - message: string; address: string | undefined | null; chainId?: number; signer?: any; From 96e703382159d0e510620a2268c10fe7bd032d23 Mon Sep 17 00:00:00 2001 From: alireza-sharifpour Date: Sun, 22 May 2022 11:28:33 +0430 Subject: [PATCH 119/257] Added balance to store and user controller --- src/components/controller/user.ctrl.tsx | 48 ++++++++++++++++++++++++- src/features/user/user.slice.ts | 7 +++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/src/components/controller/user.ctrl.tsx b/src/components/controller/user.ctrl.tsx index 9c81a7bb83..ccbd96652b 100644 --- a/src/components/controller/user.ctrl.tsx +++ b/src/components/controller/user.ctrl.tsx @@ -1,21 +1,52 @@ import { useWeb3React } from '@web3-react/core'; import { useEffect } from 'react'; +import { formatEther } from '@ethersproject/units'; +import { captureException } from '@sentry/nextjs'; import { useAppDispatch, useAppSelector } from '@/features/hooks'; import { + setBalance, setIsEnabled, setIsSignedIn, setToken, } from '@/features/user/user.slice'; import { isSSRMode } from '@/lib/helpers'; import StorageLabel from '@/lib/localStorage'; +import { fetchUserByAddress } from '@/features/user/user.thunks'; const UserController = () => { - const { account } = useWeb3React(); + const { account, library, chainId } = useWeb3React(); const dispatch = useAppDispatch(); const token = !isSSRMode ? localStorage.getItem(StorageLabel.TOKEN) : null; const isEnabled = useAppSelector(state => state.user.isEnabled); const isSignIn = useAppSelector(state => state.user.isSignedIn); console.log('UserController', isEnabled, isSignIn); + + const getBalance = () => { + if (account && library) { + library + .getBalance(account) + .then((_balance: string) => { + const balance = parseFloat(formatEther(_balance)).toFixed( + 3, + ); + console.log('balance', balance); + dispatch(setBalance(balance)); + }) + .catch((error: unknown) => { + dispatch(setBalance(null)); + captureException(error, { + tags: { + section: 'getBalance', + }, + }); + }); + } + }; + + useEffect(() => { + if (account) dispatch(fetchUserByAddress(account)); + }, [account]); + useEffect(() => { if (account && token) { dispatch(setIsEnabled(true)); @@ -31,6 +62,21 @@ const UserController = () => { } }, [token]); + useEffect(() => { + if (account && library) { + library?.on('block', () => { + getBalance(); + }); + } + return () => { + library?.removeAllListeners('block'); + }; + }, [library]); + + useEffect(() => { + getBalance(); + }, [account, library, chainId]); + return null; }; diff --git a/src/features/user/user.slice.ts b/src/features/user/user.slice.ts index 86e0180cef..cfd5c855c7 100644 --- a/src/features/user/user.slice.ts +++ b/src/features/user/user.slice.ts @@ -8,11 +8,13 @@ const initialState: { token?: string; isEnabled: boolean; isSignedIn: boolean; + balance: string | null; } = { userData: undefined, token: undefined, isEnabled: false, isSignedIn: false, + balance: null, }; export const userSlice = createSlice({ @@ -28,6 +30,9 @@ export const userSlice = createSlice({ setToken: (state, action: PayloadAction) => { state.token = action.payload; }, + setBalance: (state, action: PayloadAction) => { + state.balance = action.payload; + }, signOut: state => { localStorage.removeItem(StorageLabel.USER); localStorage.removeItem(StorageLabel.TOKEN); @@ -63,6 +68,6 @@ export const userSlice = createSlice({ }); }, }); -export const { setIsEnabled, setIsSignedIn, setToken, signOut } = +export const { setIsEnabled, setIsSignedIn, setToken, setBalance, signOut } = userSlice.actions; export default userSlice.reducer; From d0589921ec4e1cf8511e6cc2923dca3e65e584ba Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:07:16 +0430 Subject: [PATCH 120/257] remove old context --- pages/_app.tsx | 14 +++--- src/context/ModalProvider.tsx | 91 ----------------------------------- 2 files changed, 6 insertions(+), 99 deletions(-) delete mode 100644 src/context/ModalProvider.tsx diff --git a/pages/_app.tsx b/pages/_app.tsx index 5a3bbc8855..e4792eeaab 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -12,13 +12,13 @@ import { PriceProvider } from '@/context/price.context'; import { GeneralProvider } from '@/context/general.context'; import { useApollo } from '@/apollo/apolloClient'; import { UserProvider } from '@/context/UserProvider'; -import { ModalProvider } from '@/context/ModalProvider'; import { HeaderWrapper } from '@/components/Header/HeaderWrapper'; import { FooterWrapper } from '@/components/Footer/FooterWrapper'; import '../styles/globals.css'; import { store } from '@/features/store'; import SubgraphController from '@/components/controller/subgraph.ctrl'; +import ModalController from '@/components/controller/modal.ctrl'; import type { AppProps } from 'next/app'; function getLibrary(provider: ExternalProvider) { @@ -63,13 +63,11 @@ function MyApp({ Component, pageProps }: AppProps) { - - - - - - {/* */} - + + + + + diff --git a/src/context/ModalProvider.tsx b/src/context/ModalProvider.tsx deleted file mode 100644 index fb11c7bf81..0000000000 --- a/src/context/ModalProvider.tsx +++ /dev/null @@ -1,91 +0,0 @@ -import React, { - createContext, - ReactNode, - useContext, - useEffect, - useState, -} from 'react'; -import { useWeb3React } from '@web3-react/core'; - -import WalletModal from '@/components/modals/WalletModal'; -import WelcomeModal from '@/components/modals/WelcomeModal'; -import { FirstWelcomeModal } from '@/components/modals/FirstWelcomeModal'; -import { SignWithWalletModal } from '@/components/modals/SignWithWalletModal'; -import { CompleteProfileModal } from '@/components/modals/CompleteProfileModal'; - -interface IModalContext { - actions: { - showWalletModal: () => void; - showSignWithWallet: () => void; - showWelcomeModal: () => void; - showFirstWelcomeModal: () => void; - showCompleteProfile: () => void; - }; -} - -const ModalContext = createContext({ - actions: { - showWalletModal: () => {}, - showWelcomeModal: () => {}, - showFirstWelcomeModal: () => {}, - showSignWithWallet: () => {}, - showCompleteProfile: () => {}, - }, -}); - -ModalContext.displayName = 'ModalContext'; - -export const ModalProvider = (props: { children: ReactNode }) => { - const [showWalletModal, setShowWalletModal] = useState(false); - const [showWelcomeModal, setShowWelcomeModal] = useState(false); - const [showFirstWelcomeModal, setShowFirstWelcomeModal] = useState(false); - const [showSignWithWallet, setShowSignWithWallet] = useState(false); - const [showCompleteProfile, setShowCompleteProfile] = useState(false); - - const { account } = useWeb3React(); - - useEffect(() => { - if (account) { - setShowWelcomeModal(false); - } - }, [account]); - - return ( - setShowSignWithWallet(true), - showWalletModal: () => setShowWalletModal(true), - showFirstWelcomeModal: () => setShowFirstWelcomeModal(true), - showCompleteProfile: () => setShowCompleteProfile(true), - showWelcomeModal: () => setShowWelcomeModal(true), - }, - }} - > - {showWalletModal && ( - - )} - {showSignWithWallet && ( - - )} - {showCompleteProfile && ( - - )} - {showWelcomeModal && ( - - )} - {showFirstWelcomeModal && ( - - )} - {props.children} - - ); -}; - -export default function useModal() { - const context = useContext(ModalContext); - if (!context) { - throw new Error('Modal context not found!'); - } - return context; -} From 90be132774952f15a24818f27f3631c4436fd99a Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:07:24 +0430 Subject: [PATCH 121/257] add store --- src/features/modal/modal.sclie.ts | 41 +++++++++++++++++++++++++++++++ src/features/store.ts | 2 ++ 2 files changed, 43 insertions(+) create mode 100644 src/features/modal/modal.sclie.ts diff --git a/src/features/modal/modal.sclie.ts b/src/features/modal/modal.sclie.ts new file mode 100644 index 0000000000..777912b5f7 --- /dev/null +++ b/src/features/modal/modal.sclie.ts @@ -0,0 +1,41 @@ +import { createSlice, PayloadAction } from '@reduxjs/toolkit'; + +const initialState = { + showWalletModal: false, + showWelcomeModal: false, + showFirstWelcomeModal: false, + showSignWithWallet: false, + showCompleteProfile: false, +}; + +export const ModalSlice = createSlice({ + name: 'modal', + initialState, + reducers: { + setShowSignWithWallet: (state, action: PayloadAction) => { + state.showSignWithWallet = action.payload; + }, + setShowWalletModal: (state, action: PayloadAction) => { + state.showWalletModal = action.payload; + }, + setShowFirstWelcomeModal: (state, action: PayloadAction) => { + state.showFirstWelcomeModal = action.payload; + }, + setShowCompleteProfile: (state, action: PayloadAction) => { + state.showCompleteProfile = action.payload; + }, + setShowWelcomeModal: (state, action: PayloadAction) => { + state.showWelcomeModal = action.payload; + }, + }, +}); + +export const { + setShowCompleteProfile, + setShowFirstWelcomeModal, + setShowSignWithWallet, + setShowWalletModal, + setShowWelcomeModal, +} = ModalSlice.actions; + +export default ModalSlice.reducer; diff --git a/src/features/store.ts b/src/features/store.ts index 9556783eef..9c30d2070b 100644 --- a/src/features/store.ts +++ b/src/features/store.ts @@ -1,10 +1,12 @@ import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit'; // import { subgraphApiSlice } from './subgraph-api-slice'; import subgraphReducer from './subgraph/subgraph.slice'; +import modalReducer from './modal/modal.sclie'; export const store = configureStore({ reducer: { subgraph: subgraphReducer, + modal: modalReducer, }, }); From dbb2da54ffcef2773b8c0a153e6edb55b3d4de18 Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:08:28 +0430 Subject: [PATCH 122/257] add modal ModalController --- src/components/controller/modal.ctrl.tsx | 62 ++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/components/controller/modal.ctrl.tsx diff --git a/src/components/controller/modal.ctrl.tsx b/src/components/controller/modal.ctrl.tsx new file mode 100644 index 0000000000..a20ec74deb --- /dev/null +++ b/src/components/controller/modal.ctrl.tsx @@ -0,0 +1,62 @@ +import WalletModal from '@/components/modals/WalletModal'; +import WelcomeModal from '@/components/modals/WelcomeModal'; +import { FirstWelcomeModal } from '@/components/modals/FirstWelcomeModal'; +import { SignWithWalletModal } from '@/components/modals/SignWithWalletModal'; +import { CompleteProfileModal } from '@/components/modals/CompleteProfileModal'; +import { useAppDispatch, useAppSelector } from '@/features/hooks'; +import { + setShowCompleteProfile, + setShowWelcomeModal, + setShowFirstWelcomeModal, + setShowWalletModal, + setShowSignWithWallet, +} from '@/features/modal/modal.sclie'; + +const ModalController = () => { + const { + showCompleteProfile, + showFirstWelcomeModal, + showSignWithWallet, + showWalletModal, + showWelcomeModal, + } = useAppSelector(state => state.modal); + const dispatch = useAppDispatch(); + + return ( + <> + {showWalletModal && ( + dispatch(setShowWalletModal(state))} + /> + )} + {showSignWithWallet && ( + + dispatch(setShowSignWithWallet(state)) + } + /> + )} + {showCompleteProfile && ( + + dispatch(setShowCompleteProfile(state)) + } + /> + )} + {showWelcomeModal && ( + dispatch(setShowWelcomeModal(state))} + /> + )} + {showFirstWelcomeModal && ( + + dispatch(setShowFirstWelcomeModal(state)) + } + /> + )} + + ); +}; + +export default ModalController; From aca785d8f7d6dde24e3915c3fe5ddb74fe681a4f Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:08:47 +0430 Subject: [PATCH 123/257] use modal slice in ConnectCardContainer --- src/components/cards/Connect.tsx | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/components/cards/Connect.tsx b/src/components/cards/Connect.tsx index f9e7360ca4..d6a3677ef7 100644 --- a/src/components/cards/Connect.tsx +++ b/src/components/cards/Connect.tsx @@ -11,7 +11,8 @@ import useClaim, { GiveDropStateType } from '@/context/claim.context'; import { IClaimViewCardProps } from '../views/claim/Claim.view'; import { formatWeiHelper } from '@/helpers/number'; import Routes from '@/lib/constants/Routes'; -import useModal from '@/context/ModalProvider'; +import { useAppDispatch } from '@/features/hooks'; +import { setShowWalletModal } from '@/features/modal/modal.sclie'; interface IConnectCardContainerProps { data: any; @@ -133,9 +134,7 @@ const WalletCheckButton = styled.button` export const ConnectCard: FC = ({ index }) => { const [walletIsChanged, setWalletIsChanged] = useState(false); - const { - actions: { showWalletModal }, - } = useModal(); + const dispatch = useAppDispatch(); const { totalAmount, @@ -246,7 +245,7 @@ export const ConnectCard: FC = ({ index }) => { onClick={() => { deactivate(); setWalletIsChanged(true); - showWalletModal(); + dispatch(setShowWalletModal(true)); }} > {btnLabel} From 41bfdf3ea4645361b499d0487a9b9b1104701803 Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:08:55 +0430 Subject: [PATCH 124/257] use modal slice in Header --- src/components/Header/Header.tsx | 33 +++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/src/components/Header/Header.tsx b/src/components/Header/Header.tsx index 462a517a90..ad8254368b 100644 --- a/src/components/Header/Header.tsx +++ b/src/components/Header/Header.tsx @@ -38,8 +38,17 @@ import useUser from '@/context/UserProvider'; import { isUserRegistered, shortenAddress } from '@/lib/helpers'; import HeaderRoutesResponsive from './HeaderResponsiveRoutes'; import Routes from '@/lib/constants/Routes'; -import useModal from '@/context/ModalProvider'; -import { currentValuesHelper, useAppSelector } from '@/features/hooks'; +import { + currentValuesHelper, + useAppDispatch, + useAppSelector, +} from '@/features/hooks'; +import { + setShowWalletModal, + setShowWelcomeModal, + setShowSignWithWallet, + setShowCompleteProfile, +} from '@/features/modal/modal.sclie'; export interface IHeader { theme?: ThemeType; @@ -58,17 +67,11 @@ const Header: FC = () => { const { balances } = useAppSelector( state => state.subgraph[currentValuesHelper(chainId)], ); + const dispatch = useAppDispatch(); const { state: { user, isEnabled, isSignedIn }, } = useUser(); - const { - actions: { - showWelcomeModal, - showSignWithWallet, - showCompleteProfile, - showWalletModal, - }, - } = useModal(); + const { theme } = useGeneral(); const router = useRouter(); @@ -115,21 +118,21 @@ const Header: FC = () => { const handleModals = () => { if (isGIVeconomyRoute) { - showWalletModal(); + dispatch(setShowWalletModal(true)); } else { - showWelcomeModal(); + dispatch(setShowWelcomeModal(true)); } }; const handleCreateButton = () => { if (!isEnabled) { - showWelcomeModal(); + dispatch(setShowWelcomeModal(true)); } else if (!isSignedIn) { - showSignWithWallet(); + dispatch(setShowSignWithWallet(true)); } else if (isUserRegistered(user)) { router.push(Routes.CreateProject); } else { - showCompleteProfile(); + dispatch(setShowCompleteProfile(true)); } }; From ed1a8e3dd27fdb91583dc0abf4058683a0c0636c Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:09:06 +0430 Subject: [PATCH 125/257] use modal slice in MenuWallet --- src/components/menu/MenuWallet.tsx | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/components/menu/MenuWallet.tsx b/src/components/menu/MenuWallet.tsx index 4d29af5aec..dcf9dc4033 100644 --- a/src/components/menu/MenuWallet.tsx +++ b/src/components/menu/MenuWallet.tsx @@ -22,7 +22,11 @@ import { MenuContainer } from './Menu.sc'; import { ETheme, useGeneral } from '@/context/general.context'; import { isUserRegistered, networkInfo } from '@/lib/helpers'; import StorageLabel from '@/lib/localStorage'; -import useModal from '@/context/ModalProvider'; +import { useAppDispatch } from '@/features/hooks'; +import { + setShowCompleteProfile, + setShowWalletModal, +} from '@/features/modal/modal.sclie'; const MenuWallet = () => { const [isMounted, setIsMounted] = useState(false); @@ -32,16 +36,11 @@ const MenuWallet = () => { const [queueRoute, setQueueRoute] = useState(''); const router = useRouter(); - + const dispatch = useAppDispatch(); const { state: { user, isSignedIn }, actions: { signOut }, } = useUser(); - - const { - actions: { showCompleteProfile, showWalletModal }, - } = useModal(); - const { theme } = useGeneral(); const goRoute = (input: { @@ -51,7 +50,7 @@ const MenuWallet = () => { }) => { const { url, requiresSign, requiresRegistration } = input; if (requiresRegistration && !isUserRegistered(user)) { - showCompleteProfile(); + dispatch(setShowCompleteProfile(true)); if (url === Routes.CreateProject) return; } if (requiresSign && !isSignedIn) { @@ -113,7 +112,7 @@ const MenuWallet = () => { { window.localStorage.removeItem(StorageLabel.WALLET); - showWalletModal(); + dispatch(setShowWalletModal(true)); }} > Change wallet From f9c841c567d35609f5d5149a80e5095ea6c980e8 Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:09:15 +0430 Subject: [PATCH 126/257] use modal slice in DeactivateProjectModal --- src/components/modals/DeactivateProjectModal.tsx | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/components/modals/DeactivateProjectModal.tsx b/src/components/modals/DeactivateProjectModal.tsx index fcf1eee8e6..2fe7327cbb 100644 --- a/src/components/modals/DeactivateProjectModal.tsx +++ b/src/components/modals/DeactivateProjectModal.tsx @@ -26,8 +26,9 @@ import useUser from '@/context/UserProvider'; import { Modal } from './Modal'; import ArchiveIcon from '../../../public/images/icons/archive_deep.svg'; import Routes from '@/lib/constants/Routes'; -import useModal from '@/context/ModalProvider'; import { IModal } from '@/types/common'; +import { useAppDispatch } from '@/features/hooks'; +import { setShowSignWithWallet } from '@/features/modal/modal.sclie'; interface ISelectObj { value: number; @@ -56,14 +57,11 @@ const DeactivateProjectModal = ({ const [selectedReason, setSelectedReason] = useState( undefined, ); + const dispatch = useAppDispatch(); const { state: { isSignedIn }, } = useUser(); - const { - actions: { showSignWithWallet }, - } = useModal(); - const fetchReasons = async () => { const { data } = await client.query({ query: GET_STATUS_REASONS, @@ -85,7 +83,7 @@ const DeactivateProjectModal = ({ const handleConfirmButton = async () => { if (!!tab && !!selectedReason) { if (!isSignedIn) { - showSignWithWallet(); + dispatch(setShowSignWithWallet(true)); return; } const { data } = await client.mutate({ From e74c8a374bb6409e7164bb3121f461d505db2b48 Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:09:23 +0430 Subject: [PATCH 127/257] use modal slice in SignWithWalletModal --- src/components/modals/SignWithWalletModal.tsx | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/components/modals/SignWithWalletModal.tsx b/src/components/modals/SignWithWalletModal.tsx index 502db51832..f91dbd35e8 100644 --- a/src/components/modals/SignWithWalletModal.tsx +++ b/src/components/modals/SignWithWalletModal.tsx @@ -13,8 +13,9 @@ import { Modal } from '@/components/modals/Modal'; import useUser from '@/context/UserProvider'; import { ETheme, useGeneral } from '@/context/general.context'; import { mediaQueries } from '@/lib/constants/constants'; -import useModal from '@/context/ModalProvider'; import { IModal } from '@/types/common'; +import { useAppDispatch } from '@/features/hooks'; +import { setShowWelcomeModal } from '@/features/modal/modal.sclie'; interface IProps extends IModal { callback?: () => void; @@ -26,9 +27,7 @@ export const SignWithWalletModal: FC = ({ setShowModal, callback }) => { actions: { signToGetToken }, } = useUser(); const { account } = useWeb3React(); - const { - actions: { showWelcomeModal }, - } = useModal(); + const dispatch = useAppDispatch(); return ( = ({ setShowModal, callback }) => { label='SIGN IN' onClick={async () => { if (!account) { - return showWelcomeModal(); + return dispatch(setShowWelcomeModal(true)); } const signature = await signToGetToken(); setShowModal(false); From 384aaa4de8776bfc47035689905c3fa12b9392dc Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:09:32 +0430 Subject: [PATCH 128/257] use modal slice in WalletModal --- src/components/modals/WalletModal.tsx | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/components/modals/WalletModal.tsx b/src/components/modals/WalletModal.tsx index 74258b52ba..5a10842347 100644 --- a/src/components/modals/WalletModal.tsx +++ b/src/components/modals/WalletModal.tsx @@ -17,8 +17,9 @@ import { ETheme } from '@/context/general.context'; import { detectBrave, showToastError } from '@/lib/helpers'; import StorageLabel from '@/lib/localStorage'; import LowerShields from '@/components/modals/LowerShields'; -import useModal from '@/context/ModalProvider'; import { IModal } from '@/types/common'; +import { setShowFirstWelcomeModal } from '@/features/modal/modal.sclie'; +import { useAppDispatch } from '@/features/hooks'; const WalletModal: FC = ({ setShowModal }) => { const [showLowerShields, setShowLowerShields] = useState(); @@ -26,9 +27,7 @@ const WalletModal: FC = ({ setShowModal }) => { const context = useWeb3React(); const { activate, deactivate } = context; const selectedWallet = useWalletName(context); - const { - actions: { showFirstWelcomeModal }, - } = useModal(); + const dispatch = useAppDispatch(); const handleSelect = (selected: IWallet) => { if (selectedWallet !== selected.value) { @@ -41,7 +40,9 @@ const WalletModal: FC = ({ setShowModal }) => { setTimeout(() => { localStorage.setItem(StorageLabel.WALLET, selected.value); activate(selected.connector, showToastError, true) - .then(showFirstWelcomeModal) + .then(() => { + dispatch(setShowFirstWelcomeModal(true)); + }) .catch(error => { showToastError(error); captureException(error, { From 4808ae817023a5593f2459e05e702d05f38671a8 Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:09:42 +0430 Subject: [PATCH 129/257] use modal slice in WelcomeModal --- src/components/modals/WelcomeModal.tsx | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/components/modals/WelcomeModal.tsx b/src/components/modals/WelcomeModal.tsx index 51002863cc..08e41d110f 100644 --- a/src/components/modals/WelcomeModal.tsx +++ b/src/components/modals/WelcomeModal.tsx @@ -15,19 +15,18 @@ import torusBrand from '/public/images/torus_pwr.svg'; import { EWallets, torusConnector } from '@/lib/wallet/walletTypes'; import { mediaQueries } from '@/lib/constants/constants'; import { detectBrave, showToastError } from '@/lib/helpers'; -import useModal from '@/context/ModalProvider'; import StorageLabel from '@/lib/localStorage'; import LowerShields from '@/components/modals/LowerShields'; import { Modal } from './Modal'; import { IModal } from '@/types/common'; +import { useAppDispatch } from '@/features/hooks'; +import { setShowWalletModal } from '@/features/modal/modal.sclie'; const WelcomeModal: FC = ({ setShowModal }) => { const [showLowerShields, setShowLowerShields] = useState(); const { activate } = useWeb3React(); - const { - actions: { showWalletModal }, - } = useModal(); + const dispatch = useAppDispatch(); const closeModal = () => setShowModal(false); @@ -74,7 +73,11 @@ const WelcomeModal: FC = ({ setShowModal }) => { Giveth. - + + dispatch(setShowWalletModal(true)) + } + > Ether icon Sign in with Ethereum From f0c517a2fff8d50b534f758aabae40ad8c4b2a9f Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:09:52 +0430 Subject: [PATCH 130/257] use modal slice in ProjectCardLikeAndShareButtons --- .../project-card/ProjectCardLikeAndShareButtons.tsx | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/components/project-card/ProjectCardLikeAndShareButtons.tsx b/src/components/project-card/ProjectCardLikeAndShareButtons.tsx index 7be46008af..2195e08029 100644 --- a/src/components/project-card/ProjectCardLikeAndShareButtons.tsx +++ b/src/components/project-card/ProjectCardLikeAndShareButtons.tsx @@ -13,10 +13,11 @@ import { captureException } from '@sentry/nextjs'; import ShareModal from '../modals/ShareModal'; import { likeProject, unlikeProject } from '@/lib/reaction'; import { showToastError } from '@/lib/helpers'; -import useModal from '@/context/ModalProvider'; import { Flex } from '../styled-components/Flex'; import { IProject } from '@/apollo/types/types'; import useUser from '@/context/UserProvider'; +import { useAppDispatch } from '@/features/hooks'; +import { setShowSignWithWallet } from '@/features/modal/modal.sclie'; interface IProjectCardLikeAndShareButtons { project: IProject; @@ -30,25 +31,20 @@ const ProjectCardLikeAndShareButtons = ( actions: { incrementLikedProjectsCount, decrementLikedProjectsCount }, } = useUser(); - const { - actions: { showSignWithWallet }, - } = useModal(); - const [showModal, setShowModal] = useState(false); - const { project } = props; const { slug, id: projectId } = project; - const [reaction, setReaction] = useState(project.reaction); const [totalReactions, setTotalReactions] = useState( project.totalReactions, ); const [loading, setLoading] = useState(false); + const dispatch = useAppDispatch(); const likeUnlikeProject = async (e: MouseEvent) => { e.stopPropagation(); if (!isSignedIn) { - showSignWithWallet(); + dispatch(setShowSignWithWallet(true)); return; } From 2eb7bb02a81c5824efff63ae2b69ab5885aee64a Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:10:02 +0430 Subject: [PATCH 131/257] use modal slice in EditIndex --- src/components/views/EditIndex.tsx | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/components/views/EditIndex.tsx b/src/components/views/EditIndex.tsx index 58017afc5b..cfbe87a095 100644 --- a/src/components/views/EditIndex.tsx +++ b/src/components/views/EditIndex.tsx @@ -12,19 +12,21 @@ import { showToastError, } from '@/lib/helpers'; import CreateProject from '@/components/views/create/CreateProject'; -import useModal from '@/context/ModalProvider'; +import { useAppDispatch } from '@/features/hooks'; +import { + setShowCompleteProfile, + setShowSignWithWallet, + setShowWelcomeModal, +} from '@/features/modal/modal.sclie'; const EditIndex = () => { const [project, setProject] = useState(); + const dispatch = useAppDispatch(); const { state: { user, isSignedIn }, } = useUser(); - const { - actions: { showWelcomeModal, showSignWithWallet, showCompleteProfile }, - } = useModal(); - const router = useRouter(); const projectId = router?.query.projectIdSlug as string; @@ -33,11 +35,11 @@ const EditIndex = () => { if (userAddress) { if (project) setProject(undefined); if (!isUserRegistered(user)) { - showCompleteProfile(); + dispatch(setShowCompleteProfile(true)); return; } if (!isSignedIn) { - showSignWithWallet(); + dispatch(setShowSignWithWallet(true)); return; } client @@ -67,7 +69,7 @@ const EditIndex = () => { }); }); } else { - showWelcomeModal(); + dispatch(setShowWelcomeModal(true)); } }, [user, isSignedIn]); From 01f17906dd7d3ef61438f45ce68d506be795543c Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:10:18 +0430 Subject: [PATCH 132/257] use modal slice in CreateIndex --- src/components/views/create/CreateIndex.tsx | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/components/views/create/CreateIndex.tsx b/src/components/views/create/CreateIndex.tsx index 8cbaed0fc2..d61f7366e1 100644 --- a/src/components/views/create/CreateIndex.tsx +++ b/src/components/views/create/CreateIndex.tsx @@ -2,30 +2,32 @@ import React, { useEffect } from 'react'; import CreateProject from '@/components/views/create/CreateProject'; import useUser from '@/context/UserProvider'; import { isUserRegistered } from '@/lib/helpers'; -import useModal from '@/context/ModalProvider'; +import { useAppDispatch } from '@/features/hooks'; +import { + setShowCompleteProfile, + setShowSignWithWallet, + setShowWelcomeModal, +} from '@/features/modal/modal.sclie'; const CreateIndex = () => { + const dispatch = useAppDispatch(); const { state: { user, isSignedIn, isEnabled }, } = useUser(); - const { - actions: { showWelcomeModal, showSignWithWallet, showCompleteProfile }, - } = useModal(); - const isRegistered = isUserRegistered(user); useEffect(() => { if (isEnabled) { if (!isRegistered) { - showCompleteProfile(); + dispatch(setShowCompleteProfile(true)); return; } if (!isSignedIn) { - showSignWithWallet(); + dispatch(setShowSignWithWallet(true)); } } else { - showWelcomeModal(); + dispatch(setShowWelcomeModal(true)); } }, [user, isSignedIn]); From 5d318de25d179c925e8e61efc27b994f4d30efbb Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:10:32 +0430 Subject: [PATCH 133/257] use modal slice in CryptoDonation --- .../views/donate/CryptoDonation.tsx | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/components/views/donate/CryptoDonation.tsx b/src/components/views/donate/CryptoDonation.tsx index 395c6797c5..76e6cbd683 100644 --- a/src/components/views/donate/CryptoDonation.tsx +++ b/src/components/views/donate/CryptoDonation.tsx @@ -51,11 +51,15 @@ import { prepareTokenList, } from '@/components/views/donate/helpers'; import { ORGANIZATION } from '@/lib/constants/organizations'; -import useModal from '@/context/ModalProvider'; import { getERC20Info } from '@/lib/contracts'; import GIVBackToast from '@/components/views/donate/GIVBackToast'; import { DonateWrongNetwork } from '@/components/modals/DonateWrongNetwork'; import FailedDonation from '@/components/modals/FailedDonation'; +import { useAppDispatch } from '@/features/hooks'; +import { + setShowSignWithWallet, + setShowWalletModal, +} from '@/features/modal/modal.sclie'; const ethereumChain = config.PRIMARY_NETWORK; const xdaiChain = config.SECONDARY_NETWORK; @@ -77,13 +81,11 @@ const CryptoDonation = (props: { project: IProject; }) => { const { chainId: networkId, account, library } = useWeb3React(); + const dispatch = useAppDispatch(); const { state: { isSignedIn, isEnabled, balance }, } = useUser(); const { ethPrice } = usePrice(); - const { - actions: { showWalletModal, showSignWithWallet }, - } = useModal(); const { project, setSuccessDonation } = props; const { organization, verified, id: projectId, status } = project; @@ -310,7 +312,7 @@ const CryptoDonation = (props: { ); } if (!isSignedIn) { - return showSignWithWallet(); + return dispatch(setShowSignWithWallet(true)); } setShowDonateModal(true); }; @@ -469,12 +471,17 @@ const CryptoDonation = (props: { /> Want to use another wallet?{' '} - Change Wallet + dispatch(setShowWalletModal(true))}> + Change Wallet + )} {!isEnabled && ( - + dispatch(setShowWalletModal(true))} + /> )} ); From 8adcde758eecfd400b61da6426c980901960ffe9 Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:10:42 +0430 Subject: [PATCH 134/257] use modal slice in HomeChangeMakers --- src/components/views/homepage/HomeChangeMakers.tsx | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/components/views/homepage/HomeChangeMakers.tsx b/src/components/views/homepage/HomeChangeMakers.tsx index 8d5034d722..a5f241c18f 100644 --- a/src/components/views/homepage/HomeChangeMakers.tsx +++ b/src/components/views/homepage/HomeChangeMakers.tsx @@ -9,7 +9,8 @@ import useUser from '@/context/UserProvider'; import { HomeContainer } from '@/components/views/homepage/Home.sc'; import { mediaQueries } from '@/lib/constants/constants'; import { Col } from '@/components/Grid'; -import useModal from '@/context/ModalProvider'; +import { useAppDispatch } from '@/features/hooks'; +import { setShowCompleteProfile } from '@/features/modal/modal.sclie'; const content = [ { @@ -36,19 +37,17 @@ const content = [ const HomeChangeMakers = () => { const router = useRouter(); + const dispatch = useAppDispatch(); + const { state: { user }, } = useUser(); - const { - actions: { showCompleteProfile }, - } = useModal(); - const handleCreateButton = () => { if (isUserRegistered(user)) { router.push(Routes.CreateProject); } else { - showCompleteProfile(); + dispatch(setShowCompleteProfile(true)); } }; From f21690d5e03ee6d1e7f1f2f2a58f2d0e4d9a3e72 Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:10:49 +0430 Subject: [PATCH 135/257] use modal slice in HomeExploreProjects --- src/components/views/homepage/HomeExploreProjects.tsx | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/components/views/homepage/HomeExploreProjects.tsx b/src/components/views/homepage/HomeExploreProjects.tsx index b960083fa8..4daf90ef68 100644 --- a/src/components/views/homepage/HomeExploreProjects.tsx +++ b/src/components/views/homepage/HomeExploreProjects.tsx @@ -15,7 +15,8 @@ import { isUserRegistered } from '@/lib/helpers'; import { FlexCenter } from '@/components/styled-components/Flex'; import useUser from '@/context/UserProvider'; import { deviceSize, mediaQueries } from '@/lib/constants/constants'; -import useModal from '@/context/ModalProvider'; +import { useAppDispatch } from '@/features/hooks'; +import { setShowCompleteProfile } from '@/features/modal/modal.sclie'; interface IHomeExploreProjects { projects: IProject[]; @@ -27,19 +28,16 @@ const HomeExploreProjects = (props: IHomeExploreProjects) => { const { projects, totalCount, noTitle } = props; const router = useRouter(); + const dispatch = useAppDispatch(); const { state: { user }, } = useUser(); - const { - actions: { showCompleteProfile }, - } = useModal(); - const handleCreateButton = () => { if (isUserRegistered(user)) { router.push(Routes.CreateProject); } else { - showCompleteProfile(); + dispatch(setShowCompleteProfile(true)); } }; From ceb3829fc1bef8003cccafb4aed9df7a4135035c Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:10:59 +0430 Subject: [PATCH 136/257] use modal slice in HomeHeader --- src/components/views/homepage/HomeHeader.tsx | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/components/views/homepage/HomeHeader.tsx b/src/components/views/homepage/HomeHeader.tsx index 3fd7cf19b5..291f3fc00c 100644 --- a/src/components/views/homepage/HomeHeader.tsx +++ b/src/components/views/homepage/HomeHeader.tsx @@ -8,23 +8,21 @@ import { Arc } from '@/components/styled-components/Arc'; import useUser from '@/context/UserProvider'; import { isUserRegistered } from '@/lib/helpers'; import { mediaQueries } from '@/lib/constants/constants'; -import useModal from '@/context/ModalProvider'; +import { useAppDispatch } from '@/features/hooks'; +import { setShowCompleteProfile } from '@/features/modal/modal.sclie'; const HomeHeader = () => { const router = useRouter(); + const dispatch = useAppDispatch(); const { state: { user }, } = useUser(); - const { - actions: { showCompleteProfile }, - } = useModal(); - const handleCreateButton = () => { if (isUserRegistered(user)) { router.push(Routes.CreateProject); } else { - showCompleteProfile(); + dispatch(setShowCompleteProfile(true)); } }; From 97eb72bf725de05fc320d94b67d3a76c3ade07f9 Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:11:09 +0430 Subject: [PATCH 137/257] use modal slice in HomePurpleSection --- src/components/views/homepage/HomePurpleSection.tsx | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/components/views/homepage/HomePurpleSection.tsx b/src/components/views/homepage/HomePurpleSection.tsx index a1ebbf2e46..48d04219d3 100644 --- a/src/components/views/homepage/HomePurpleSection.tsx +++ b/src/components/views/homepage/HomePurpleSection.tsx @@ -20,23 +20,21 @@ import { Col, Row } from '@/components/Grid'; import { Arc } from '@/components/styled-components/Arc'; import { HomeContainer } from '@/components/views/homepage/Home.sc'; import { deviceSize, mediaQueries } from '@/lib/constants/constants'; -import useModal from '@/context/ModalProvider'; +import { useAppDispatch } from '@/features/hooks'; +import { setShowCompleteProfile } from '@/features/modal/modal.sclie'; const HomePurpleSection = () => { const router = useRouter(); + const dispatch = useAppDispatch(); const { state: { user }, } = useUser(); - const { - actions: { showCompleteProfile }, - } = useModal(); - const handleCreateButton = () => { if (isUserRegistered(user)) { router.push(Routes.CreateProject); } else { - showCompleteProfile(); + dispatch(setShowCompleteProfile(true)); } }; From 2481015e1e94a65b59ae535f2356ebe738045bcd Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:11:18 +0430 Subject: [PATCH 138/257] use modal slice in OnboardActions --- src/components/views/onboarding/common.tsx | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/components/views/onboarding/common.tsx b/src/components/views/onboarding/common.tsx index 5af01a587c..cb2a01a0be 100644 --- a/src/components/views/onboarding/common.tsx +++ b/src/components/views/onboarding/common.tsx @@ -5,7 +5,8 @@ import styled from 'styled-components'; import { Col, Row } from '@/components/Grid'; import useUser from '@/context/UserProvider'; import { OnboardSteps } from './Onboarding.view'; -import useModal from '@/context/ModalProvider'; +import { useAppDispatch } from '@/features/hooks'; +import { setShowSignWithWallet } from '@/features/modal/modal.sclie'; export const OnboardStep = styled(Col)` margin: 0 auto; @@ -27,24 +28,21 @@ export const OnboardActions: FC = ({ onLater, disabled, }) => { + const dispatch = useAppDispatch(); const { state: { isSignedIn }, actions: { reFetchUser }, } = useUser(); - const { - actions: { showSignWithWallet }, - } = useModal(); - useEffect(() => { if (!isSignedIn) { - showSignWithWallet(); + dispatch(setShowSignWithWallet(true)); } }, [isSignedIn]); const handleSave = async () => { if (!isSignedIn) { - showSignWithWallet(); + dispatch(setShowSignWithWallet(true)); } else { const res = await onSave(); if (res) { From 67ac71aab857d073da5636f021fd2161bc34d9c5 Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:11:29 +0430 Subject: [PATCH 139/257] use modal slice in DoneStep --- src/components/views/onboarding/DoneStep.tsx | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/components/views/onboarding/DoneStep.tsx b/src/components/views/onboarding/DoneStep.tsx index 1128a8989e..e4a8449800 100644 --- a/src/components/views/onboarding/DoneStep.tsx +++ b/src/components/views/onboarding/DoneStep.tsx @@ -18,7 +18,8 @@ import Routes from '@/lib/constants/Routes'; import useUser from '@/context/UserProvider'; import { isUserRegistered } from '@/lib/helpers'; import { Col, Row } from '@/components/Grid'; -import useModal from '@/context/ModalProvider'; +import { useAppDispatch } from '@/features/hooks'; +import { setShowCompleteProfile } from '@/features/modal/modal.sclie'; const CongratsAnimationOptions = { loop: true, @@ -29,21 +30,17 @@ const CongratsAnimationOptions = { }; const DoneStep = () => { + const router = useRouter(); + const dispatch = useAppDispatch(); const { state: { user }, } = useUser(); - const { - actions: { showCompleteProfile }, - } = useModal(); - - const router = useRouter(); - const handleCreateButton = () => { if (isUserRegistered(user)) { router.push(Routes.CreateProject); } else { - showCompleteProfile(); + dispatch(setShowCompleteProfile(true)); } }; From a8981c5ccecaf63986ecdc2ce2e2944c9ed3d48b Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:11:42 +0430 Subject: [PATCH 140/257] use modal slice in ProjectDonateCard --- src/components/views/project/ProjectDonateCard.tsx | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/components/views/project/ProjectDonateCard.tsx b/src/components/views/project/ProjectDonateCard.tsx index 8ed6dae549..8011ce1464 100644 --- a/src/components/views/project/ProjectDonateCard.tsx +++ b/src/components/views/project/ProjectDonateCard.tsx @@ -42,7 +42,8 @@ import ProjectCardOrgBadge from '../../project-card/ProjectCardOrgBadge'; import ExternalLink from '@/components/ExternalLink'; import InternalLink from '@/components/InternalLink'; import Routes from '@/lib/constants/Routes'; -import useModal from '@/context/ModalProvider'; +import { useAppDispatch } from '@/features/hooks'; +import { setShowSignWithWallet } from '@/features/modal/modal.sclie'; interface IProjectDonateCard { project?: IProject; @@ -63,15 +64,12 @@ const ProjectDonateCard = ({ setIsDraft, setCreationSuccessful, }: IProjectDonateCard) => { + const dispatch = useAppDispatch(); const { state: { user, isSignedIn }, actions: { incrementLikedProjectsCount, decrementLikedProjectsCount }, } = useUser(); - const { - actions: { showSignWithWallet }, - } = useModal(); - const { categories = [], slug, @@ -100,7 +98,7 @@ const ProjectDonateCard = ({ const likeUnlikeProject = async () => { if (!isSignedIn) { - showSignWithWallet(); + dispatch(setShowSignWithWallet(true)); return; } if (loading) return; @@ -187,7 +185,7 @@ const ProjectDonateCard = ({ } else { try { if (!isSignedIn) { - showSignWithWallet(); + dispatch(setShowSignWithWallet(true)); return; } const { data } = await client.mutate({ From 565b1d466e388c129972e8699ab433e3d0be8a2a Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:11:50 +0430 Subject: [PATCH 141/257] use modal slice in ProjectUpdates --- src/components/views/project/ProjectUpdates.tsx | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/components/views/project/ProjectUpdates.tsx b/src/components/views/project/ProjectUpdates.tsx index a867e929be..e547ca9d6c 100644 --- a/src/components/views/project/ProjectUpdates.tsx +++ b/src/components/views/project/ProjectUpdates.tsx @@ -22,8 +22,9 @@ import ProjectTimeline, { TimelineSection } from './ProjectTimeline'; import { IProject, IProjectUpdate } from '@/apollo/types/types'; import { RemoveUpdateModal } from '@/components/modals/RemoveUpdateModal'; import { mediaQueries } from '@/lib/constants/constants'; -import useModal from '@/context/ModalProvider'; import useUser from '@/context/UserProvider'; +import { useAppDispatch } from '@/features/hooks'; +import { setShowSignWithWallet } from '@/features/modal/modal.sclie'; const RichTextInput = dynamic(() => import('@/components/RichTextInput'), { ssr: false, @@ -38,14 +39,11 @@ const ProjectUpdates = (props: { const { project, fetchProject } = props; const { id, creationDate, adminUser } = project || {}; + const dispatch = useAppDispatch(); const { state: { user, isSignedIn }, } = useUser(); - const { - actions: { showSignWithWallet }, - } = useModal(); - const [newUpdate, setNewUpdate] = useState(''); const [title, setTitle] = useState(''); const [currentUpdate, setCurrentUpdate] = useState(''); @@ -151,7 +149,7 @@ const ProjectUpdates = (props: { const addUpdate = async () => { try { if (!isSignedIn) { - showSignWithWallet(); + dispatch(setShowSignWithWallet(true)); return; } if (!newUpdate) { From 7ef8410225e1b2a0195370ab807bb356fc7f30da Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:12:13 +0430 Subject: [PATCH 142/257] use modal slice in ProjectsIndex --- src/components/views/projects/ProjectsIndex.tsx | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/components/views/projects/ProjectsIndex.tsx b/src/components/views/projects/ProjectsIndex.tsx index e363d0c390..e270ee8241 100644 --- a/src/components/views/projects/ProjectsIndex.tsx +++ b/src/components/views/projects/ProjectsIndex.tsx @@ -32,7 +32,8 @@ import ProjectsNoResults from '@/components/views/projects/ProjectsNoResults'; import { Shadow } from '../../styled-components/Shadow'; import useUser from '@/context/UserProvider'; import { deviceSize, mediaQueries } from '@/lib/constants/constants'; -import useModal from '@/context/ModalProvider'; +import { useAppDispatch } from '@/features/hooks'; +import { setShowCompleteProfile } from '@/features/modal/modal.sclie'; interface IProjectsView { projects: IProject[]; @@ -90,10 +91,6 @@ const ProjectsIndex = (props: IProjectsView) => { state: { user }, } = useUser(); - const { - actions: { showCompleteProfile }, - } = useModal(); - const [categoriesObj, setCategoriesObj] = useState(); const [selectedCategory, setSelectedCategory] = useState(allCategoryObj); @@ -105,12 +102,12 @@ const ProjectsIndex = (props: IProjectsView) => { const [searchValue, setSearchValue] = useState(''); const [totalCount, setTotalCount] = useState(_totalCount); + const dispatch = useAppDispatch(); + const router = useRouter(); const isFirstRender = useRef(true); const debouncedSearch = useRef(); const pageNum = useRef(0); - const router = useRouter(); - useEffect(() => { setCategoriesObj(buildCategoryObj(categories)); debouncedSearch.current = Debounced(setSearch, 1000); @@ -199,7 +196,7 @@ const ProjectsIndex = (props: IProjectsView) => { if (isUserRegistered(user)) { router.push(Routes.CreateProject); } else { - showCompleteProfile(); + dispatch(setShowCompleteProfile(true)); } }; From bfbfeda3ee8cc4f7e857b84861baf330b4d6c434 Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:12:21 +0430 Subject: [PATCH 143/257] use modal slice in IncompleteProfileToast --- .../views/userPublicProfile/IncompleteProfileToast.tsx | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/components/views/userPublicProfile/IncompleteProfileToast.tsx b/src/components/views/userPublicProfile/IncompleteProfileToast.tsx index b9e10d1fc9..2163b0b9b0 100644 --- a/src/components/views/userPublicProfile/IncompleteProfileToast.tsx +++ b/src/components/views/userPublicProfile/IncompleteProfileToast.tsx @@ -6,17 +6,16 @@ import { IconX, } from '@giveth/ui-design-system'; import styled from 'styled-components'; -import useModal from '@/context/ModalProvider'; import { mediaQueries } from '@/lib/constants/constants'; +import { useAppDispatch } from '@/features/hooks'; +import { setShowCompleteProfile } from '@/features/modal/modal.sclie'; interface IIncompleteToast { close: () => void; } const IncompleteProfileToast = ({ close }: IIncompleteToast) => { - const { - actions: { showCompleteProfile }, - } = useModal(); + const dispatch = useAppDispatch(); return ( @@ -37,7 +36,7 @@ const IncompleteProfileToast = ({ close }: IIncompleteToast) => { size='small' label="LET'S DO IT" buttonType='texty' - onClick={showCompleteProfile} + onClick={() => dispatch(setShowCompleteProfile(true))} /> ); From c1ac3b4f797820c6ada07bacaa73636b69a37aba Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:12:54 +0430 Subject: [PATCH 144/257] use modal slice in PublicProfileOverviewTab --- .../userPublicProfile/PublicProfileOverviewTab.tsx | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/components/views/userPublicProfile/PublicProfileOverviewTab.tsx b/src/components/views/userPublicProfile/PublicProfileOverviewTab.tsx index a9521e85c6..438980098b 100644 --- a/src/components/views/userPublicProfile/PublicProfileOverviewTab.tsx +++ b/src/components/views/userPublicProfile/PublicProfileOverviewTab.tsx @@ -14,9 +14,10 @@ import Routes from '@/lib/constants/Routes'; import ContributeCard from './PublicProfileContributeCard'; import { Flex } from '@/components/styled-components/Flex'; import { isUserRegistered } from '@/lib/helpers'; -import useModal from '@/context/ModalProvider'; import { IUserPublicProfileView } from '@/components/views/userPublicProfile/UserPublicProfile.view'; import { mediaQueries } from '@/lib/constants/constants'; +import { useAppDispatch } from '@/features/hooks'; +import { setShowCompleteProfile } from '@/features/modal/modal.sclie'; interface IBtnProps extends IButtonProps { outline?: boolean; @@ -30,16 +31,13 @@ interface ISection { const PublicProfileOverviewTab: FC = ({ user }) => { const router = useRouter(); - - const { - actions: { showCompleteProfile }, - } = useModal(); + const dispatch = useAppDispatch(); const handleCreateButton = () => { if (isUserRegistered(user)) { router.push(Routes.CreateProject); } else { - showCompleteProfile(); + dispatch(setShowCompleteProfile(true)); } }; From cb544d32ebb6c19b10fdb407b514aa47ff0ebb0e Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 22 May 2022 12:13:05 +0430 Subject: [PATCH 145/257] use modal slice in UserPublicProfileView --- .../views/userPublicProfile/UserPublicProfile.view.tsx | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/components/views/userPublicProfile/UserPublicProfile.view.tsx b/src/components/views/userPublicProfile/UserPublicProfile.view.tsx index c31a7cdbd8..cc0b989b08 100644 --- a/src/components/views/userPublicProfile/UserPublicProfile.view.tsx +++ b/src/components/views/userPublicProfile/UserPublicProfile.view.tsx @@ -22,10 +22,11 @@ import { shortenAddress, } from '@/lib/helpers'; import { Container } from '@/components/Grid'; -import useModal from '@/context/ModalProvider'; import { EDirection } from '@/apollo/types/gqlEnums'; import ExternalLink from '@/components/ExternalLink'; import IncompleteProfileToast from '@/components/views/userPublicProfile/IncompleteProfileToast'; +import { useAppDispatch } from '@/features/hooks'; +import { setShowSignWithWallet } from '@/features/modal/modal.sclie'; export enum EOrderBy { TokenAmount = 'TokenAmount', @@ -48,14 +49,11 @@ const UserPublicProfileView: FC = ({ user, myAccount, }) => { + const dispatch = useAppDispatch(); const { state: { isSignedIn }, } = useUser(); - const { - actions: { showSignWithWallet }, - } = useModal(); - const { chainId } = useWeb3React(); const [showModal, setShowModal] = useState(false); // follow this state to refresh user content on screen @@ -65,7 +63,7 @@ const UserPublicProfileView: FC = ({ useEffect(() => { if (myAccount && !isSignedIn) { - showSignWithWallet(); + dispatch(setShowSignWithWallet(true)); } }, [user, isSignedIn]); From d57675777eae56167736a3a15d9ab23e3bf36788 Mon Sep 17 00:00:00 2001 From: alireza-sharifpour Date: Sun, 22 May 2022 12:43:03 +0430 Subject: [PATCH 146/257] Removed Usercontext and Handled SignIn action and set token in store from localStorage and read userdata from redux in UserPublicProfileView --- pages/_app.tsx | 21 ++++--- pages/account.tsx | 7 +-- src/components/controller/user.ctrl.tsx | 14 ++++- src/components/modals/SignWithWalletModal.tsx | 17 ++++-- .../UserPublicProfile.view.tsx | 59 ++++++++++--------- src/features/user/user.slice.ts | 21 ++++++- 6 files changed, 86 insertions(+), 53 deletions(-) diff --git a/pages/_app.tsx b/pages/_app.tsx index c08cf7f6cf..d751376430 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -11,7 +11,6 @@ import { Provider } from 'react-redux'; import { PriceProvider } from '@/context/price.context'; import { GeneralProvider } from '@/context/general.context'; import { useApollo } from '@/apollo/apolloClient'; -import { UserProvider } from '@/context/UserProvider'; import { ModalProvider } from '@/context/ModalProvider'; import { HeaderWrapper } from '@/components/Header/HeaderWrapper'; import { FooterWrapper } from '@/components/Footer/FooterWrapper'; @@ -63,16 +62,16 @@ function MyApp({ Component, pageProps }: AppProps) { - - - - - - - - {/* */} - - + {/* */} + + + + + + + {/* */} + + {/* */} diff --git a/pages/account.tsx b/pages/account.tsx index 9f4ce6e9e5..a0b4ecaaf6 100644 --- a/pages/account.tsx +++ b/pages/account.tsx @@ -3,16 +3,15 @@ import { H5 } from '@giveth/ui-design-system'; import Head from 'next/head'; import { FC } from 'react'; import UserPublicProfileView from '@/components/views/userPublicProfile/UserPublicProfile.view'; -import useUser from '@/context/UserProvider'; +import { useAppSelector } from '@/features/hooks'; const NoUserContainer = styled.div` padding: 200px; `; const UserRoute: FC = () => { - const { - state: { user }, - } = useUser(); + const user = useAppSelector(state => state.user.userData); + console.log('user', user); return ( <> diff --git a/src/components/controller/user.ctrl.tsx b/src/components/controller/user.ctrl.tsx index ccbd96652b..474cf35f32 100644 --- a/src/components/controller/user.ctrl.tsx +++ b/src/components/controller/user.ctrl.tsx @@ -12,15 +12,15 @@ import { import { isSSRMode } from '@/lib/helpers'; import StorageLabel from '@/lib/localStorage'; import { fetchUserByAddress } from '@/features/user/user.thunks'; +import { walletsArray } from '@/lib/wallet/walletTypes'; const UserController = () => { - const { account, library, chainId } = useWeb3React(); + const { account, library, chainId, activate } = useWeb3React(); const dispatch = useAppDispatch(); const token = !isSSRMode ? localStorage.getItem(StorageLabel.TOKEN) : null; const isEnabled = useAppSelector(state => state.user.isEnabled); const isSignIn = useAppSelector(state => state.user.isSignedIn); console.log('UserController', isEnabled, isSignIn); - const getBalance = () => { if (account && library) { library @@ -43,6 +43,16 @@ const UserController = () => { } }; + useEffect(() => { + const selectedWalletName = localStorage.getItem(StorageLabel.WALLET); + const wallet = walletsArray.find(w => w.value === selectedWalletName); + if (wallet) { + activate(wallet.connector, err => { + console.log('err', err); + }); + } + }, [activate]); + useEffect(() => { if (account) dispatch(fetchUserByAddress(account)); }, [account]); diff --git a/src/components/modals/SignWithWalletModal.tsx b/src/components/modals/SignWithWalletModal.tsx index 502db51832..37d5849cb6 100644 --- a/src/components/modals/SignWithWalletModal.tsx +++ b/src/components/modals/SignWithWalletModal.tsx @@ -10,11 +10,12 @@ import { import { useWeb3React } from '@web3-react/core'; import { Modal } from '@/components/modals/Modal'; -import useUser from '@/context/UserProvider'; import { ETheme, useGeneral } from '@/context/general.context'; import { mediaQueries } from '@/lib/constants/constants'; import useModal from '@/context/ModalProvider'; import { IModal } from '@/types/common'; +import { useAppDispatch } from '@/features/hooks'; +import { signToGetToken } from '@/features/user/user.thunks'; interface IProps extends IModal { callback?: () => void; @@ -22,10 +23,8 @@ interface IProps extends IModal { export const SignWithWalletModal: FC = ({ setShowModal, callback }) => { const { theme } = useGeneral(); - const { - actions: { signToGetToken }, - } = useUser(); - const { account } = useWeb3React(); + const dispatch = useAppDispatch(); + const { account, library, chainId } = useWeb3React(); const { actions: { showWelcomeModal }, } = useModal(); @@ -52,7 +51,13 @@ export const SignWithWalletModal: FC = ({ setShowModal, callback }) => { if (!account) { return showWelcomeModal(); } - const signature = await signToGetToken(); + const signature = await dispatch( + signToGetToken({ + address: account, + chainId, + signer: library?.getSigner(), + }), + ); setShowModal(false); !!signature && callback && callback(); }} diff --git a/src/components/views/userPublicProfile/UserPublicProfile.view.tsx b/src/components/views/userPublicProfile/UserPublicProfile.view.tsx index c31a7cdbd8..0ea2b114f3 100644 --- a/src/components/views/userPublicProfile/UserPublicProfile.view.tsx +++ b/src/components/views/userPublicProfile/UserPublicProfile.view.tsx @@ -15,7 +15,6 @@ import PublicProfileContributes from './PublicProfileContributes'; import { IUser } from '@/apollo/types/types'; import EditUserModal from '@/components/modals/EditUserModal'; import { Flex, FlexCenter } from '@/components/styled-components/Flex'; -import useUser from '@/context/UserProvider'; import { formatWalletLink, isUserRegistered, @@ -26,6 +25,7 @@ import useModal from '@/context/ModalProvider'; import { EDirection } from '@/apollo/types/gqlEnums'; import ExternalLink from '@/components/ExternalLink'; import IncompleteProfileToast from '@/components/views/userPublicProfile/IncompleteProfileToast'; +import { useAppSelector } from '@/features/hooks'; export enum EOrderBy { TokenAmount = 'TokenAmount', @@ -44,14 +44,11 @@ export interface IUserPublicProfileView { myAccount?: boolean; } -const UserPublicProfileView: FC = ({ - user, - myAccount, -}) => { - const { - state: { isSignedIn }, - } = useUser(); +const UserPublicProfileView: FC = ({ myAccount }) => { + const { isSignedIn } = useAppSelector(state => state.user); + const userData = useAppSelector(state => state.user.userData); + console.log('UserPublic', userData); const { actions: { showSignWithWallet }, } = useModal(); @@ -61,15 +58,15 @@ const UserPublicProfileView: FC = ({ const [showModal, setShowModal] = useState(false); // follow this state to refresh user content on screen const [showIncompleteWarning, setShowIncompleteWarning] = useState(true); const showCompleteProfile = - !isUserRegistered(user) && showIncompleteWarning && myAccount; + !isUserRegistered(userData) && showIncompleteWarning && myAccount; useEffect(() => { if (myAccount && !isSignedIn) { showSignWithWallet(); } - }, [user, isSignedIn]); + }, [userData, isSignedIn]); - if (!user || (myAccount && !isSignedIn)) + if (!userData || (myAccount && !isSignedIn)) return (
Not logged in
@@ -87,36 +84,40 @@ const UserPublicProfileView: FC = ({ )} {user.name} -

{user.name}

- {user.email && ( - {user.email} +

{userData?.name}

+ {userData?.email && ( + {userData?.email} )} - {myAccount && user?.name && user?.email && ( - setShowModal(true)} - > - Edit Profile - - )} + {myAccount && + userData?.name && + userData?.email && ( + setShowModal(true)} + > + Edit Profile + + )} - {user.walletAddress} + {userData?.walletAddress} - {shortenAddress(user.walletAddress)} + {shortenAddress( + userData?.walletAddress, + )} @@ -128,9 +129,9 @@ const UserPublicProfileView: FC = ({
- + {showModal && ( - + )} ); diff --git a/src/features/user/user.slice.ts b/src/features/user/user.slice.ts index cfd5c855c7..effe9ff0c7 100644 --- a/src/features/user/user.slice.ts +++ b/src/features/user/user.slice.ts @@ -2,6 +2,7 @@ import { createSlice, PayloadAction } from '@reduxjs/toolkit'; import { IUser } from '@/apollo/types/types'; import { fetchUserByAddress, signToGetToken } from './user.thunks'; import StorageLabel from '@/lib/localStorage'; +import { compareAddresses } from '@/lib/helpers'; const initialState: { userData?: IUser; @@ -53,6 +54,24 @@ export const userSlice = createSlice({ }; }>, ) => { + const localAddress = localStorage + .getItem(StorageLabel.USER) + ?.toLocaleLowerCase(); + console.log( + 'localAddress', + localAddress, + action.payload.data.userByAddress.walletAddress, + ); + if ( + compareAddresses( + localAddress, + action.payload.data.userByAddress.walletAddress, + ) + ) { + state.token = + localStorage.getItem(StorageLabel.TOKEN) ?? + undefined; + } state.userData = action.payload.data?.userByAddress; }, ) @@ -61,7 +80,7 @@ export const userSlice = createSlice({ state.token = action.payload; localStorage.setItem( StorageLabel.USER, - action.meta.arg.address || '', + action.meta.arg.address?.toLocaleLowerCase() || '', ); localStorage.setItem(StorageLabel.TOKEN, action.payload); state.isSignedIn = true; From 2631d47d5553c1238c4b6dbc5e4aac92ed0bcf02 Mon Sep 17 00:00:00 2001 From: alireza-sharifpour Date: Sun, 22 May 2022 17:56:24 +0430 Subject: [PATCH 147/257] Replaced User Redux with User context in all components --- pages/_app.tsx | 17 ++++++++--------- pages/index.tsx | 7 ++----- src/apollo/types/types.ts | 1 - src/components/Header/Header.tsx | 19 ++++++++++--------- src/components/RichTextInput.tsx | 2 +- src/components/menu/MenuWallet.tsx | 18 +++++++++--------- .../modals/DeactivateProjectModal.tsx | 8 ++------ src/components/modals/EditUserModal.tsx | 13 +++++++------ src/components/modals/Stake.tsx | 7 ------- src/components/views/EditIndex.tsx | 8 ++------ src/components/views/create/CreateIndex.tsx | 12 +++++++----- src/components/views/create/CreateProject.tsx | 7 ++----- .../views/create/WalletAddressInput.tsx | 8 ++------ .../views/donate/CryptoDonation.tsx | 9 ++++----- .../views/homepage/HomeChangeMakers.tsx | 8 ++------ .../views/homepage/HomeExploreProjects.tsx | 7 ++----- src/components/views/homepage/HomeHeader.tsx | 7 ++----- .../views/homepage/HomePurpleSection.tsx | 7 ++----- src/components/views/onboarding/DoneStep.tsx | 7 ++----- src/components/views/onboarding/common.tsx | 14 ++++++-------- src/components/views/project/ProjectIndex.tsx | 7 ++----- .../views/project/ProjectUpdates.tsx | 7 ++----- .../views/projects/ProjectsIndex.tsx | 8 ++------ src/features/user/user.slice.ts | 3 ++- src/features/user/user.thunks.ts | 18 +++++++++++++++--- src/features/user/user.types.ts | 6 +++--- 26 files changed, 98 insertions(+), 137 deletions(-) diff --git a/pages/_app.tsx b/pages/_app.tsx index 182eb4b6dd..3bb0aaff11 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -11,7 +11,6 @@ import { Provider } from 'react-redux'; import { PriceProvider } from '@/context/price.context'; import { GeneralProvider } from '@/context/general.context'; import { useApollo } from '@/apollo/apolloClient'; -import { UserProvider } from '@/context/UserProvider'; import { HeaderWrapper } from '@/components/Header/HeaderWrapper'; import { FooterWrapper } from '@/components/Footer/FooterWrapper'; @@ -63,14 +62,14 @@ function MyApp({ Component, pageProps }: AppProps) { - - - - - - - - + {/* */} + + + + + + + {/* */} diff --git a/pages/index.tsx b/pages/index.tsx index cc320c9ae0..43f6d58b9a 100644 --- a/pages/index.tsx +++ b/pages/index.tsx @@ -6,8 +6,8 @@ import { client } from '@/apollo/apolloClient'; import { FETCH_HOME_PROJECTS } from '@/apollo/gql/gqlProjects'; import { EDirection, gqlEnums } from '@/apollo/types/gqlEnums'; import { IProject } from '@/apollo/types/types'; -import useUser from '@/context/UserProvider'; import { HomeMeta } from '@/lib/meta'; +import { useAppSelector } from '@/features/hooks'; const projectsToFetch = 12; @@ -35,10 +35,7 @@ const fetchProjects = async (userId: string | undefined = undefined) => { }; const HomeRoute = (props: IHomeRoute) => { - const { - state: { user }, - } = useUser(); - + const user = useAppSelector(state => state.user.userData); const [projects, setProjects] = useState(props.projects); const [totalCount, setTotalCount] = useState(props.totalCount); diff --git a/src/apollo/types/types.ts b/src/apollo/types/types.ts index 7bec9ac703..e3c32864d9 100644 --- a/src/apollo/types/types.ts +++ b/src/apollo/types/types.ts @@ -85,7 +85,6 @@ export interface IUser { walletAddress?: string; url?: string; location?: string; - token?: string; userId?: string; totalDonated?: number; totalReceived?: number; diff --git a/src/components/Header/Header.tsx b/src/components/Header/Header.tsx index ad8254368b..ab516ba345 100644 --- a/src/components/Header/Header.tsx +++ b/src/components/Header/Header.tsx @@ -34,7 +34,6 @@ import { RewardMenu } from '@/components/menu/RewardMenu'; import MenuWallet from '@/components/menu/MenuWallet'; import { ETheme, useGeneral } from '@/context/general.context'; import { menuRoutes } from '../menu/menuRoutes'; -import useUser from '@/context/UserProvider'; import { isUserRegistered, shortenAddress } from '@/lib/helpers'; import HeaderRoutesResponsive from './HeaderResponsiveRoutes'; import Routes from '@/lib/constants/Routes'; @@ -68,10 +67,12 @@ const Header: FC = () => { state => state.subgraph[currentValuesHelper(chainId)], ); const dispatch = useAppDispatch(); - const { - state: { user, isEnabled, isSignedIn }, - } = useUser(); - + const { isEnabled, isSignedIn, userData } = useAppSelector( + state => state.user, + ); + // const { + // state: { user, isEnabled, isSignedIn }, + // } = useUser(); const { theme } = useGeneral(); const router = useRouter(); @@ -129,7 +130,7 @@ const Header: FC = () => { dispatch(setShowWelcomeModal(true)); } else if (!isSignedIn) { dispatch(setShowSignWithWallet(true)); - } else if (isUserRegistered(user)) { + } else if (isUserRegistered(userData)) { router.push(Routes.CreateProject); } else { dispatch(setShowCompleteProfile(true)); @@ -264,8 +265,8 @@ const Header: FC = () => { = () => { /> - {user?.name || + {userData?.name || shortenAddress(account)} diff --git a/src/components/RichTextInput.tsx b/src/components/RichTextInput.tsx index 690b97192f..2a5337c8ed 100644 --- a/src/components/RichTextInput.tsx +++ b/src/components/RichTextInput.tsx @@ -99,7 +99,7 @@ const modules = (projectId?: any) => { 'emoji-toolbar': true, 'emoji-textarea': true, 'emoji-shortname': true, - magicUrl: true, + magicUrl: false, clipboard: { // toggle to add extra line breaks when pasting HTML: matchVisual: false, diff --git a/src/components/menu/MenuWallet.tsx b/src/components/menu/MenuWallet.tsx index dcf9dc4033..663dbd045e 100644 --- a/src/components/menu/MenuWallet.tsx +++ b/src/components/menu/MenuWallet.tsx @@ -14,7 +14,6 @@ import { import { captureException } from '@sentry/nextjs'; import Routes from '@/lib/constants/Routes'; -import useUser from '@/context/UserProvider'; import links from '@/lib/constants/links'; import { SignWithWalletModal } from '@/components/modals/SignWithWalletModal'; import { switchNetworkHandler } from '@/lib/wallet'; @@ -22,11 +21,12 @@ import { MenuContainer } from './Menu.sc'; import { ETheme, useGeneral } from '@/context/general.context'; import { isUserRegistered, networkInfo } from '@/lib/helpers'; import StorageLabel from '@/lib/localStorage'; -import { useAppDispatch } from '@/features/hooks'; +import { useAppDispatch, useAppSelector } from '@/features/hooks'; import { setShowCompleteProfile, setShowWalletModal, } from '@/features/modal/modal.sclie'; +import { signOut } from '@/features/user/user.slice'; const MenuWallet = () => { const [isMounted, setIsMounted] = useState(false); @@ -37,19 +37,16 @@ const MenuWallet = () => { const router = useRouter(); const dispatch = useAppDispatch(); - const { - state: { user, isSignedIn }, - actions: { signOut }, - } = useUser(); + const { isSignedIn, userData } = useAppSelector(state => state.user); const { theme } = useGeneral(); - + console.log('isSignedIn', isSignedIn); const goRoute = (input: { url: string; requiresSign: boolean; requiresRegistration?: boolean; }) => { const { url, requiresSign, requiresRegistration } = input; - if (requiresRegistration && !isUserRegistered(user)) { + if (requiresRegistration && !isUserRegistered(userData)) { dispatch(setShowCompleteProfile(true)); if (url === Routes.CreateProject) return; } @@ -140,7 +137,10 @@ const MenuWallet = () => { ))} {isSignedIn && ( - + dispatch(signOut())} + theme={theme} + > Sign out )} diff --git a/src/components/modals/DeactivateProjectModal.tsx b/src/components/modals/DeactivateProjectModal.tsx index 2fe7327cbb..4873765c67 100644 --- a/src/components/modals/DeactivateProjectModal.tsx +++ b/src/components/modals/DeactivateProjectModal.tsx @@ -22,12 +22,11 @@ import { import QuestionBadge from '@/components/badges/QuestionBadge'; import FormProgress from '@/components/FormProgress'; import { Shadow } from '@/components/styled-components/Shadow'; -import useUser from '@/context/UserProvider'; import { Modal } from './Modal'; import ArchiveIcon from '../../../public/images/icons/archive_deep.svg'; import Routes from '@/lib/constants/Routes'; import { IModal } from '@/types/common'; -import { useAppDispatch } from '@/features/hooks'; +import { useAppDispatch, useAppSelector } from '@/features/hooks'; import { setShowSignWithWallet } from '@/features/modal/modal.sclie'; interface ISelectObj { @@ -58,10 +57,7 @@ const DeactivateProjectModal = ({ undefined, ); const dispatch = useAppDispatch(); - const { - state: { isSignedIn }, - } = useUser(); - + const isSignedIn = useAppSelector(state => state.user.isSignedIn); const fetchReasons = async () => { const { data } = await client.query({ query: GET_STATUS_REASONS, diff --git a/src/components/modals/EditUserModal.tsx b/src/components/modals/EditUserModal.tsx index f26bfb1e59..7f508a1fd6 100644 --- a/src/components/modals/EditUserModal.tsx +++ b/src/components/modals/EditUserModal.tsx @@ -4,6 +4,7 @@ import Image from 'next/image'; import { useMutation } from '@apollo/client'; import { Button, brandColors } from '@giveth/ui-design-system'; import { captureException } from '@sentry/nextjs'; +import { useWeb3React } from '@web3-react/core'; import { Modal } from './Modal'; import { client } from '@/apollo/apolloClient'; import { UPDATE_USER } from '@/apollo/gql/gqlUser'; @@ -11,7 +12,6 @@ import { IUser } from '@/apollo/types/types'; import { FlexCenter, Flex } from '@/components/styled-components/Flex'; import ImageUploader from '../ImageUploader'; import { gToast, ToastType } from '../toasts'; -import useUser from '@/context/UserProvider'; import Input, { IFormValidations, InputSize, @@ -20,6 +20,8 @@ import Input, { import { IUserInfo } from '../views/onboarding/InfoStep'; import { mediaQueries } from '@/lib/constants/constants'; import { IModal } from '@/types/common'; +import { useAppDispatch } from '@/features/hooks'; +import { fetchUserByAddress } from '@/features/user/user.thunks'; enum EditStatusType { INFO, @@ -51,9 +53,8 @@ const EditUserModal = ({ setShowModal, user }: IEditUserModal) => { }, ); - const { - actions: { reFetchUser }, - } = useUser(); + const dispatch = useAppDispatch(); + const { account } = useWeb3React(); const [updateUser] = useMutation(UPDATE_USER); useEffect(() => { @@ -76,7 +77,7 @@ const EditUserModal = ({ setShowModal, user }: IEditUserModal) => { }, }); if (response.updateUser) { - reFetchUser(); + account && dispatch(fetchUserByAddress(account)); setEditStatus(EditStatusType.INFO); gToast('Profile Photo updated.', { type: ToastType.SUCCESS, @@ -109,7 +110,7 @@ const EditUserModal = ({ setShowModal, user }: IEditUserModal) => { }, }); if (data.updateUser) { - reFetchUser(); + account && dispatch(fetchUserByAddress(account)); gToast('Profile information updated.', { type: ToastType.SUCCESS, title: 'Success', diff --git a/src/components/modals/Stake.tsx b/src/components/modals/Stake.tsx index 0049051c95..52a9f45787 100644 --- a/src/components/modals/Stake.tsx +++ b/src/components/modals/Stake.tsx @@ -33,7 +33,6 @@ import { import { StakeState } from '@/lib/staking'; import ToggleSwitch from '../styled-components/Switch'; import { abi as ERC20_ABI } from '@/artifacts/ERC20.json'; -import useUser from '@/context/UserProvider'; import { IModal } from '@/types/common'; interface IStakeModalProps extends IModal { @@ -65,9 +64,6 @@ export const StakeModal: FC = ({ const { title, LM_ADDRESS, POOL_ADDRESS, GARDEN_ADDRESS } = poolStakingConfig; const [permit, setPermit] = useState(false); - const { - actions: { getBalance }, - } = useUser(); useEffect(() => { if (GARDEN_ADDRESS) { @@ -114,9 +110,6 @@ export const StakeModal: FC = ({ }); return () => { library.removeAllListeners('block'); - library?.on('block', () => { - getBalance(); - }); }; }, [library, amount, stakeState]); diff --git a/src/components/views/EditIndex.tsx b/src/components/views/EditIndex.tsx index cfbe87a095..0428cac33b 100644 --- a/src/components/views/EditIndex.tsx +++ b/src/components/views/EditIndex.tsx @@ -2,7 +2,6 @@ import React, { useEffect, useState } from 'react'; import { useRouter } from 'next/router'; import { captureException } from '@sentry/nextjs'; -import useUser from '@/context/UserProvider'; import { client } from '@/apollo/apolloClient'; import { FETCH_PROJECT_BY_ID } from '@/apollo/gql/gqlProjects'; import { IProjectEdition } from '@/apollo/types/types'; @@ -12,7 +11,7 @@ import { showToastError, } from '@/lib/helpers'; import CreateProject from '@/components/views/create/CreateProject'; -import { useAppDispatch } from '@/features/hooks'; +import { useAppDispatch, useAppSelector } from '@/features/hooks'; import { setShowCompleteProfile, setShowSignWithWallet, @@ -23,10 +22,7 @@ const EditIndex = () => { const [project, setProject] = useState(); const dispatch = useAppDispatch(); - const { - state: { user, isSignedIn }, - } = useUser(); - + const { isSignedIn, userData: user } = useAppSelector(state => state.user); const router = useRouter(); const projectId = router?.query.projectIdSlug as string; diff --git a/src/components/views/create/CreateIndex.tsx b/src/components/views/create/CreateIndex.tsx index d61f7366e1..f3af6701e9 100644 --- a/src/components/views/create/CreateIndex.tsx +++ b/src/components/views/create/CreateIndex.tsx @@ -1,8 +1,7 @@ import React, { useEffect } from 'react'; import CreateProject from '@/components/views/create/CreateProject'; -import useUser from '@/context/UserProvider'; import { isUserRegistered } from '@/lib/helpers'; -import { useAppDispatch } from '@/features/hooks'; +import { useAppDispatch, useAppSelector } from '@/features/hooks'; import { setShowCompleteProfile, setShowSignWithWallet, @@ -12,14 +11,17 @@ import { const CreateIndex = () => { const dispatch = useAppDispatch(); const { - state: { user, isSignedIn, isEnabled }, - } = useUser(); - + isEnabled, + isSignedIn, + userData: user, + } = useAppSelector(state => state.user); + console.log('Hiii', user); const isRegistered = isUserRegistered(user); useEffect(() => { if (isEnabled) { if (!isRegistered) { + console.log('Hiii'); dispatch(setShowCompleteProfile(true)); return; } diff --git a/src/components/views/create/CreateProject.tsx b/src/components/views/create/CreateProject.tsx index 0daa132e6e..8528ede0ce 100644 --- a/src/components/views/create/CreateProject.tsx +++ b/src/components/views/create/CreateProject.tsx @@ -34,7 +34,6 @@ import { NameInput, WalletAddressInput, } from './Inputs'; -import useUser from '@/context/UserProvider'; import SuccessfulCreation from './SuccessfulCreation'; import { ProjectGuidelineModal } from '@/components/modals/ProjectGuidelineModal'; import { @@ -49,6 +48,7 @@ import { client } from '@/apollo/apolloClient'; import LightBulbIcon from '/public/images/icons/lightbulb.svg'; import { Shadow } from '@/components/styled-components/Shadow'; import { deviceSize, mediaQueries } from '@/lib/constants/constants'; +import { useAppSelector } from '@/features/hooks'; export enum ECreateErrFields { NAME = 'name', @@ -92,16 +92,13 @@ const CreateProject = (props: { project?: IProjectEdition }) => { const [impactLocation, setImpactLocation] = useState( project?.impactLocation || '', ); + const user = useAppSelector(state => state.user?.userData); const [errors, setErrors] = useState({ [ECreateErrFields.NAME]: isEditMode ? '' : 'Title is required', [ECreateErrFields.DESCRIPTION]: '', [ECreateErrFields.WALLET_ADDRESS]: '', }); - const { - state: { user }, - } = useUser(); - const debouncedTitleValidation = useRef(); const debouncedAddressValidation = useRef(); const debouncedDescriptionValidation = useRef(); diff --git a/src/components/views/create/WalletAddressInput.tsx b/src/components/views/create/WalletAddressInput.tsx index 934af7c725..05b58a4e04 100644 --- a/src/components/views/create/WalletAddressInput.tsx +++ b/src/components/views/create/WalletAddressInput.tsx @@ -8,9 +8,9 @@ import { InputWithError, TinyLabel, } from './Create.sc'; -import useUser from '@/context/UserProvider'; import { compareAddresses } from '@/lib/helpers'; import { ECreateErrFields } from '@/components/views/create/CreateProject'; +import { useAppSelector } from '@/features/hooks'; const WalletAddressInput = (props: { value: string; @@ -18,11 +18,7 @@ const WalletAddressInput = (props: { error: string; }) => { const { value, setValue, error } = props; - - const { - state: { user }, - } = useUser(); - + const user = useAppSelector(state => state.user?.userData); const isDefaultAddress = compareAddresses(value, user?.walletAddress); return ( diff --git a/src/components/views/donate/CryptoDonation.tsx b/src/components/views/donate/CryptoDonation.tsx index 76e6cbd683..e0a569cac1 100644 --- a/src/components/views/donate/CryptoDonation.tsx +++ b/src/components/views/donate/CryptoDonation.tsx @@ -18,7 +18,6 @@ import tokenAbi from 'human-standard-token-abi'; import { captureException } from '@sentry/nextjs'; import { Shadow } from '@/components/styled-components/Shadow'; import InputBox from '../../InputBox'; -import useUser from '@/context/UserProvider'; import CheckBox from '@/components/Checkbox'; import DonateModal from '@/components/modals/DonateModal'; import { mediaQueries } from '@/lib/constants/constants'; @@ -55,7 +54,7 @@ import { getERC20Info } from '@/lib/contracts'; import GIVBackToast from '@/components/views/donate/GIVBackToast'; import { DonateWrongNetwork } from '@/components/modals/DonateWrongNetwork'; import FailedDonation from '@/components/modals/FailedDonation'; -import { useAppDispatch } from '@/features/hooks'; +import { useAppDispatch, useAppSelector } from '@/features/hooks'; import { setShowSignWithWallet, setShowWalletModal, @@ -82,9 +81,9 @@ const CryptoDonation = (props: { }) => { const { chainId: networkId, account, library } = useWeb3React(); const dispatch = useAppDispatch(); - const { - state: { isSignedIn, isEnabled, balance }, - } = useUser(); + const { isEnabled, isSignedIn, balance } = useAppSelector( + state => state.user, + ); const { ethPrice } = usePrice(); const { project, setSuccessDonation } = props; diff --git a/src/components/views/homepage/HomeChangeMakers.tsx b/src/components/views/homepage/HomeChangeMakers.tsx index a5f241c18f..904a2bc2ae 100644 --- a/src/components/views/homepage/HomeChangeMakers.tsx +++ b/src/components/views/homepage/HomeChangeMakers.tsx @@ -5,11 +5,10 @@ import styled from 'styled-components'; import Routes from '@/lib/constants/Routes'; import { Arc } from '@/components/styled-components/Arc'; import { isUserRegistered } from '@/lib/helpers'; -import useUser from '@/context/UserProvider'; import { HomeContainer } from '@/components/views/homepage/Home.sc'; import { mediaQueries } from '@/lib/constants/constants'; import { Col } from '@/components/Grid'; -import { useAppDispatch } from '@/features/hooks'; +import { useAppDispatch, useAppSelector } from '@/features/hooks'; import { setShowCompleteProfile } from '@/features/modal/modal.sclie'; const content = [ @@ -38,10 +37,7 @@ const content = [ const HomeChangeMakers = () => { const router = useRouter(); const dispatch = useAppDispatch(); - - const { - state: { user }, - } = useUser(); + const user = useAppSelector(state => state.user.userData); const handleCreateButton = () => { if (isUserRegistered(user)) { diff --git a/src/components/views/homepage/HomeExploreProjects.tsx b/src/components/views/homepage/HomeExploreProjects.tsx index 4daf90ef68..758c421dd2 100644 --- a/src/components/views/homepage/HomeExploreProjects.tsx +++ b/src/components/views/homepage/HomeExploreProjects.tsx @@ -13,9 +13,8 @@ import { IProject } from '@/apollo/types/types'; import Routes from '@/lib/constants/Routes'; import { isUserRegistered } from '@/lib/helpers'; import { FlexCenter } from '@/components/styled-components/Flex'; -import useUser from '@/context/UserProvider'; import { deviceSize, mediaQueries } from '@/lib/constants/constants'; -import { useAppDispatch } from '@/features/hooks'; +import { useAppDispatch, useAppSelector } from '@/features/hooks'; import { setShowCompleteProfile } from '@/features/modal/modal.sclie'; interface IHomeExploreProjects { @@ -29,9 +28,7 @@ const HomeExploreProjects = (props: IHomeExploreProjects) => { const router = useRouter(); const dispatch = useAppDispatch(); - const { - state: { user }, - } = useUser(); + const user = useAppSelector(state => state.user.userData); const handleCreateButton = () => { if (isUserRegistered(user)) { diff --git a/src/components/views/homepage/HomeHeader.tsx b/src/components/views/homepage/HomeHeader.tsx index 291f3fc00c..62f54f5021 100644 --- a/src/components/views/homepage/HomeHeader.tsx +++ b/src/components/views/homepage/HomeHeader.tsx @@ -5,18 +5,15 @@ import styled from 'styled-components'; import { FlexCenter } from '@/components/styled-components/Flex'; import Routes from '@/lib/constants/Routes'; import { Arc } from '@/components/styled-components/Arc'; -import useUser from '@/context/UserProvider'; import { isUserRegistered } from '@/lib/helpers'; import { mediaQueries } from '@/lib/constants/constants'; -import { useAppDispatch } from '@/features/hooks'; +import { useAppDispatch, useAppSelector } from '@/features/hooks'; import { setShowCompleteProfile } from '@/features/modal/modal.sclie'; const HomeHeader = () => { const router = useRouter(); const dispatch = useAppDispatch(); - const { - state: { user }, - } = useUser(); + const user = useAppSelector(state => state.user.userData); const handleCreateButton = () => { if (isUserRegistered(user)) { diff --git a/src/components/views/homepage/HomePurpleSection.tsx b/src/components/views/homepage/HomePurpleSection.tsx index 48d04219d3..44969518a5 100644 --- a/src/components/views/homepage/HomePurpleSection.tsx +++ b/src/components/views/homepage/HomePurpleSection.tsx @@ -13,22 +13,19 @@ import { } from '@giveth/ui-design-system'; import TwitterIcon from '/public/images/twitter.svg'; -import useUser from '@/context/UserProvider'; import { isSSRMode, isUserRegistered } from '@/lib/helpers'; import Routes from '@/lib/constants/Routes'; import { Col, Row } from '@/components/Grid'; import { Arc } from '@/components/styled-components/Arc'; import { HomeContainer } from '@/components/views/homepage/Home.sc'; import { deviceSize, mediaQueries } from '@/lib/constants/constants'; -import { useAppDispatch } from '@/features/hooks'; +import { useAppDispatch, useAppSelector } from '@/features/hooks'; import { setShowCompleteProfile } from '@/features/modal/modal.sclie'; const HomePurpleSection = () => { const router = useRouter(); const dispatch = useAppDispatch(); - const { - state: { user }, - } = useUser(); + const user = useAppSelector(state => state.user.userData); const handleCreateButton = () => { if (isUserRegistered(user)) { diff --git a/src/components/views/onboarding/DoneStep.tsx b/src/components/views/onboarding/DoneStep.tsx index e4a8449800..148df2ae43 100644 --- a/src/components/views/onboarding/DoneStep.tsx +++ b/src/components/views/onboarding/DoneStep.tsx @@ -15,10 +15,9 @@ import { OnboardStep } from './common'; import { Flex } from '@/components/styled-components/Flex'; import CongratsAnimation from '@/animations/congrats.json'; import Routes from '@/lib/constants/Routes'; -import useUser from '@/context/UserProvider'; import { isUserRegistered } from '@/lib/helpers'; import { Col, Row } from '@/components/Grid'; -import { useAppDispatch } from '@/features/hooks'; +import { useAppDispatch, useAppSelector } from '@/features/hooks'; import { setShowCompleteProfile } from '@/features/modal/modal.sclie'; const CongratsAnimationOptions = { @@ -32,9 +31,7 @@ const CongratsAnimationOptions = { const DoneStep = () => { const router = useRouter(); const dispatch = useAppDispatch(); - const { - state: { user }, - } = useUser(); + const user = useAppSelector(state => state.user.userData); const handleCreateButton = () => { if (isUserRegistered(user)) { diff --git a/src/components/views/onboarding/common.tsx b/src/components/views/onboarding/common.tsx index cb2a01a0be..fc682afd2f 100644 --- a/src/components/views/onboarding/common.tsx +++ b/src/components/views/onboarding/common.tsx @@ -2,11 +2,12 @@ import { Button, neutralColors } from '@giveth/ui-design-system'; import { Dispatch, FC, SetStateAction, useEffect } from 'react'; import styled from 'styled-components'; +import { useWeb3React } from '@web3-react/core'; import { Col, Row } from '@/components/Grid'; -import useUser from '@/context/UserProvider'; import { OnboardSteps } from './Onboarding.view'; -import { useAppDispatch } from '@/features/hooks'; +import { useAppDispatch, useAppSelector } from '@/features/hooks'; import { setShowSignWithWallet } from '@/features/modal/modal.sclie'; +import { fetchUserByAddress } from '@/features/user/user.thunks'; export const OnboardStep = styled(Col)` margin: 0 auto; @@ -29,11 +30,8 @@ export const OnboardActions: FC = ({ disabled, }) => { const dispatch = useAppDispatch(); - const { - state: { isSignedIn }, - actions: { reFetchUser }, - } = useUser(); - + const isSignedIn = useAppSelector(state => state.user.isSignedIn); + const { account } = useWeb3React(); useEffect(() => { if (!isSignedIn) { dispatch(setShowSignWithWallet(true)); @@ -46,7 +44,7 @@ export const OnboardActions: FC = ({ } else { const res = await onSave(); if (res) { - reFetchUser(); + account && dispatch(fetchUserByAddress(account)); } } }; diff --git a/src/components/views/project/ProjectIndex.tsx b/src/components/views/project/ProjectIndex.tsx index 22defc2c68..465553ab39 100644 --- a/src/components/views/project/ProjectIndex.tsx +++ b/src/components/views/project/ProjectIndex.tsx @@ -12,7 +12,6 @@ import ProjectDonateCard from './ProjectDonateCard'; import { FETCH_PROJECT_DONATIONS } from '@/apollo/gql/gqlDonations'; import { client } from '@/apollo/apolloClient'; import { FETCH_PROJECT_BY_SLUG } from '@/apollo/gql/gqlProjects'; -import useUser from '@/context/UserProvider'; import { IDonation, IProject } from '@/apollo/types/types'; import { EDirection, EProjectStatus, gqlEnums } from '@/apollo/types/gqlEnums'; import InfoBadge from '@/components/badges/InfoBadge'; @@ -23,6 +22,7 @@ import InlineToast from '@/components/toasts/InlineToast'; import { ProjectMeta } from '@/lib/meta'; import SimilarProjects from '@/components/views/project/SimilarProjects'; import { showToastError } from '@/lib/helpers'; +import { useAppSelector } from '@/features/hooks'; const ProjectDonations = dynamic(() => import('./ProjectDonations')); const ProjectUpdates = dynamic(() => import('./ProjectUpdates')); @@ -45,10 +45,7 @@ const ProjectIndex = (props: { project?: IProject }) => { const [creationSuccessful, setCreationSuccessful] = useState(false); const [isMobile, setIsMobile] = useState(false); const [isCancelled, setIsCancelled] = useState(false); - - const { - state: { user }, - } = useUser(); + const user = useAppSelector(state => state.user.userData); const { description = '', title, status, id = '' } = project || {}; const router = useRouter(); diff --git a/src/components/views/project/ProjectUpdates.tsx b/src/components/views/project/ProjectUpdates.tsx index e547ca9d6c..a7c65bd0ce 100644 --- a/src/components/views/project/ProjectUpdates.tsx +++ b/src/components/views/project/ProjectUpdates.tsx @@ -22,8 +22,7 @@ import ProjectTimeline, { TimelineSection } from './ProjectTimeline'; import { IProject, IProjectUpdate } from '@/apollo/types/types'; import { RemoveUpdateModal } from '@/components/modals/RemoveUpdateModal'; import { mediaQueries } from '@/lib/constants/constants'; -import useUser from '@/context/UserProvider'; -import { useAppDispatch } from '@/features/hooks'; +import { useAppDispatch, useAppSelector } from '@/features/hooks'; import { setShowSignWithWallet } from '@/features/modal/modal.sclie'; const RichTextInput = dynamic(() => import('@/components/RichTextInput'), { @@ -40,9 +39,7 @@ const ProjectUpdates = (props: { const { id, creationDate, adminUser } = project || {}; const dispatch = useAppDispatch(); - const { - state: { user, isSignedIn }, - } = useUser(); + const { isSignedIn, userData: user } = useAppSelector(state => state.user); const [newUpdate, setNewUpdate] = useState(''); const [title, setTitle] = useState(''); diff --git a/src/components/views/projects/ProjectsIndex.tsx b/src/components/views/projects/ProjectsIndex.tsx index e270ee8241..7ce3ba14e0 100644 --- a/src/components/views/projects/ProjectsIndex.tsx +++ b/src/components/views/projects/ProjectsIndex.tsx @@ -30,9 +30,8 @@ import { IFetchAllProjects } from '@/apollo/types/gqlTypes'; import { EDirection, gqlEnums } from '@/apollo/types/gqlEnums'; import ProjectsNoResults from '@/components/views/projects/ProjectsNoResults'; import { Shadow } from '../../styled-components/Shadow'; -import useUser from '@/context/UserProvider'; import { deviceSize, mediaQueries } from '@/lib/constants/constants'; -import { useAppDispatch } from '@/features/hooks'; +import { useAppDispatch, useAppSelector } from '@/features/hooks'; import { setShowCompleteProfile } from '@/features/modal/modal.sclie'; interface IProjectsView { @@ -86,10 +85,7 @@ const buildCategoryObj = (array: ICategory[]) => { const ProjectsIndex = (props: IProjectsView) => { const { projects, totalCount: _totalCount, categories } = props; - - const { - state: { user }, - } = useUser(); + const user = useAppSelector(state => state.user.userData); const [categoriesObj, setCategoriesObj] = useState(); const [selectedCategory, setSelectedCategory] = diff --git a/src/features/user/user.slice.ts b/src/features/user/user.slice.ts index effe9ff0c7..17eb7e8783 100644 --- a/src/features/user/user.slice.ts +++ b/src/features/user/user.slice.ts @@ -39,7 +39,6 @@ export const userSlice = createSlice({ localStorage.removeItem(StorageLabel.TOKEN); state.token = undefined; state.isSignedIn = false; - state.userData = undefined; }, }, extraReducers: builder => { @@ -71,6 +70,8 @@ export const userSlice = createSlice({ state.token = localStorage.getItem(StorageLabel.TOKEN) ?? undefined; + } else { + state.token = undefined; } state.userData = action.payload.data?.userByAddress; }, diff --git a/src/features/user/user.thunks.ts b/src/features/user/user.thunks.ts index 4c91e01ba9..720cce3a4c 100644 --- a/src/features/user/user.thunks.ts +++ b/src/features/user/user.thunks.ts @@ -15,7 +15,10 @@ export const fetchUserByAddress = createAsyncThunk( export const signToGetToken = createAsyncThunk( 'user/signToGetToken', - async ({ address, chainId, signer }: ISignToGetToken, { getState }) => { + async ( + { address, chainId, signer }: ISignToGetToken, + { getState, dispatch }, + ) => { const signedMessage = await signMessage( process.env.NEXT_PUBLIC_OUR_SECRET as string, address, @@ -23,8 +26,17 @@ export const signToGetToken = createAsyncThunk( signer, ); if (signedMessage) { - const { user } = getState() as { user: RootState['user'] }; - return getToken(address, signedMessage, chainId, user); + const state = getState() as RootState; + console.log('getToken State', state.user.userData); + if (!state.user.userData) { + await dispatch(fetchUserByAddress(address)); + } + return getToken( + address, + signedMessage, + chainId, + state.user.userData, + ); } else { return Promise.reject('Signing failed'); } diff --git a/src/features/user/user.types.ts b/src/features/user/user.types.ts index f5e5f52160..142c2fe084 100644 --- a/src/features/user/user.types.ts +++ b/src/features/user/user.types.ts @@ -1,5 +1,5 @@ export interface ISignToGetToken { - address: string | undefined | null; - chainId?: number; - signer?: any; + address: string; + chainId: number; + signer: any; } From e7894d4719f0f9c1ee230f50e75ddf5f2328d28b Mon Sep 17 00:00:00 2001 From: alireza-sharifpour Date: Sun, 22 May 2022 17:56:57 +0430 Subject: [PATCH 148/257] Set MagicURL to true --- src/components/RichTextInput.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/RichTextInput.tsx b/src/components/RichTextInput.tsx index 2a5337c8ed..690b97192f 100644 --- a/src/components/RichTextInput.tsx +++ b/src/components/RichTextInput.tsx @@ -99,7 +99,7 @@ const modules = (projectId?: any) => { 'emoji-toolbar': true, 'emoji-textarea': true, 'emoji-shortname': true, - magicUrl: false, + magicUrl: true, clipboard: { // toggle to add extra line breaks when pasting HTML: matchVisual: false, From 795e360ce3705c83e4c0437e4aa4371243a0ec38 Mon Sep 17 00:00:00 2001 From: alireza-sharifpour Date: Sun, 22 May 2022 18:05:30 +0430 Subject: [PATCH 149/257] Removed chainId check from ISignToGetToken --- src/features/user/user.types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/features/user/user.types.ts b/src/features/user/user.types.ts index 142c2fe084..41bdc1a881 100644 --- a/src/features/user/user.types.ts +++ b/src/features/user/user.types.ts @@ -1,5 +1,5 @@ export interface ISignToGetToken { address: string; - chainId: number; + chainId?: number; signer: any; } From 10794a27301d5e33e3311aaff35be5cd2275b6a5 Mon Sep 17 00:00:00 2001 From: Ramin Date: Sun, 22 May 2022 18:20:41 +0430 Subject: [PATCH 150/257] #774 fix set a valid amount error in donation page --- .../{ => views/create}/InputBox.tsx | 44 +++++++++---------- .../views/donate/CryptoDonation.tsx | 11 +++-- 2 files changed, 29 insertions(+), 26 deletions(-) rename src/components/{ => views/create}/InputBox.tsx (74%) diff --git a/src/components/InputBox.tsx b/src/components/views/create/InputBox.tsx similarity index 74% rename from src/components/InputBox.tsx rename to src/components/views/create/InputBox.tsx index c24a83d147..8637e5c2ac 100644 --- a/src/components/InputBox.tsx +++ b/src/components/views/create/InputBox.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { FC } from 'react'; import { neutralColors, semanticColors, @@ -7,28 +7,30 @@ import { } from '@giveth/ui-design-system'; import styled from 'styled-components'; -type OnChangeFunction = (e: number) => void; - -const InputBox = (props: { +interface IInputBox { value?: number; - onChange: OnChangeFunction; + onChange: (e: number) => void; placeholder?: string; type?: string; - errorHandler?: any; + errorHandler: { + condition: (i: number) => boolean; + message: string; + }; setError?: any; error?: any; onFocus?: any; +} + +const InputBox: FC = ({ + value, + onChange, + error, + setError, + errorHandler, + type, + placeholder, + onFocus, }) => { - const { - value, - onChange, - error, - setError, - errorHandler, - type, - placeholder, - onFocus, - } = props; return ( @@ -37,15 +39,13 @@ const InputBox = (props: { value={value} type={type} onChange={e => { - onChange(Number(e.target.value)); - setError( - errorHandler && - errorHandler?.condition(e.target.value), - ); + const num = Number(e.target.value); + onChange(num); + setError(errorHandler.condition(num)); }} onFocus={() => onFocus(true)} onBlur={() => onFocus(false)} - placeholder={placeholder || 'Search Projects...'} + placeholder={placeholder} /> {error && {errorHandler?.message}} diff --git a/src/components/views/donate/CryptoDonation.tsx b/src/components/views/donate/CryptoDonation.tsx index 395c6797c5..599caa6b4b 100644 --- a/src/components/views/donate/CryptoDonation.tsx +++ b/src/components/views/donate/CryptoDonation.tsx @@ -17,7 +17,7 @@ import tokenAbi from 'human-standard-token-abi'; import { captureException } from '@sentry/nextjs'; import { Shadow } from '@/components/styled-components/Shadow'; -import InputBox from '../../InputBox'; +import InputBox from '../create/InputBox'; import useUser from '@/context/UserProvider'; import CheckBox from '@/components/Checkbox'; import DonateModal from '@/components/modals/DonateModal'; @@ -316,7 +316,11 @@ const CryptoDonation = (props: { }; const donationDisabled = - !isActive || !amountTyped || amountTyped <= 0 || !selectedToken; + !isActive || + !amountTyped || + amountTyped <= 0 || + !selectedToken || + error; return ( @@ -417,8 +421,7 @@ const CryptoDonation = (props: { error={error} setError={setError} errorHandler={{ - condition: (value: any) => - value >= 0 && value <= 0.000001, + condition: value => value >= 0 && value <= 0.000001, message: 'Set a valid amount', }} type='number' From d19f25cd5cc37a5d3eb2c823d991a34732f032e1 Mon Sep 17 00:00:00 2001 From: alireza-sharifpour Date: Sun, 22 May 2022 18:52:48 +0430 Subject: [PATCH 151/257] Added incrementLikedProjectsCount and decrementLikedProjectsCount to redux --- src/components/Header/Header.tsx | 4 +- .../ProjectCardLikeAndShareButtons.tsx | 17 +- .../views/project/ProjectDonateCard.tsx | 16 +- .../views/projects/ProjectsIndex.tsx | 1 - src/context/UserProvider.tsx | 227 ------------------ src/features/user/user.slice.ts | 23 +- 6 files changed, 38 insertions(+), 250 deletions(-) delete mode 100644 src/context/UserProvider.tsx diff --git a/src/components/Header/Header.tsx b/src/components/Header/Header.tsx index ab516ba345..2f9dbd237e 100644 --- a/src/components/Header/Header.tsx +++ b/src/components/Header/Header.tsx @@ -70,9 +70,7 @@ const Header: FC = () => { const { isEnabled, isSignedIn, userData } = useAppSelector( state => state.user, ); - // const { - // state: { user, isEnabled, isSignedIn }, - // } = useUser(); + const { theme } = useGeneral(); const router = useRouter(); diff --git a/src/components/project-card/ProjectCardLikeAndShareButtons.tsx b/src/components/project-card/ProjectCardLikeAndShareButtons.tsx index 2195e08029..e1f50bd517 100644 --- a/src/components/project-card/ProjectCardLikeAndShareButtons.tsx +++ b/src/components/project-card/ProjectCardLikeAndShareButtons.tsx @@ -15,9 +15,12 @@ import { likeProject, unlikeProject } from '@/lib/reaction'; import { showToastError } from '@/lib/helpers'; import { Flex } from '../styled-components/Flex'; import { IProject } from '@/apollo/types/types'; -import useUser from '@/context/UserProvider'; -import { useAppDispatch } from '@/features/hooks'; +import { useAppDispatch, useAppSelector } from '@/features/hooks'; import { setShowSignWithWallet } from '@/features/modal/modal.sclie'; +import { + decrementLikedProjectsCount, + incrementLikedProjectsCount, +} from '@/features/user/user.slice'; interface IProjectCardLikeAndShareButtons { project: IProject; @@ -26,11 +29,6 @@ interface IProjectCardLikeAndShareButtons { const ProjectCardLikeAndShareButtons = ( props: IProjectCardLikeAndShareButtons, ) => { - const { - state: { user, isSignedIn }, - actions: { incrementLikedProjectsCount, decrementLikedProjectsCount }, - } = useUser(); - const [showModal, setShowModal] = useState(false); const { project } = props; const { slug, id: projectId } = project; @@ -39,6 +37,7 @@ const ProjectCardLikeAndShareButtons = ( project.totalReactions, ); const [loading, setLoading] = useState(false); + const { isSignedIn, userData: user } = useAppSelector(state => state.user); const dispatch = useAppDispatch(); const likeUnlikeProject = async (e: MouseEvent) => { @@ -59,14 +58,14 @@ const ProjectCardLikeAndShareButtons = ( setReaction(newReaction); if (newReaction) { setTotalReactions((totalReactions || 0) + 1); - incrementLikedProjectsCount(); + dispatch(incrementLikedProjectsCount()); } } else if (reaction?.userId === user?.id) { const successful = await unlikeProject(reaction.id); if (successful) { setReaction(undefined); setTotalReactions((totalReactions || 1) - 1); - decrementLikedProjectsCount(); + dispatch(decrementLikedProjectsCount()); } } } catch (e) { diff --git a/src/components/views/project/ProjectDonateCard.tsx b/src/components/views/project/ProjectDonateCard.tsx index 8011ce1464..0ed66345ea 100644 --- a/src/components/views/project/ProjectDonateCard.tsx +++ b/src/components/views/project/ProjectDonateCard.tsx @@ -26,7 +26,6 @@ import CategoryBadge from '@/components/badges/CategoryBadge'; import { compareAddresses, showToastError } from '@/lib/helpers'; import { IProject } from '@/apollo/types/types'; import links from '@/lib/constants/links'; -import useUser from '@/context/UserProvider'; import ShareModal from '@/components/modals/ShareModal'; import { IReaction } from '@/apollo/types/types'; import { client } from '@/apollo/apolloClient'; @@ -42,8 +41,12 @@ import ProjectCardOrgBadge from '../../project-card/ProjectCardOrgBadge'; import ExternalLink from '@/components/ExternalLink'; import InternalLink from '@/components/InternalLink'; import Routes from '@/lib/constants/Routes'; -import { useAppDispatch } from '@/features/hooks'; +import { useAppDispatch, useAppSelector } from '@/features/hooks'; import { setShowSignWithWallet } from '@/features/modal/modal.sclie'; +import { + incrementLikedProjectsCount, + decrementLikedProjectsCount, +} from '@/features/user/user.slice'; interface IProjectDonateCard { project?: IProject; @@ -65,10 +68,7 @@ const ProjectDonateCard = ({ setCreationSuccessful, }: IProjectDonateCard) => { const dispatch = useAppDispatch(); - const { - state: { user, isSignedIn }, - actions: { incrementLikedProjectsCount, decrementLikedProjectsCount }, - } = useUser(); + const { isSignedIn, userData: user } = useAppSelector(state => state.user); const { categories = [], @@ -111,13 +111,13 @@ const ProjectDonateCard = ({ const newReaction = await likeProject(id); if (newReaction) { setReaction(newReaction); - incrementLikedProjectsCount(); + dispatch(incrementLikedProjectsCount()); } } else if (reaction?.userId === user?.id) { const successful = await unlikeProject(reaction.id); if (successful) { setReaction(undefined); - decrementLikedProjectsCount(); + dispatch(decrementLikedProjectsCount()); } } } catch (e) { diff --git a/src/components/views/projects/ProjectsIndex.tsx b/src/components/views/projects/ProjectsIndex.tsx index 7ce3ba14e0..e89b793a58 100644 --- a/src/components/views/projects/ProjectsIndex.tsx +++ b/src/components/views/projects/ProjectsIndex.tsx @@ -203,7 +203,6 @@ const ProjectsIndex = (props: IProjectsView) => { Projects - Support for-good projects, nonprofits & charities with crypto donations. Give directly with zero added fees. Get diff --git a/src/context/UserProvider.tsx b/src/context/UserProvider.tsx deleted file mode 100644 index 69a7803a4c..0000000000 --- a/src/context/UserProvider.tsx +++ /dev/null @@ -1,227 +0,0 @@ -import React, { - createContext, - ReactNode, - useContext, - useEffect, - useState, -} from 'react'; -import { useWeb3React } from '@web3-react/core'; -import { BigNumberish } from '@ethersproject/bignumber'; -import { formatEther } from '@ethersproject/units'; - -import { captureException } from '@sentry/nextjs'; -import { initializeApollo } from '@/apollo/apolloClient'; -import { GET_USER_BY_ADDRESS } from '@/apollo/gql/gqlUser'; -import { compareAddresses, showToastError, signMessage } from '@/lib/helpers'; -import { getToken } from '@/services/token'; -import { IUser } from '@/apollo/types/types'; -import StorageLabel from '@/lib/localStorage'; -import { walletsArray } from '@/lib/wallet/walletTypes'; - -interface IUserContext { - state: { - user?: IUser; - balance?: string | null; - isEnabled?: boolean; - isSignedIn?: boolean; - }; - actions: { - signToGetToken: () => Promise; - signOut?: () => void; - reFetchUser: () => void; - incrementLikedProjectsCount: () => void; - decrementLikedProjectsCount: () => void; - getBalance: () => void; - }; -} - -const UserContext = createContext({ - state: { - user: undefined, - isEnabled: false, - isSignedIn: false, - }, - actions: { - signToGetToken: async () => false, - signOut: () => {}, - reFetchUser: () => {}, - incrementLikedProjectsCount: () => {}, - decrementLikedProjectsCount: () => {}, - getBalance: () => {}, - }, -}); - -UserContext.displayName = 'UserContext'; - -const apolloClient = initializeApollo(); - -export const UserProvider = (props: { children: ReactNode }) => { - const { account, library, chainId, activate } = useWeb3React(); - - const [user, setUser] = useState(); - const [balance, setBalance] = useState(null); - - const isEnabled = !!library?.getSigner() && !!account && !!chainId; - const isSignedIn = isEnabled && !!user?.token; - - useEffect(() => { - const selectedWalletName = localStorage.getItem(StorageLabel.WALLET); - const wallet = walletsArray.find(w => w.value === selectedWalletName); - if (wallet) { - activate(wallet.connector, err => { - console.log('err', err); - }); - } - }, [activate]); - - useEffect(() => { - if (account) reFetchUser(); - else setUser(undefined); - }, [account]); - - useEffect(() => { - library?.on('block', () => { - getBalance(); - }); - return () => { - library?.removeAllListeners('block'); - }; - }, [library]); - - useEffect(() => { - if (account && library) { - getBalance(); - } - }, [account, library, chainId]); - - const fetchUser = () => { - return apolloClient - .query({ - query: GET_USER_BY_ADDRESS, - variables: { - address: account?.toLowerCase(), - }, - fetchPolicy: 'network-only', - }) - .then((res: any) => { - const newUser = res.data?.userByAddress; - const localAddress = localStorage.getItem(StorageLabel.USER); - if (compareAddresses(localAddress, newUser?.walletAddress)) { - const token = localStorage.getItem(StorageLabel.TOKEN); - return { ...newUser, token }; - } - removeToken(); - return newUser; - }) - .catch((error: unknown) => { - showToastError(error); - captureException(error, { - tags: { - section: 'fetchUser', - }, - }); - }); - }; - - const reFetchUser = () => { - fetchUser().then(setUser); - }; - - const setToken = (token: string) => { - localStorage.setItem(StorageLabel.USER, user?.walletAddress || ''); - localStorage.setItem(StorageLabel.TOKEN, token); - }; - - const removeToken = () => { - localStorage.removeItem(StorageLabel.USER); - localStorage.removeItem(StorageLabel.TOKEN); - }; - - const signOut = () => { - removeToken(); - setUser({ ...user, token: undefined }); - }; - - const signToGetToken = async () => { - const signedMessage = await signMessage( - process.env.NEXT_PUBLIC_OUR_SECRET as string, - account, - chainId, - library.getSigner(), - ); - if (!signedMessage) return false; - - const token = await getToken(account, signedMessage, chainId, user); - await apolloClient.resetStore(); - setToken(token); - setUser({ ...user, token }); - return token; - }; - - const getBalance = () => { - library - .getBalance(account) - .then((_balance: BigNumberish) => { - setBalance(parseFloat(formatEther(_balance)).toFixed(3)); - }) - .catch((error: unknown) => { - setBalance(null); - captureException(error, { - tags: { - section: 'getBalance', - }, - }); - }); - }; - - const incrementLikedProjectsCount = () => { - if (user) { - setUser({ - ...user, - likedProjectsCount: (user.likedProjectsCount || 0) + 1, - }); - } - }; - - const decrementLikedProjectsCount = () => { - if (user) { - setUser({ - ...user, - likedProjectsCount: (user.likedProjectsCount || 1) - 1, - }); - } - }; - - return ( - - {props.children} - - ); -}; - -export default function useUser() { - const context = useContext(UserContext); - - if (!context) { - throw new Error('Claim context not found!'); - } - - return context; -} diff --git a/src/features/user/user.slice.ts b/src/features/user/user.slice.ts index 17eb7e8783..d8edb06cc6 100644 --- a/src/features/user/user.slice.ts +++ b/src/features/user/user.slice.ts @@ -40,6 +40,18 @@ export const userSlice = createSlice({ state.token = undefined; state.isSignedIn = false; }, + incrementLikedProjectsCount: state => { + if (state.userData) { + state.userData.likedProjectsCount = + (state.userData.likedProjectsCount || 0) + 1; + } + }, + decrementLikedProjectsCount: state => { + if (state.userData) { + state.userData.likedProjectsCount = + (state.userData.likedProjectsCount || 1) - 1; + } + }, }, extraReducers: builder => { builder @@ -88,6 +100,13 @@ export const userSlice = createSlice({ }); }, }); -export const { setIsEnabled, setIsSignedIn, setToken, setBalance, signOut } = - userSlice.actions; +export const { + setIsEnabled, + setIsSignedIn, + setToken, + setBalance, + signOut, + incrementLikedProjectsCount, + decrementLikedProjectsCount, +} = userSlice.actions; export default userSlice.reducer; From bfc8bc51f7cd583307f498511b8ff88bede8948e Mon Sep 17 00:00:00 2001 From: alireza-sharifpour Date: Sun, 22 May 2022 19:33:46 +0430 Subject: [PATCH 152/257] Removed console logs and merge 2 useEffects if user.ctrl --- pages/account.tsx | 1 - pages/test.tsx | 19 ++----- src/components/controller/user.ctrl.tsx | 50 ++++++++----------- src/components/menu/MenuWallet.tsx | 1 - src/components/views/create/CreateIndex.tsx | 2 - .../UserPublicProfile.view.tsx | 3 +- src/features/user/user.slice.ts | 6 --- 7 files changed, 24 insertions(+), 58 deletions(-) diff --git a/pages/account.tsx b/pages/account.tsx index a0b4ecaaf6..eb6954b505 100644 --- a/pages/account.tsx +++ b/pages/account.tsx @@ -11,7 +11,6 @@ const NoUserContainer = styled.div` const UserRoute: FC = () => { const user = useAppSelector(state => state.user.userData); - console.log('user', user); return ( <> diff --git a/pages/test.tsx b/pages/test.tsx index 2c0caf544d..a6709fb104 100644 --- a/pages/test.tsx +++ b/pages/test.tsx @@ -3,19 +3,15 @@ import styled from 'styled-components'; import { GetServerSideProps } from 'next'; import { useWeb3React } from '@web3-react/core'; import { gToast, ToastType } from '@/components/toasts'; -import { useAppDispatch, useAppSelector } from '@/features/hooks'; +import { useAppDispatch } from '@/features/hooks'; import { fetchXDaiInfoAsync } from '@/features/subgraph/subgraph.thunks'; -import { signToGetToken } from '@/features/user/user.thunks'; const TestRoute = () => { // const xDaiValues = useSelector( // (state: RootState) => state.subgraph.xDaiValues, // ); - const { library, chainId, account } = useWeb3React(); - const user = useAppSelector(state => state.user); - console.log('userTest', user); + const { account } = useWeb3React(); const dispatch = useAppDispatch(); - const xDaiValues = useAppSelector(state => state.subgraph.xDaiValues); // const { data, isLoading, error, refetch } = useGetSubgraphValuesQuery({ // chain: chainId, @@ -43,15 +39,7 @@ const TestRoute = () => { // }; // }, [library]); // console.log('****data', data); - function handleSignIn() { - dispatch( - signToGetToken({ - address: account, - chainId, - signer: library?.getSigner(), - }), - ); - } + return ( <> @@ -76,7 +64,6 @@ const TestRoute = () => { > Throw error -
); diff --git a/src/components/controller/user.ctrl.tsx b/src/components/controller/user.ctrl.tsx index 474cf35f32..46e96997d1 100644 --- a/src/components/controller/user.ctrl.tsx +++ b/src/components/controller/user.ctrl.tsx @@ -2,7 +2,7 @@ import { useWeb3React } from '@web3-react/core'; import { useEffect } from 'react'; import { formatEther } from '@ethersproject/units'; import { captureException } from '@sentry/nextjs'; -import { useAppDispatch, useAppSelector } from '@/features/hooks'; +import { useAppDispatch } from '@/features/hooks'; import { setBalance, setIsEnabled, @@ -18,30 +18,6 @@ const UserController = () => { const { account, library, chainId, activate } = useWeb3React(); const dispatch = useAppDispatch(); const token = !isSSRMode ? localStorage.getItem(StorageLabel.TOKEN) : null; - const isEnabled = useAppSelector(state => state.user.isEnabled); - const isSignIn = useAppSelector(state => state.user.isSignedIn); - console.log('UserController', isEnabled, isSignIn); - const getBalance = () => { - if (account && library) { - library - .getBalance(account) - .then((_balance: string) => { - const balance = parseFloat(formatEther(_balance)).toFixed( - 3, - ); - console.log('balance', balance); - dispatch(setBalance(balance)); - }) - .catch((error: unknown) => { - dispatch(setBalance(null)); - captureException(error, { - tags: { - section: 'getBalance', - }, - }); - }); - } - }; useEffect(() => { const selectedWalletName = localStorage.getItem(StorageLabel.WALLET); @@ -75,16 +51,30 @@ const UserController = () => { useEffect(() => { if (account && library) { library?.on('block', () => { - getBalance(); + //Getting balance on every block + if (account && library) { + library + .getBalance(account) + .then((_balance: string) => { + const balance = parseFloat( + formatEther(_balance), + ).toFixed(3); + dispatch(setBalance(balance)); + }) + .catch((error: unknown) => { + dispatch(setBalance(null)); + captureException(error, { + tags: { + section: 'getBalance', + }, + }); + }); + } }); } return () => { library?.removeAllListeners('block'); }; - }, [library]); - - useEffect(() => { - getBalance(); }, [account, library, chainId]); return null; diff --git a/src/components/menu/MenuWallet.tsx b/src/components/menu/MenuWallet.tsx index 663dbd045e..da6dbdfa9f 100644 --- a/src/components/menu/MenuWallet.tsx +++ b/src/components/menu/MenuWallet.tsx @@ -39,7 +39,6 @@ const MenuWallet = () => { const dispatch = useAppDispatch(); const { isSignedIn, userData } = useAppSelector(state => state.user); const { theme } = useGeneral(); - console.log('isSignedIn', isSignedIn); const goRoute = (input: { url: string; requiresSign: boolean; diff --git a/src/components/views/create/CreateIndex.tsx b/src/components/views/create/CreateIndex.tsx index f3af6701e9..559756c178 100644 --- a/src/components/views/create/CreateIndex.tsx +++ b/src/components/views/create/CreateIndex.tsx @@ -15,13 +15,11 @@ const CreateIndex = () => { isSignedIn, userData: user, } = useAppSelector(state => state.user); - console.log('Hiii', user); const isRegistered = isUserRegistered(user); useEffect(() => { if (isEnabled) { if (!isRegistered) { - console.log('Hiii'); dispatch(setShowCompleteProfile(true)); return; } diff --git a/src/components/views/userPublicProfile/UserPublicProfile.view.tsx b/src/components/views/userPublicProfile/UserPublicProfile.view.tsx index a231e36772..095f8fbd92 100644 --- a/src/components/views/userPublicProfile/UserPublicProfile.view.tsx +++ b/src/components/views/userPublicProfile/UserPublicProfile.view.tsx @@ -46,8 +46,7 @@ export interface IUserPublicProfileView { const UserPublicProfileView: FC = ({ myAccount }) => { const dispatch = useAppDispatch(); - const { isSignedIn } = useAppSelector(state => state.user); - const userData = useAppSelector(state => state.user.userData); + const { isSignedIn, userData } = useAppSelector(state => state.user); const { chainId } = useWeb3React(); diff --git a/src/features/user/user.slice.ts b/src/features/user/user.slice.ts index d8edb06cc6..65af64e225 100644 --- a/src/features/user/user.slice.ts +++ b/src/features/user/user.slice.ts @@ -68,11 +68,6 @@ export const userSlice = createSlice({ const localAddress = localStorage .getItem(StorageLabel.USER) ?.toLocaleLowerCase(); - console.log( - 'localAddress', - localAddress, - action.payload.data.userByAddress.walletAddress, - ); if ( compareAddresses( localAddress, @@ -89,7 +84,6 @@ export const userSlice = createSlice({ }, ) .addCase(signToGetToken.fulfilled, (state, action) => { - console.log('SignIn Action', action); state.token = action.payload; localStorage.setItem( StorageLabel.USER, From 0ebb8eaf29c2d770e8c502d518dd35960808f08b Mon Sep 17 00:00:00 2001 From: Ramin Date: Sun, 22 May 2022 23:51:15 +0430 Subject: [PATCH 153/257] fix donation input file location --- src/components/views/donate/CryptoDonation.tsx | 2 +- src/components/views/{create => donate}/InputBox.tsx | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename src/components/views/{create => donate}/InputBox.tsx (100%) diff --git a/src/components/views/donate/CryptoDonation.tsx b/src/components/views/donate/CryptoDonation.tsx index e709177ca1..15b4748298 100644 --- a/src/components/views/donate/CryptoDonation.tsx +++ b/src/components/views/donate/CryptoDonation.tsx @@ -17,7 +17,7 @@ import tokenAbi from 'human-standard-token-abi'; import { captureException } from '@sentry/nextjs'; import { Shadow } from '@/components/styled-components/Shadow'; -import InputBox from '../create/InputBox'; +import InputBox from './InputBox'; import useUser from '@/context/UserProvider'; import CheckBox from '@/components/Checkbox'; import DonateModal from '@/components/modals/DonateModal'; diff --git a/src/components/views/create/InputBox.tsx b/src/components/views/donate/InputBox.tsx similarity index 100% rename from src/components/views/create/InputBox.tsx rename to src/components/views/donate/InputBox.tsx From c61d01f5fab3f134df050e7b3195e74a722596e4 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 23 May 2022 11:29:20 +0430 Subject: [PATCH 154/257] add useLeaveConfirm hook --- src/hooks/useLeaveConfirm.tsx | 44 +++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/hooks/useLeaveConfirm.tsx diff --git a/src/hooks/useLeaveConfirm.tsx b/src/hooks/useLeaveConfirm.tsx new file mode 100644 index 0000000000..8ff51ba499 --- /dev/null +++ b/src/hooks/useLeaveConfirm.tsx @@ -0,0 +1,44 @@ +import { useRouter } from 'next/router'; +import { useEffect } from 'react'; + +type Props = { + shouldConfirm: boolean; + message?: string; +}; + +const defaultMessage = 'Are you sure to leave without save?'; + +const useLeaveConfirm = ({ + shouldConfirm, + message = defaultMessage, +}: Props) => { + const Router = useRouter(); + + useEffect(() => { + const onberforeunload = function (event: any) { + event.returnValue = message; + }; + const onRouteChangeStart = () => { + if (shouldConfirm) { + if (window.confirm(message)) { + return true; + } + Router.events.emit('routeChangeError'); + throw "Abort route change by user's confirmation."; + } + }; + if (shouldConfirm) { + console.log('hereeeeeeeeeeeee', shouldConfirm); + Router.events.on('routeChangeStart', onRouteChangeStart); + window.addEventListener('beforeunload', onberforeunload); + } + + return () => { + window.removeEventListener('beforeunload', onberforeunload); + Router.events.off('routeChangeStart', onRouteChangeStart); + }; + }, [Router.events, message, shouldConfirm]); + + return; +}; +export default useLeaveConfirm; From dcc9f1fce4eaff2856741784529e1c6872474204 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 23 May 2022 11:29:52 +0430 Subject: [PATCH 155/257] use useLeaveConfirm in create project --- src/components/views/create/CreateProject.tsx | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/src/components/views/create/CreateProject.tsx b/src/components/views/create/CreateProject.tsx index 58a36e7703..ad3fc890f2 100644 --- a/src/components/views/create/CreateProject.tsx +++ b/src/components/views/create/CreateProject.tsx @@ -49,6 +49,7 @@ import LightBulbIcon from '/public/images/icons/lightbulb.svg'; import { Shadow } from '@/components/styled-components/Shadow'; import { deviceSize, mediaQueries } from '@/lib/constants/constants'; import { useAppSelector } from '@/features/hooks'; +import useLeaveConfirm from '@/hooks/useLeaveConfirm'; export enum ECreateErrFields { NAME = 'name', @@ -103,6 +104,7 @@ const CreateProject = (props: { project?: IProjectEdition }) => { const debouncedTitleValidation = useRef(); const debouncedAddressValidation = useRef(); const debouncedDescriptionValidation = useRef(); + useLeaveConfirm({ shouldConfirm: formChange }); useEffect(() => { if (isEditMode) { @@ -156,17 +158,6 @@ const CreateProject = (props: { project?: IProjectEdition }) => { ); }, []); - useEffect(() => { - const onberforeunload = function (event: any) { - event.returnValue = 'Write something clever here..'; - }; - if (formChange) - window.addEventListener('beforeunload', onberforeunload); - return () => { - window.removeEventListener('beforeunload', onberforeunload); - }; - }, [formChange]); - const handleInputChange = (value: string, id: string) => { if (id === ECreateErrFields.NAME) { setName(value); @@ -320,6 +311,7 @@ const CreateProject = (props: { project?: IProjectEdition }) => { { + console.log('name'); setFormChange(true); handleInputChange(e, ECreateErrFields.NAME); }} @@ -328,6 +320,7 @@ const CreateProject = (props: { project?: IProjectEdition }) => { { + console.log('name'); setFormChange(true); handleInputChange( e, @@ -339,6 +332,7 @@ const CreateProject = (props: { project?: IProjectEdition }) => { { + console.log('category'); setFormChange(true); setCategories(category); }} @@ -346,6 +340,7 @@ const CreateProject = (props: { project?: IProjectEdition }) => { { + console.log('location'); setFormChange(true); setImpactLocation(location); }} @@ -353,6 +348,7 @@ const CreateProject = (props: { project?: IProjectEdition }) => { { + console.log('image'); setFormChange(true); setImage(img); }} @@ -361,6 +357,7 @@ const CreateProject = (props: { project?: IProjectEdition }) => { { + console.log('walletAddress'); setFormChange(true); handleInputChange( e, From 5d9b6e9a06ebea5221f93e1dfe891bd4434ef082 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 23 May 2022 13:09:22 +0430 Subject: [PATCH 156/257] create GeneralMetatags component --- src/components/Metatag.tsx | 64 ++++++++++++++++ src/lib/meta.tsx | 151 ------------------------------------- 2 files changed, 64 insertions(+), 151 deletions(-) create mode 100644 src/components/Metatag.tsx delete mode 100644 src/lib/meta.tsx diff --git a/src/components/Metatag.tsx b/src/components/Metatag.tsx new file mode 100644 index 0000000000..778f8d55c8 --- /dev/null +++ b/src/components/Metatag.tsx @@ -0,0 +1,64 @@ +import { IProject } from '@/apollo/types/types'; +import { htmlToText } from '@/lib/helpers'; +import type { FC } from 'react'; + +export interface IMetaTags { + title: string; + desc: string; + image: string; + url: string; + type?: string; +} +export const GeneralMetatags: FC<{ info: IMetaTags }> = ({ info }) => { + return ( + <> + {info.title} + + + + + + + + + + + + + + + + + ); +}; + +export const ProjectMeta = (props: { + project?: IProject; + preTitle?: string; +}) => { + const { project, preTitle } = props; + const metaDescription = htmlToText(project?.description?.slice(0, 100)); + return ( + <> + + + + + + + + + + + + ); +}; diff --git a/src/lib/meta.tsx b/src/lib/meta.tsx deleted file mode 100644 index df01271f2b..0000000000 --- a/src/lib/meta.tsx +++ /dev/null @@ -1,151 +0,0 @@ -import React from 'react'; -import { IProject } from '@/apollo/types/types'; -import { htmlToText } from '@/lib/helpers'; - -export const HomeMeta = () => { - return ( - <> - - - - - - - - - - - - - - - - - ); -}; - -export const ProjectsMeta = () => { - return ( - <> - - - - - - - - - - - - - - - - - ); -}; - -export const GiveconomyMeta = () => { - return ( - <> - - - - - - - - - - - - - - - - - ); -}; - -export const ProjectMeta = (props: { - project?: IProject; - preTitle?: string; -}) => { - const { project, preTitle } = props; - const metaDescription = htmlToText(project?.description?.slice(0, 100)); - return ( - <> - - - - - - - - - - - - ); -}; From f958403125b12ea96d520f66f1755dae16727da6 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 23 May 2022 13:09:35 +0430 Subject: [PATCH 157/257] add metatags content --- src/content/metatags.ts | 55 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/content/metatags.ts diff --git a/src/content/metatags.ts b/src/content/metatags.ts new file mode 100644 index 0000000000..fce6a3385c --- /dev/null +++ b/src/content/metatags.ts @@ -0,0 +1,55 @@ +export const homeMetatags = { + title: 'Giveth: Welcome to the Future of Giving', + desc: 'Get rewarded for giving to for-good projects with zero added fees. Donate crypto directly to over 1,000 for-good projects, non profits & charities!', + image: 'https://giveth.mypinata.cloud/ipfs/QmQ9sfdevs9vS7czBXBfDaRRPhU8a6T5gXxF3NDGSnQe1c', + url: 'https://giveth.io/', +}; + +export const givfarmMetatags = { + title: 'GIVfarm: Stake-to-earn while supporting for-good DAOs', + desc: 'Get crypto rewards by providing liquidity and supporting the GIVeconomy. Support Regen projects and kickstart your UBI-esque reward streams!', + image: 'https://i.ibb.co/HTbdCdd/Thumbnail.png', + url: 'https://giveth.io/givfarm', +}; + +export const aboutMetatags = { + title: 'About Giveth: Mission, Vision & Values', + desc: 'Giveth is a community focused on Building the Future of Giving using crypto & blockchain technology. Learn about our mission, vision & values.', + image: 'https://giveth.mypinata.cloud/ipfs/QmQ9sfdevs9vS7czBXBfDaRRPhU8a6T5gXxF3NDGSnQe1c', + url: 'https://giveth.io/about', +}; + +export const givstreamMetatags = { + title: 'GIVstream: Get more GIV/week until the end of 2026', + desc: 'Want to earn crypto reward stream by doing good? Support the GIVeconomy to earn rewards and kickstart your GIV/week flowrate.', + image: 'https://i.ibb.co/HTbdCdd/Thumbnail.png', + url: 'https://giveth.io/givstream', +}; + +export const givgardenMetatags = { + title: 'GIVgarden: Have your say in Giveth governance', + desc: 'We need your help to shape the future of Giving! With the power of Conviction Voting, use your GIV to vote to allocate funding to community proposals.', + image: 'https://i.ibb.co/HTbdCdd/Thumbnail.png', + url: 'https://giveth.io/givgarden', +}; + +export const projectsMetatags = { + title: 'Give directly to for-good projects with crypto & zero fees', + desc: 'Support for-good projects, nonprofits & charities with crypto donations. Give directly with zero added fees. Get rewarded when you donate to verified projects!', + image: 'https://giveth.mypinata.cloud/ipfs/QmQ9sfdevs9vS7czBXBfDaRRPhU8a6T5gXxF3NDGSnQe1c', + url: 'https://giveth.io/projects', +}; + +export const givbacksMetatags = { + title: 'GIVbacks: Get rewarded for donating to verified projects', + desc: 'GIVbacks rewards donors to verified projects with GIV, super-charging Giveth as a donor-driven force for good. GIVbacks is only available on Gnosis Chain.', + image: 'https://i.ibb.co/HTbdCdd/Thumbnail.png', + url: 'https://giveth.io/givbacks', +}; + +export const giveconomyMetatags = { + title: 'GIVeconomy: Empowering our collective to build the Future of Giving.', + desc: 'Giveth is a donor owned and governed economy. With GIVbacks, we reward donors to verified projects on Giveth with GIV. ', + image: 'https://i.ibb.co/HTbdCdd/Thumbnail.png', + url: 'https://giveth.io/giveconomy', +}; From 13a7e5e5b8b5391f7bb8f3c571e96d51f5c7490b Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 23 May 2022 13:09:56 +0430 Subject: [PATCH 158/257] use GeneralMetatags in about page --- pages/about.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pages/about.tsx b/pages/about.tsx index 8adeef14ad..f6c48e158b 100644 --- a/pages/about.tsx +++ b/pages/about.tsx @@ -1,11 +1,13 @@ import Head from 'next/head'; import AboutIndex from '@/components/views/about/AboutIndex'; +import { aboutMetatags } from '@/content/metatags'; +import { GeneralMetatags } from '@/components/Metatag'; const AboutRoute = () => { return ( <> - About Us | Giveth + From 57a94438c3bf0cbd32a95533728fb8dfdf5c134f Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 23 May 2022 13:10:16 +0430 Subject: [PATCH 159/257] use GeneralMetatags in givbacks page --- pages/givbacks.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pages/givbacks.tsx b/pages/givbacks.tsx index fd5ff0ebc8..185495e490 100644 --- a/pages/givbacks.tsx +++ b/pages/givbacks.tsx @@ -3,7 +3,8 @@ import { useEffect } from 'react'; import GIVbackView from '@/components/views/Back.view'; import { useGeneral, ETheme } from '@/context/general.context'; -import { GiveconomyMeta } from '@/lib/meta'; +import { givbacksMetatags } from '@/content/metatags'; +import { GeneralMetatags } from '@/components/Metatag'; export default function GIVbacksRoute() { const { setTheme } = useGeneral(); @@ -17,8 +18,7 @@ export default function GIVbacksRoute() { return ( <> - GIVbacks - + From 657684d8ee1b0ba4a88b9ed514a2c48248842fae Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 23 May 2022 13:10:26 +0430 Subject: [PATCH 160/257] use GeneralMetatags in giveconomy page --- pages/giveconomy.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pages/giveconomy.tsx b/pages/giveconomy.tsx index 1d4ffa7843..2ec37d4966 100644 --- a/pages/giveconomy.tsx +++ b/pages/giveconomy.tsx @@ -3,7 +3,8 @@ import { useEffect } from 'react'; import HomeView from '@/components/views/Home.view'; import { ETheme, useGeneral } from '@/context/general.context'; -import { GiveconomyMeta } from '@/lib/meta'; +import { giveconomyMetatags } from '@/content/metatags'; +import { GeneralMetatags } from '@/components/Metatag'; export default function GIVeconomyRoute() { const { setTheme } = useGeneral(); @@ -18,8 +19,7 @@ export default function GIVeconomyRoute() { return ( <> - GIVeconomy - + From de5030d7f5a1f90e1e8ef190fef33d49f27e8418 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 23 May 2022 13:10:38 +0430 Subject: [PATCH 161/257] use GeneralMetatags in givfarm page --- pages/givfarm.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pages/givfarm.tsx b/pages/givfarm.tsx index ac631431fa..ff2f1eb5e3 100644 --- a/pages/givfarm.tsx +++ b/pages/givfarm.tsx @@ -3,7 +3,8 @@ import { useEffect } from 'react'; import GIVfarmView from '@/components/views/Farm.view'; import { useGeneral, ETheme } from '@/context/general.context'; -import { GiveconomyMeta } from '@/lib/meta'; +import { givfarmMetatags } from '@/content/metatags'; +import { GeneralMetatags } from '@/components/Metatag'; export default function GIVfarmRoute() { const { setTheme } = useGeneral(); @@ -17,8 +18,7 @@ export default function GIVfarmRoute() { return ( <> - GIVfarm - + From 54aa83c3accc4d3269a24149a203c78b68a439d9 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 23 May 2022 13:10:51 +0430 Subject: [PATCH 162/257] use GeneralMetatags in givgarden page --- pages/givgarden.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pages/givgarden.tsx b/pages/givgarden.tsx index 2b18a6c978..889c1bb38b 100644 --- a/pages/givgarden.tsx +++ b/pages/givgarden.tsx @@ -3,7 +3,8 @@ import { useEffect } from 'react'; import GIVgardenView from '@/components/views/Garden.view'; import { useGeneral, ETheme } from '@/context/general.context'; -import { GiveconomyMeta } from '@/lib/meta'; +import { givgardenMetatags } from '@/content/metatags'; +import { GeneralMetatags } from '@/components/Metatag'; export default function GIVgardenRoute() { const { setTheme } = useGeneral(); @@ -17,8 +18,7 @@ export default function GIVgardenRoute() { return ( <> - GIVgarden - + From 1e1a964abdedc26f1c03aa7e7052196440c21801 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 23 May 2022 13:10:59 +0430 Subject: [PATCH 163/257] use GeneralMetatags in index page --- pages/index.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pages/index.tsx b/pages/index.tsx index 43f6d58b9a..5a370d39c1 100644 --- a/pages/index.tsx +++ b/pages/index.tsx @@ -6,8 +6,9 @@ import { client } from '@/apollo/apolloClient'; import { FETCH_HOME_PROJECTS } from '@/apollo/gql/gqlProjects'; import { EDirection, gqlEnums } from '@/apollo/types/gqlEnums'; import { IProject } from '@/apollo/types/types'; -import { HomeMeta } from '@/lib/meta'; import { useAppSelector } from '@/features/hooks'; +import { homeMetatags } from '@/content/metatags'; +import { GeneralMetatags } from '@/components/Metatag'; const projectsToFetch = 12; @@ -49,8 +50,7 @@ const HomeRoute = (props: IHomeRoute) => { return ( <> - Home | Giveth - + From c390103cabc1456224f5812695a67d26dd27a425 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 23 May 2022 13:11:08 +0430 Subject: [PATCH 164/257] use GeneralMetatags in givstream page --- pages/givstream.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pages/givstream.tsx b/pages/givstream.tsx index c32c4d9dcc..4fa22e438e 100644 --- a/pages/givstream.tsx +++ b/pages/givstream.tsx @@ -3,7 +3,8 @@ import { useEffect } from 'react'; import GIVstreamView from '@/components/views/Stream.view'; import { useGeneral, ETheme } from '@/context/general.context'; -import { GiveconomyMeta } from '@/lib/meta'; +import { givstreamMetatags } from '@/content/metatags'; +import { GeneralMetatags } from '@/components/Metatag'; export default function GIVstreamRoute() { const { setTheme } = useGeneral(); @@ -17,8 +18,7 @@ export default function GIVstreamRoute() { return ( <> - GIVstream - + From 2be03995fc030e43d3e073850ae3eb949453bc1b Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 23 May 2022 13:11:21 +0430 Subject: [PATCH 165/257] use GeneralMetatags in projects page --- pages/projects.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pages/projects.tsx b/pages/projects.tsx index 0e4737cade..6c7cb89bcd 100644 --- a/pages/projects.tsx +++ b/pages/projects.tsx @@ -4,7 +4,8 @@ import { FETCH_ALL_PROJECTS } from '@/apollo/gql/gqlProjects'; import { OPTIONS_HOME_PROJECTS } from '@/apollo/gql/gqlOptions'; import ProjectsIndex from '@/components/views/projects/ProjectsIndex'; import { ICategory, IProject } from '@/apollo/types/types'; -import { ProjectsMeta } from '@/lib/meta'; +import { projectsMetatags } from '@/content/metatags'; +import { GeneralMetatags } from '@/components/Metatag'; interface IProjectsRoute { projects: IProject[]; @@ -17,8 +18,7 @@ const ProjectsRoute = (props: IProjectsRoute) => { return ( <> - Projects | Giveth - + Date: Mon, 23 May 2022 13:11:42 +0430 Subject: [PATCH 166/257] remove claim duplicate metatags --- pages/claim.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/pages/claim.tsx b/pages/claim.tsx index 8bc30b27db..5a78a15056 100644 --- a/pages/claim.tsx +++ b/pages/claim.tsx @@ -4,7 +4,6 @@ import { useEffect } from 'react'; import ClaimView from '@/components/views/claim/Claim.view'; import { ClaimProvider } from '@/context/claim.context'; import { ETheme, useGeneral } from '@/context/general.context'; -import { GiveconomyMeta } from '@/lib/meta'; export default function GIVdropRoute() { const { setShowHeader, setTheme } = useGeneral(); @@ -22,7 +21,6 @@ export default function GIVdropRoute() { <> GIVdrop - From 1e9154fcec004905782ac0de147d5416fbaf62c3 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 23 May 2022 13:11:54 +0430 Subject: [PATCH 167/257] fix imoprts --- pages/donate/[slug].tsx | 2 +- src/components/views/project/ProjectIndex.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pages/donate/[slug].tsx b/pages/donate/[slug].tsx index 6f66e10e35..4c344267e5 100644 --- a/pages/donate/[slug].tsx +++ b/pages/donate/[slug].tsx @@ -6,7 +6,7 @@ import { captureException } from '@sentry/nextjs'; import { IProjectBySlug } from '@/apollo/types/types'; import { FETCH_PROJECT_BY_SLUG } from '@/apollo/gql/gqlProjects'; import { client } from '@/apollo/apolloClient'; -import { ProjectMeta } from '@/lib/meta'; +import { ProjectMeta } from '@/components/Metatag'; const DonateIndex = dynamic( () => import('@/components/views/donate/DonateIndex'), diff --git a/src/components/views/project/ProjectIndex.tsx b/src/components/views/project/ProjectIndex.tsx index 465553ab39..8645d683f5 100644 --- a/src/components/views/project/ProjectIndex.tsx +++ b/src/components/views/project/ProjectIndex.tsx @@ -19,10 +19,10 @@ import { IDonationsByProjectIdGQL } from '@/apollo/types/gqlTypes'; import SuccessfulCreation from '@/components/views/create/SuccessfulCreation'; import { deviceSize, mediaQueries } from '@/lib/constants/constants'; import InlineToast from '@/components/toasts/InlineToast'; -import { ProjectMeta } from '@/lib/meta'; import SimilarProjects from '@/components/views/project/SimilarProjects'; import { showToastError } from '@/lib/helpers'; import { useAppSelector } from '@/features/hooks'; +import { ProjectMeta } from '@/components/Metatag'; const ProjectDonations = dynamic(() => import('./ProjectDonations')); const ProjectUpdates = dynamic(() => import('./ProjectUpdates')); From 5396017c2a7c5ec37651f32c770c3b5e46d670bd Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 23 May 2022 13:32:26 +0430 Subject: [PATCH 168/257] remove log --- src/hooks/useLeaveConfirm.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/src/hooks/useLeaveConfirm.tsx b/src/hooks/useLeaveConfirm.tsx index 8ff51ba499..5ad2335eb1 100644 --- a/src/hooks/useLeaveConfirm.tsx +++ b/src/hooks/useLeaveConfirm.tsx @@ -28,7 +28,6 @@ const useLeaveConfirm = ({ } }; if (shouldConfirm) { - console.log('hereeeeeeeeeeeee', shouldConfirm); Router.events.on('routeChangeStart', onRouteChangeStart); window.addEventListener('beforeunload', onberforeunload); } From 99514ca6e533fe2cf3cbe53886a94577f047c368 Mon Sep 17 00:00:00 2001 From: Mateo Daza Date: Mon, 23 May 2022 09:48:08 -0500 Subject: [PATCH 169/257] adds logout token from backend --- src/components/menu/MenuWallet.tsx | 8 +++- src/components/modals/SignWithWalletModal.tsx | 5 +++ src/features/user/user.thunks.ts | 43 ++++++++++--------- src/features/user/user.types.ts | 1 + src/services/token.ts | 6 +++ 5 files changed, 41 insertions(+), 22 deletions(-) diff --git a/src/components/menu/MenuWallet.tsx b/src/components/menu/MenuWallet.tsx index da6dbdfa9f..dac691755c 100644 --- a/src/components/menu/MenuWallet.tsx +++ b/src/components/menu/MenuWallet.tsx @@ -26,6 +26,7 @@ import { setShowCompleteProfile, setShowWalletModal, } from '@/features/modal/modal.sclie'; +import { logoutToken } from '@/services/token'; import { signOut } from '@/features/user/user.slice'; const MenuWallet = () => { @@ -37,7 +38,7 @@ const MenuWallet = () => { const router = useRouter(); const dispatch = useAppDispatch(); - const { isSignedIn, userData } = useAppSelector(state => state.user); + const { isSignedIn, userData, token } = useAppSelector(state => state.user); const { theme } = useGeneral(); const goRoute = (input: { url: string; @@ -137,7 +138,10 @@ const MenuWallet = () => { ))} {isSignedIn && ( dispatch(signOut())} + onClick={async () => { + await logoutToken(token!); + dispatch(signOut()); + }} theme={theme} > Sign out diff --git a/src/components/modals/SignWithWalletModal.tsx b/src/components/modals/SignWithWalletModal.tsx index 3b2cc71081..9f163be209 100644 --- a/src/components/modals/SignWithWalletModal.tsx +++ b/src/components/modals/SignWithWalletModal.tsx @@ -8,6 +8,7 @@ import { neutralColors, } from '@giveth/ui-design-system'; import { useWeb3React } from '@web3-react/core'; +import { useRouter } from 'next/router'; import { Modal } from '@/components/modals/Modal'; import { ETheme, useGeneral } from '@/context/general.context'; @@ -24,6 +25,8 @@ interface IProps extends IModal { export const SignWithWalletModal: FC = ({ setShowModal, callback }) => { const { theme } = useGeneral(); const { account, library, chainId } = useWeb3React(); + const router = useRouter(); + const dispatch = useAppDispatch(); return ( @@ -53,8 +56,10 @@ export const SignWithWalletModal: FC = ({ setShowModal, callback }) => { address: account, chainId, signer: library?.getSigner(), + pathname: router.pathname, }), ); + console.log({ signature }); setShowModal(false); !!signature && callback && callback(); }} diff --git a/src/features/user/user.thunks.ts b/src/features/user/user.thunks.ts index 720cce3a4c..fc392f0dbd 100644 --- a/src/features/user/user.thunks.ts +++ b/src/features/user/user.thunks.ts @@ -2,7 +2,7 @@ import { createAsyncThunk } from '@reduxjs/toolkit'; import gqlRequest from '@/helpers/gqlRequest'; import { GET_USER_BY_ADDRESS } from './user.queries'; import { ISignToGetToken } from './user.types'; -import { signMessage } from '@/lib/helpers'; +import { signMessage, createSiweMessage } from '@/lib/helpers'; import { getToken } from '@/services/token'; import { RootState } from '../store'; @@ -16,28 +16,31 @@ export const fetchUserByAddress = createAsyncThunk( export const signToGetToken = createAsyncThunk( 'user/signToGetToken', async ( - { address, chainId, signer }: ISignToGetToken, + { address, chainId, signer, pathname }: ISignToGetToken, { getState, dispatch }, ) => { - const signedMessage = await signMessage( - process.env.NEXT_PUBLIC_OUR_SECRET as string, - address, - chainId, - signer, - ); - if (signedMessage) { - const state = getState() as RootState; - console.log('getToken State', state.user.userData); - if (!state.user.userData) { - await dispatch(fetchUserByAddress(address)); - } - return getToken( - address, - signedMessage, - chainId, - state.user.userData, + try { + const siweMessage: any = await createSiweMessage( + address!, + chainId!, + pathname!, + 'Login into Giveth services', ); - } else { + const { nonce, message } = siweMessage; + const signature = await signer.signMessage(message); + if (signature) { + const state = getState() as RootState; + console.log('getToken State', state.user.userData); + if (!state.user.userData) { + await dispatch(fetchUserByAddress(address)); + } + const token = await getToken(signature, message, nonce); + return token.jwt; + } else { + return Promise.reject('Signing failed'); + } + } catch (error) { + console.log({ error }); return Promise.reject('Signing failed'); } }, diff --git a/src/features/user/user.types.ts b/src/features/user/user.types.ts index 41bdc1a881..9a2f69dbf1 100644 --- a/src/features/user/user.types.ts +++ b/src/features/user/user.types.ts @@ -2,4 +2,5 @@ export interface ISignToGetToken { address: string; chainId?: number; signer: any; + pathname?: string; } diff --git a/src/services/token.ts b/src/services/token.ts index ac2e85a72e..63e74a4dcd 100644 --- a/src/services/token.ts +++ b/src/services/token.ts @@ -59,6 +59,12 @@ export async function getToken( ); } +export async function logoutToken(jwt: string) { + return await postData(`${config.MICROSERVICES.authentication}/logout`, { + jwt, + }); +} + export const fetchPrice = async ( chainId: number, tokenAddress: string | undefined, From 6b567cde28b5b3872003ac6c03fa655ffe43b097 Mon Sep 17 00:00:00 2001 From: Mateo Daza Date: Mon, 23 May 2022 09:52:02 -0500 Subject: [PATCH 170/257] removes unused signMessage function --- src/features/user/user.thunks.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/features/user/user.thunks.ts b/src/features/user/user.thunks.ts index fc392f0dbd..17f6f21683 100644 --- a/src/features/user/user.thunks.ts +++ b/src/features/user/user.thunks.ts @@ -2,7 +2,7 @@ import { createAsyncThunk } from '@reduxjs/toolkit'; import gqlRequest from '@/helpers/gqlRequest'; import { GET_USER_BY_ADDRESS } from './user.queries'; import { ISignToGetToken } from './user.types'; -import { signMessage, createSiweMessage } from '@/lib/helpers'; +import { createSiweMessage } from '@/lib/helpers'; import { getToken } from '@/services/token'; import { RootState } from '../store'; From 4eeb23a65076129b3fc16277f04994b4cb0f2208 Mon Sep 17 00:00:00 2001 From: mitch Date: Mon, 23 May 2022 08:55:36 -0600 Subject: [PATCH 171/257] update default discord link --- src/lib/constants/links.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/constants/links.ts b/src/lib/constants/links.ts index e153831522..223884da50 100644 --- a/src/lib/constants/links.ts +++ b/src/lib/constants/links.ts @@ -13,7 +13,7 @@ const links: any = { FEATURE_REQUEST: 'https://giveth.typeform.com/featurerequest', FEEDBACK: 'https://giveth.typeform.com/feedback', PROJECT_VERIFICATION: 'https://giveth.typeform.com/verification', - DISCORD: 'https://discord.gg/Uq2TaXP9bC', + DISCORD: 'https://discord.giveth.io', DISCOURSE, GIVBACK_TOKENS_FORUM: 'https://forum.giveth.io/t/givbacks-token-list/253', GITHUB: 'https://github.com/Giveth/', From 122242224975cd0fd33a9c9a82fb317ce77cb0b4 Mon Sep 17 00:00:00 2001 From: alireza-sharifpour Date: Mon, 23 May 2022 19:40:19 +0430 Subject: [PATCH 172/257] Fixed User public view issue --- .../UserPublicProfile.view.tsx | 53 +++++++++---------- 1 file changed, 26 insertions(+), 27 deletions(-) diff --git a/src/components/views/userPublicProfile/UserPublicProfile.view.tsx b/src/components/views/userPublicProfile/UserPublicProfile.view.tsx index 095f8fbd92..52bc3c4020 100644 --- a/src/components/views/userPublicProfile/UserPublicProfile.view.tsx +++ b/src/components/views/userPublicProfile/UserPublicProfile.view.tsx @@ -44,24 +44,27 @@ export interface IUserPublicProfileView { myAccount?: boolean; } -const UserPublicProfileView: FC = ({ myAccount }) => { +const UserPublicProfileView: FC = ({ + myAccount, + user, +}) => { const dispatch = useAppDispatch(); - const { isSignedIn, userData } = useAppSelector(state => state.user); + const { isSignedIn } = useAppSelector(state => state.user); const { chainId } = useWeb3React(); const [showModal, setShowModal] = useState(false); // follow this state to refresh user content on screen const [showIncompleteWarning, setShowIncompleteWarning] = useState(true); const showCompleteProfile = - !isUserRegistered(userData) && showIncompleteWarning && myAccount; + !isUserRegistered(user) && showIncompleteWarning && myAccount; useEffect(() => { if (myAccount && !isSignedIn) { dispatch(setShowSignWithWallet(true)); } - }, [userData, isSignedIn]); + }, [user, isSignedIn]); - if (!userData || (myAccount && !isSignedIn)) + if (!user || (myAccount && !isSignedIn)) return (
Not logged in
@@ -79,40 +82,36 @@ const UserPublicProfileView: FC = ({ myAccount }) => { )} {userData?.name} -

{userData?.name}

- {userData?.email && ( - {userData?.email} +

{user?.name}

+ {user?.email && ( + {user?.email} )} - {myAccount && - userData?.name && - userData?.email && ( - setShowModal(true)} - > - Edit Profile - - )} + {myAccount && user?.name && user?.email && ( + setShowModal(true)} + > + Edit Profile + + )} - {userData?.walletAddress} + {user?.walletAddress} - {shortenAddress( - userData?.walletAddress, - )} + {shortenAddress(user?.walletAddress)} @@ -124,9 +123,9 @@ const UserPublicProfileView: FC = ({ myAccount }) => {
- + {showModal && ( - + )} ); From 02bf5cc89191f424139fb21613f06739a4b7997c Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 23 May 2022 21:41:36 +0430 Subject: [PATCH 173/257] create new request --- src/helpers/{gqlRequest.ts => requests.ts} | 30 ++++++++++++++++------ src/lib/helpers.ts | 15 ----------- 2 files changed, 22 insertions(+), 23 deletions(-) rename src/helpers/{gqlRequest.ts => requests.ts} (74%) diff --git a/src/helpers/gqlRequest.ts b/src/helpers/requests.ts similarity index 74% rename from src/helpers/gqlRequest.ts rename to src/helpers/requests.ts index 0e3daf6827..403ecadb74 100644 --- a/src/helpers/gqlRequest.ts +++ b/src/helpers/requests.ts @@ -2,9 +2,9 @@ import { isSSRMode } from '@/lib/helpers'; import links from '@/lib/constants/links'; import StorageLabel from '@/lib/localStorage'; -export default function gqlRequest( - query: string, - variables: {} = {}, +export function postRequest( + url: string, + body: {} = {}, additionalHeaders: HeadersInit = {}, additionalOptions: RequestInit = {}, ) { @@ -21,13 +21,10 @@ export default function gqlRequest( } : { ...defaultHeaders }; try { - return fetch(links.BACKEND, { + return fetch(url, { method: 'POST', headers, - body: JSON.stringify({ - query, - variables, - }), + body: JSON.stringify(body), ...additionalOptions, }).then(async response => { if (response.ok) { @@ -43,3 +40,20 @@ export default function gqlRequest( return Promise.reject(error); } } + +export function gqlRequest( + query: string, + variables: {} = {}, + additionalHeaders: HeadersInit = {}, + additionalOptions: RequestInit = {}, +) { + return postRequest( + links.BACKEND, + { + query, + variables, + }, + additionalHeaders, + additionalOptions, + ); +} diff --git a/src/lib/helpers.ts b/src/lib/helpers.ts index 056183917b..4c7f465d7a 100644 --- a/src/lib/helpers.ts +++ b/src/lib/helpers.ts @@ -397,21 +397,6 @@ export const networkInfo = (networkId?: number) => { }; }; -export const postData = async (url: string, data: object) => { - const response = await fetch(url, { - method: 'POST', - cache: 'no-cache', - credentials: 'same-origin', - headers: { - 'Content-Type': 'application/json', - }, - redirect: 'follow', - referrerPolicy: 'no-referrer', - body: JSON.stringify(data), - }); - return response.json(); -}; - export const createSiweMessage = async ( address: string, chainId: number, From fb476cb1503e41691617b922a1e3162028ddd517 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 23 May 2022 21:42:01 +0430 Subject: [PATCH 174/257] use new request --- src/features/user/user.thunks.ts | 2 +- src/services/token.ts | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/features/user/user.thunks.ts b/src/features/user/user.thunks.ts index 17f6f21683..d605b510e8 100644 --- a/src/features/user/user.thunks.ts +++ b/src/features/user/user.thunks.ts @@ -1,5 +1,5 @@ import { createAsyncThunk } from '@reduxjs/toolkit'; -import gqlRequest from '@/helpers/gqlRequest'; +import { gqlRequest } from '@/helpers/requests'; import { GET_USER_BY_ADDRESS } from './user.queries'; import { ISignToGetToken } from './user.types'; import { createSiweMessage } from '@/lib/helpers'; diff --git a/src/services/token.ts b/src/services/token.ts index 63e74a4dcd..f22d1e78a9 100644 --- a/src/services/token.ts +++ b/src/services/token.ts @@ -4,8 +4,9 @@ import { captureException } from '@sentry/nextjs'; import { IUser } from '@/apollo/types/types'; import { initializeApollo } from '@/apollo/apolloClient'; import { LOGIN_USER } from '@/apollo/gql/gqlAuth'; -import { showToastError, postData } from '@/lib/helpers'; +import { showToastError } from '@/lib/helpers'; import config from '@/configuration'; +import { postRequest } from '@/helpers/requests'; const apolloClient = initializeApollo(); @@ -49,7 +50,7 @@ export async function getToken( message: string, nonce: string, ) { - return await postData( + return await postRequest( `${config.MICROSERVICES.authentication}/authentication`, { signature, @@ -60,7 +61,7 @@ export async function getToken( } export async function logoutToken(jwt: string) { - return await postData(`${config.MICROSERVICES.authentication}/logout`, { + return await postRequest(`${config.MICROSERVICES.authentication}/logout`, { jwt, }); } From 503dae6f84985318e267d3ac7a9a8b6439370b19 Mon Sep 17 00:00:00 2001 From: Mateo Daza Date: Mon, 23 May 2022 14:16:30 -0500 Subject: [PATCH 175/257] lazy loads siwe --- src/lib/helpers.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/helpers.ts b/src/lib/helpers.ts index 4c7f465d7a..8265e84f59 100644 --- a/src/lib/helpers.ts +++ b/src/lib/helpers.ts @@ -7,7 +7,6 @@ import { Contract } from '@ethersproject/contracts'; import { Web3Provider } from '@ethersproject/providers'; import { AddressZero } from '@ethersproject/constants'; import { brandColors } from '@giveth/ui-design-system'; -import { SiweMessage } from 'siwe'; // @ts-ignore import abi from 'human-standard-token-abi'; @@ -415,6 +414,7 @@ export const createSiweMessage = async ( return n.json(); }); const nonce = nonceResponse.message; + const { SiweMessage } = await import('siwe'); const siweMessage = new SiweMessage({ domain, address, From e41f0f923d50613cf1c7c0e9fef16de8e33bb38e Mon Sep 17 00:00:00 2001 From: Amin Latifi Date: Tue, 24 May 2022 20:45:00 +0430 Subject: [PATCH 176/257] Support gnosis GIV/DAI farm Some refactoring of farms configuration --- src/components/cards/BaseStakingCard.tsx | 73 ++++++++++++----------- src/components/cards/Stake.tsx | 3 +- src/components/homeTabs/GIVfarm.tsx | 3 +- src/components/modals/HarvestAll.tsx | 2 +- src/config/development.ts | 38 +++++++++--- src/config/production.ts | 19 ++++-- src/features/subgraph/subgraph.types.ts | 15 +++-- src/helpers/networkProvider.ts | 2 + src/hooks/useLiquidityPositions.tsx | 2 +- src/hooks/useStakingNFT.tsx | 2 +- src/lib/contracts.ts | 2 +- src/lib/stakingPool.ts | 18 ++++-- src/lib/subgraph/subgraphDataTransform.ts | 28 ++++++--- src/lib/subgraph/subgraphQueryBuilder.ts | 12 ++-- src/types/config.ts | 23 +++++-- src/types/subgraph.ts | 8 +++ 16 files changed, 165 insertions(+), 85 deletions(-) diff --git a/src/components/cards/BaseStakingCard.tsx b/src/components/cards/BaseStakingCard.tsx index 1347c09b6c..2f24bf7e92 100644 --- a/src/components/cards/BaseStakingCard.tsx +++ b/src/components/cards/BaseStakingCard.tsx @@ -1,10 +1,10 @@ import Image from 'next/image'; -import React, { FC, useEffect, useState, ReactNode, useMemo } from 'react'; +import React, { FC, ReactNode, useEffect, useMemo, useState } from 'react'; import { - IconSpark, brandColors, - IconHelp, IconExternalLink, + IconHelp, + IconSpark, } from '@giveth/ui-design-system'; import { constants } from 'ethers'; import BigNumber from 'bignumber.js'; @@ -13,39 +13,40 @@ import config from '../../configuration'; import { PoolStakingConfig, RegenPoolStakingConfig, + StakingPlatform, StakingType, } from '@/types/config'; import { IconWithTooltip } from '../IconWithToolTip'; import { BN, formatEthHelper, formatWeiHelper } from '@/helpers/number'; import { - StakingPoolContainer, - StakingPoolExchangeRow, - SPTitle, - StakingPoolLabel, - StakingPoolSubtitle, - Details, - FirstDetail, + ClaimButton, Detail, DetailLabel, - DetailValue, - ClaimButton, - StakeButton, - StakingPoolExchange, - StakePoolInfoContainer, + Details, DetailUnit, - StakeButtonsRow, - StakeContainer, - StakeAmount, - LiquidityButton, - IconContainer, - IconHelpWraper, - GIVgardenTooltip, - IntroIcon, + DetailValue, DisableModal, - DisableModalContent, - DisableModalText, DisableModalCloseButton, + DisableModalContent, DisableModalImage, + DisableModalText, + FirstDetail, + GIVgardenTooltip, + IconContainer, + IconHelpWraper, + IntroIcon, + LiquidityButton, + SPTitle, + StakeAmount, + StakeButton, + StakeButtonsRow, + StakeContainer, + StakePoolInfoContainer, + StakingPoolContainer, + StakingPoolExchange, + StakingPoolExchangeRow, + StakingPoolLabel, + StakingPoolSubtitle, } from './BaseStakingCard.sc'; import { APRModal } from '../modals/APR'; import { StakeModal } from '../modals/Stake'; @@ -76,18 +77,17 @@ export enum StakeCardState { INTRO, } -export const getPoolIconWithName = (pool: string) => { - switch (pool) { - case StakingType.BALANCER: +export const getPoolIconWithName = (platform: StakingPlatform) => { + switch (platform) { + case StakingPlatform.BALANCER: return ; - case StakingType.GIV_LM: + case StakingPlatform.GIVETH: return ; - case StakingType.HONEYSWAP: + case StakingPlatform.HONEYSWAP: return ; - case StakingType.UNISWAPV2: - case StakingType.UNISWAPV3: + case StakingPlatform.UNISWAP: return ; - case StakingType.SUSHISWAP: + case StakingPlatform.SUSHISWAP: return ; default: break; @@ -134,6 +134,7 @@ const BaseStakingCard: FC = ({ const { type, + platform, title, description, provideLiquidityLink, @@ -143,7 +144,7 @@ const BaseStakingCard: FC = ({ active, } = poolStakingConfig; - const isInactive = !active || type === StakingType.UNISWAPV3; + const isInactive = !active || type === StakingType.UNISWAPV3_ETH_GIV; const { apr, @@ -236,12 +237,12 @@ const BaseStakingCard: FC = ({ {state === StakeCardState.NORMAL ? ( <> - {getPoolIconWithName(type)} + {getPoolIconWithName(platform)} {type === StakingType.GIV_LM && chainId === config.XDAI_NETWORK_NUMBER && `GIVgarden `} - {type} + {platform} {chainId === config.XDAI_NETWORK_NUMBER && type === StakingType.GIV_LM && ( diff --git a/src/components/cards/Stake.tsx b/src/components/cards/Stake.tsx index 5dd1fec590..02b42b9b05 100644 --- a/src/components/cards/Stake.tsx +++ b/src/components/cards/Stake.tsx @@ -160,7 +160,8 @@ const InvestCard: FC = ({ index }) => { promiseQueue.push(promise); }); config.MAINNET_CONFIG.pools.forEach(poolStakingConfig => { - if (poolStakingConfig.type === StakingType.UNISWAPV3) return; + if (poolStakingConfig.type === StakingType.UNISWAPV3_ETH_GIV) + return; const unipool = mainnetValues[poolStakingConfig.type]; const unipoolHelper = unipool && new UnipoolHelper(unipool); diff --git a/src/components/homeTabs/GIVfarm.tsx b/src/components/homeTabs/GIVfarm.tsx index 97eba2b436..1f9cca1333 100644 --- a/src/components/homeTabs/GIVfarm.tsx +++ b/src/components/homeTabs/GIVfarm.tsx @@ -57,7 +57,8 @@ const renderPools = ( lg={4} key={`staking_pool_card_${network}_${index}`} > - {poolStakingConfig.type === StakingType.UNISWAPV3 ? ( + {poolStakingConfig.type === + StakingType.UNISWAPV3_ETH_GIV ? ( diff --git a/src/components/modals/HarvestAll.tsx b/src/components/modals/HarvestAll.tsx index 92db5cefbf..15a1768387 100644 --- a/src/components/modals/HarvestAll.tsx +++ b/src/components/modals/HarvestAll.tsx @@ -484,7 +484,7 @@ export const HarvestAllModal: FC = ({ {poolStakingConfig.title} {getPoolIconWithName( - poolStakingConfig.type, + poolStakingConfig.platform, )} diff --git a/src/config/development.ts b/src/config/development.ts index 17a35ea023..1d9e8d7290 100644 --- a/src/config/development.ts +++ b/src/config/development.ts @@ -1,6 +1,7 @@ import { EnvConfig, RegenFarmType, + StakingPlatform, StakingType, StreamType, } from '@/types/config'; @@ -31,7 +32,7 @@ const config: EnvConfig = { blockExplorerName: ['Etherscan'], blockExplorerUrls: ['https://kovan.etherscan.io'], subgraphAddress: - 'https://api.thegraph.com/subgraphs/name/giveth/giveth-economy-kovan-staging', + 'https://api.thegraph.com/subgraphs/name/mohammadranjbarz/giv-economy-kovan-deployment-seven', TOKEN_ADDRESS: '0x29434A25abd94AE882aA883eea81585Aaa5b078D', WETH_TOKEN_ADDRESS: '0xd0a1e359811322d97991e03f863a0c30c2cf029c', @@ -48,7 +49,8 @@ const config: EnvConfig = { { POOL_ADDRESS: '0x6D5481911052a42c109F1f56354BEB07Ec430b85', LM_ADDRESS: '0x9e4EcF5fE5F58C888C84338525422A1D0915f6ff', - type: StakingType.UNISWAPV2, + type: StakingType.UNISWAPV2_GIV_DAI, + platform: StakingPlatform.UNISWAP, title: 'GIV / DAI', description: '50% GIV, 50% DAI', provideLiquidityLink: @@ -62,7 +64,8 @@ const config: EnvConfig = { POOL_ID: '0x8a6b25e33b12d1bb6929a8793961076bd1f9d3eb00020000000000000000053f', LM_ADDRESS: '0x4B319c068685aF260c91407B651918307df30061', - type: StakingType.BALANCER, + type: StakingType.BALANCER_ETH_GIV, + platform: StakingPlatform.BALANCER, title: 'GIV / ETH', description: '80% GIV, 20% ETH', provideLiquidityLink: @@ -86,7 +89,8 @@ const config: EnvConfig = { '0x5f672d71399d8cDbA64f596394b4f4381247E025', POOL_ADDRESS: '0xa48C26fF05F47a2eEd88C09664de1cb604A21b01', LM_ADDRESS: '0x1aD46D40648639f84a396Fef32132888038c5aA8', - type: StakingType.UNISWAPV3, + type: StakingType.UNISWAPV3_ETH_GIV, + platform: StakingPlatform.UNISWAP, title: 'GIV / ETH', description: '0.3% tier only', provideLiquidityLink: `https://app.uniswap.org/#/add/ETH/0x29434A25abd94AE882aA883eea81585Aaa5b078D/3000`, @@ -112,7 +116,8 @@ const config: EnvConfig = { { POOL_ADDRESS: '0x6bb32725aa31b1a99e7c782e0605b0fb57e4b9e6', LM_ADDRESS: '0x9d23d449af3e2c07a286688c85ff5d3d4c219d79', - type: StakingType.UNISWAPV2, + type: StakingType.UNISWAPV2_CULT_ETH, + platform: StakingPlatform.UNISWAP, network: 42, title: 'CULT / ETH', description: '50% CULT, 50% ETH', @@ -150,7 +155,7 @@ const config: EnvConfig = { blockExplorerName: ['Blockscout'], blockExplorerUrls: ['https://blockscout.com/xdai/mainnet'], subgraphAddress: - 'https://api.thegraph.com/subgraphs/name/giveth/giveth-economy-xdai-staging', + 'https://api.thegraph.com/subgraphs/name/mohammadranjbarz/giv-economy-xdai-deployment-seven', TOKEN_ADDRESS: '0x83a8eea6427985C523a0c4d9d3E62C051B6580d3', MERKLE_ADDRESS: '0xc87403C70c9FBfb594d98d3B5E695BBE4C694188', @@ -169,7 +174,8 @@ const config: EnvConfig = { { POOL_ADDRESS: '0x31A5AeA76Af79F592a3A3F46a9f6Cb118990433b', LM_ADDRESS: '0xC09147Ac0aC8B5271F03b511c3554e3238Ae3201', - type: StakingType.HONEYSWAP, + type: StakingType.HONEYSWAP_GIV_HNY, + platform: StakingPlatform.HONEYSWAP, title: 'GIV / HNY', description: '50% GIV, 50% HNY', provideLiquidityLink: @@ -180,7 +186,8 @@ const config: EnvConfig = { { POOL_ADDRESS: '0x437B0da7932b21F54488fD80Ee09b519a6f4d8AD', LM_ADDRESS: '0x83535D6DeF8E881E647C00462315bae9A6E7BD09', - type: StakingType.SUSHISWAP, + type: StakingType.SUSHISWAP_ETH_GIV, + platform: StakingPlatform.SUSHISWAP, title: 'GIV / ETH', description: '50% ETH, 50% GIV', provideLiquidityLink: @@ -188,6 +195,18 @@ const config: EnvConfig = { unit: 'LP', active: true, }, + { + POOL_ADDRESS: '0xB4E0fc187f0EEd740D93eF15Cd14750a2780fc2A', + LM_ADDRESS: '0xe2c436E177C39A5D18AF6923Fc2Fc673f4729C05', + type: StakingType.HONEYSWAP_GIV_DAI, + platform: StakingPlatform.HONEYSWAP, + title: 'GIV / DAI', + description: '50% GIV, 50% DAI', + provideLiquidityLink: + 'https://app.honeyswap.org/#/add/0x83a8eea6427985C523a0c4d9d3E62C051B6580d3/0x97c4dD5cE204b8c1F2f3B8fBfBBDC771d867d18c', + unit: 'LP', + active: true, + }, ], uniswapV2Subgraph: @@ -210,7 +229,8 @@ const config: EnvConfig = { { POOL_ADDRESS: '0xD28C07F802212F04AF41834ec0CC81d2d283124B', LM_ADDRESS: '0x06851400866e065972ff21e1ECdE035b4772736d', - type: StakingType.HONEYSWAP, + type: StakingType.HONEYSWAP_FOX_HNY, + platform: StakingPlatform.HONEYSWAP, network: 100, title: 'FOX / HNY', description: '50% FOX, 50% HNY', diff --git a/src/config/production.ts b/src/config/production.ts index 411d9b68b5..258813a442 100644 --- a/src/config/production.ts +++ b/src/config/production.ts @@ -1,6 +1,7 @@ import { EnvConfig, RegenFarmType, + StakingPlatform, StakingType, StreamType, } from '@/types/config'; @@ -48,7 +49,8 @@ const config: EnvConfig = { { POOL_ADDRESS: '0xbeba1666c62c65e58770376de332891b09461eeb', LM_ADDRESS: '0xa4523D703F663615Bd41606B46B58dEb2F926D98', - type: StakingType.UNISWAPV2, + type: StakingType.UNISWAPV2_GIV_DAI, + platform: StakingPlatform.UNISWAP, title: 'GIV / DAI', description: '50% GIV, 50% DAI', provideLiquidityLink: @@ -63,7 +65,8 @@ const config: EnvConfig = { POOL_ID: '0x7819f1532c49388106f7762328c51ee70edd134c000200000000000000000109', LM_ADDRESS: '0xc0dbDcA66a0636236fAbe1B3C16B1bD4C84bB1E1', - type: StakingType.BALANCER, + type: StakingType.BALANCER_ETH_GIV, + platform: StakingPlatform.BALANCER, title: 'GIV / ETH', description: '80% GIV, 20% ETH', provideLiquidityLink: @@ -87,7 +90,8 @@ const config: EnvConfig = { '0x34d27210cC319EC5281bDc4DC2ad8FbcF4EAEAEB', POOL_ADDRESS: '', //it's used in uniswap v2 LM_ADDRESS: '', //it's used in uniswap v2 - type: StakingType.UNISWAPV3, + type: StakingType.UNISWAPV3_ETH_GIV, + platform: StakingPlatform.UNISWAP, title: 'GIV / ETH', description: '0.3% tier only', provideLiquidityLink: `https://app.uniswap.org/#/add/ETH/0x900dB999074d9277c5DA2A43F252D74366230DA0/3000`, @@ -135,7 +139,8 @@ const config: EnvConfig = { { POOL_ADDRESS: '0x08ea9f608656A4a775EF73f5B187a2F1AE2ae10e', LM_ADDRESS: '0x4B9EfAE862a1755F7CEcb021856D467E86976755', - type: StakingType.HONEYSWAP, + type: StakingType.HONEYSWAP_GIV_HNY, + platform: StakingPlatform.HONEYSWAP, title: 'GIV / HNY', description: '50% GIV, 50% HNY', provideLiquidityLink: @@ -146,7 +151,8 @@ const config: EnvConfig = { { POOL_ADDRESS: '0x55FF0cef43F0DF88226E9D87D09fA036017F5586', LM_ADDRESS: '0xfB429010C1e9D08B7347F968a7d88f0207807EF0', - type: StakingType.SUSHISWAP, + type: StakingType.SUSHISWAP_ETH_GIV, + platform: StakingPlatform.SUSHISWAP, title: 'GIV / ETH', description: '50% ETH, 50% GIV', provideLiquidityLink: @@ -176,7 +182,8 @@ const config: EnvConfig = { { POOL_ADDRESS: '0x8a0bee989c591142414ad67fb604539d917889df', LM_ADDRESS: '0x502EC7a040F486EE6Cb7d634D94764874B29dE68', - type: StakingType.HONEYSWAP, + type: StakingType.HONEYSWAP_FOX_HNY, + platform: StakingPlatform.HONEYSWAP, title: 'FOX / HNY', description: '50% FOX, 50% HNY', provideLiquidityLink: diff --git a/src/features/subgraph/subgraph.types.ts b/src/features/subgraph/subgraph.types.ts index 9ff11c4455..fcc974547c 100644 --- a/src/features/subgraph/subgraph.types.ts +++ b/src/features/subgraph/subgraph.types.ts @@ -14,17 +14,22 @@ export interface ISubgraphState { tokenDistroInfo?: ITokenDistroInfo; uniswapV3Pool?: IUniswapV3Pool; [StakingType.GIV_LM]?: IUnipool; - [StakingType.BALANCER]?: IUnipool; - [StakingType.SUSHISWAP]?: IUnipool; - [StakingType.HONEYSWAP]?: IUnipool; - [StakingType.UNISWAPV2]?: IUnipool; - [StakingType.UNISWAPV3]?: IUnipool; + [StakingType.BALANCER_ETH_GIV]?: IUnipool; + [StakingType.SUSHISWAP_ETH_GIV]?: IUnipool; + [StakingType.HONEYSWAP_GIV_HNY]?: IUnipool; + [StakingType.HONEYSWAP_GIV_DAI]?: IUnipool; + [StakingType.UNISWAPV2_GIV_DAI]?: IUnipool; + [StakingType.UNISWAPV3_ETH_GIV]?: IUnipool; + [StakingType.HONEYSWAP_FOX_HNY]?: IUnipool; + [StakingType.UNISWAPV2_CULT_ETH]?: IUnipool; + userNotStakedPositions: IUniswapV3Position[]; userStakedPositions: IUniswapV3Position[]; allPositions: IUniswapV3Position[]; uniswapV2EthGivPair?: IUniswapV2Pair; infinitePositionReward?: IInfinitePositionReward; infinitePosition?: IUniswapV3Position; + [StreamType.FOX]?: ITokenDistroInfo; [StreamType.CULT]?: ITokenDistroInfo; [RegenFarmType.FOX_HNY]?: IUnipool; diff --git a/src/helpers/networkProvider.ts b/src/helpers/networkProvider.ts index 9c1e9668da..0fe77e3755 100644 --- a/src/helpers/networkProvider.ts +++ b/src/helpers/networkProvider.ts @@ -2,6 +2,7 @@ import { JsonRpcProvider } from '@ethersproject/providers'; import { BasicNetworkConfig, SimplePoolStakingConfig, + StakingPlatform, StakingType, } from '@/types/config'; import config from '../configuration'; @@ -29,6 +30,7 @@ export const getGivStakingConfig = ( ...networkConfig.GIV, POOL_ADDRESS: networkConfig.TOKEN_ADDRESS, type: StakingType.GIV_LM, + platform: StakingPlatform.GIVETH, title: 'GIV', description: '100% GIV', unit: 'GIV', diff --git a/src/hooks/useLiquidityPositions.tsx b/src/hooks/useLiquidityPositions.tsx index e2af549e60..320ba27d0a 100644 --- a/src/hooks/useLiquidityPositions.tsx +++ b/src/hooks/useLiquidityPositions.tsx @@ -46,7 +46,7 @@ export const useLiquidityPositions = () => { const mainnetConfig = config.MAINNET_CONFIG; const uniswapConfig = mainnetConfig.pools.find( - c => c.type === StakingType.UNISWAPV3, + c => c.type === StakingType.UNISWAPV3_ETH_GIV, ) as UniswapV3PoolStakingConfig; const rewardToken = uniswapConfig.REWARD_TOKEN; const poolAddress = uniswapConfig.UNISWAP_V3_LP_POOL; diff --git a/src/hooks/useStakingNFT.tsx b/src/hooks/useStakingNFT.tsx index 6f755bf3cc..689a36c47a 100644 --- a/src/hooks/useStakingNFT.tsx +++ b/src/hooks/useStakingNFT.tsx @@ -17,7 +17,7 @@ export const useStakingNFT = (stakedPositions: LiquidityPosition[]) => { const mainnetConfig = config.MAINNET_CONFIG; const uniswapV3Config = mainnetConfig.pools.find( - c => c.type === StakingType.UNISWAPV3, + c => c.type === StakingType.UNISWAPV3_ETH_GIV, ) as UniswapV3PoolStakingConfig; const rewardToken = uniswapV3Config.REWARD_TOKEN; const poolAddress = uniswapV3Config.UNISWAP_V3_LP_POOL; diff --git a/src/lib/contracts.ts b/src/lib/contracts.ts index 3d0b12adcd..36bc25f67f 100644 --- a/src/lib/contracts.ts +++ b/src/lib/contracts.ts @@ -13,7 +13,7 @@ const { abi: NonfungiblePositionManagerABI } = NonfungiblePositionManagerJson; const mainnetConfig = config.MAINNET_CONFIG; const uniswapV3Config = mainnetConfig.pools.find( - c => c.type === StakingType.UNISWAPV3, + c => c.type === StakingType.UNISWAPV3_ETH_GIV, ) as UniswapV3PoolStakingConfig; const { NFT_POSITIONS_MANAGER_ADDRESS, UNISWAP_V3_STAKER, UNISWAP_V3_LP_POOL } = diff --git a/src/lib/stakingPool.ts b/src/lib/stakingPool.ts index 0e58d56f5c..6b66e80afc 100644 --- a/src/lib/stakingPool.ts +++ b/src/lib/stakingPool.ts @@ -66,7 +66,7 @@ export const getLPStakingAPR = async ( if (!provider) { return Zero; } - if (poolStakingConfig.type === StakingType.BALANCER) { + if (poolStakingConfig.type === StakingType.BALANCER_ETH_GIV) { return getBalancerPoolStakingAPR( poolStakingConfig as BalancerPoolStakingConfig, network, @@ -273,25 +273,33 @@ export const getUserStakeInfo = ( } } else { switch (type) { - case StakingType.SUSHISWAP: + case StakingType.SUSHISWAP_ETH_GIV: rewards = BN(balance.rewardsSushiSwap); rewardPerTokenPaid = BN(balance.rewardPerTokenPaidSushiSwap); stakedAmount = BN(balance.sushiSwapLpStaked); notStakedAmount = BN(balance.sushiswapLp); break; - case StakingType.HONEYSWAP: + case StakingType.HONEYSWAP_GIV_HNY: rewards = BN(balance.rewardsHoneyswap); rewardPerTokenPaid = BN(balance.rewardPerTokenPaidHoneyswap); stakedAmount = BN(balance.honeyswapLpStaked); notStakedAmount = BN(balance.honeyswapLp); break; - case StakingType.BALANCER: + case StakingType.HONEYSWAP_GIV_DAI: + rewards = BN(balance.rewardsHoneyswapGivDai); + rewardPerTokenPaid = BN( + balance.rewardPerTokenPaidHoneyswapGivDai, + ); + stakedAmount = BN(balance.honeyswapGivDaiLpStaked); + notStakedAmount = BN(balance.honeyswapGivDaiLp); + break; + case StakingType.BALANCER_ETH_GIV: rewards = BN(balance.rewardsBalancer); rewardPerTokenPaid = BN(balance.rewardPerTokenPaidBalancer); stakedAmount = BN(balance.balancerLpStaked); notStakedAmount = BN(balance.balancerLp); break; - case StakingType.UNISWAPV2: + case StakingType.UNISWAPV2_GIV_DAI: rewards = BN(balance.rewardsUniswapV2GivDai); rewardPerTokenPaid = BN( balance.rewardPerTokenPaidUniswapV2GivDai, diff --git a/src/lib/subgraph/subgraphDataTransform.ts b/src/lib/subgraph/subgraphDataTransform.ts index a9626fc701..be798a210a 100644 --- a/src/lib/subgraph/subgraphDataTransform.ts +++ b/src/lib/subgraph/subgraphDataTransform.ts @@ -24,6 +24,9 @@ const transformBalanceInfo = (info: any): IBalances => { const rewardsSushiSwap = info.rewardsSushiSwap || 0; const rewardPerTokenPaidHoneyswap = info.rewardPerTokenPaidHoneyswap || 0; const rewardsHoneyswap = info.rewardsHoneyswap || 0; + const rewardPerTokenPaidHoneyswapGivDai = + info.rewardPerTokenPaidHoneyswapGivDai || 0; + const rewardsHoneyswapGivDai = info.rewardsHoneyswapGivDai || 0; const rewardPerTokenPaidBalancer = info.rewardPerTokenPaidBalancer || 0; const rewardsBalancer = info.rewardsBalancer || 0; const rewardPerTokenPaidUniswapV2GivDai = @@ -39,6 +42,8 @@ const transformBalanceInfo = (info: any): IBalances => { const sushiSwapLpStaked = info.sushiSwapLpStaked || 0; const honeyswapLp = info.honeyswapLp || 0; const honeyswapLpStaked = info.honeyswapLpStaked || 0; + const honeyswapGivDaiLp = info.honeyswapGivDaiLp || 0; + const honeyswapGivDaiLpStaked = info.honeyswapGivDaiLpStaked || 0; const givStaked = info.givStaked || 0; const allocationCount = Number(info.allocationCount || 0); const givDropClaimed = Boolean(info.givDropClaimed); @@ -67,6 +72,8 @@ const transformBalanceInfo = (info: any): IBalances => { rewardsSushiSwap, rewardPerTokenPaidHoneyswap, rewardsHoneyswap, + rewardPerTokenPaidHoneyswapGivDai, + rewardsHoneyswapGivDai, rewardPerTokenPaidBalancer, rewardsBalancer, rewardPerTokenPaidUniswapV2GivDai, @@ -81,6 +88,8 @@ const transformBalanceInfo = (info: any): IBalances => { sushiSwapLpStaked, honeyswapLp, honeyswapLpStaked, + honeyswapGivDaiLp, + honeyswapGivDaiLpStaked, givStaked, allocationCount, givDropClaimed, @@ -247,17 +256,20 @@ export const transformSubgraphData = (data: any = {}): ISubgraphState => { [StreamType.CULT]: transformTokenDistroInfo(data[StreamType.CULT]), [StakingType.GIV_LM]: transformUnipoolInfo(data[StakingType.GIV_LM]), - [StakingType.BALANCER]: transformUnipoolInfo( - data[StakingType.BALANCER], + [StakingType.BALANCER_ETH_GIV]: transformUnipoolInfo( + data[StakingType.BALANCER_ETH_GIV], ), - [StakingType.UNISWAPV2]: transformUnipoolInfo( - data[StakingType.UNISWAPV2], + [StakingType.UNISWAPV2_GIV_DAI]: transformUnipoolInfo( + data[StakingType.UNISWAPV2_GIV_DAI], ), - [StakingType.HONEYSWAP]: transformUnipoolInfo( - data[StakingType.HONEYSWAP], + [StakingType.HONEYSWAP_GIV_HNY]: transformUnipoolInfo( + data[StakingType.HONEYSWAP_GIV_HNY], ), - [StakingType.SUSHISWAP]: transformUnipoolInfo( - data[StakingType.SUSHISWAP], + [StakingType.HONEYSWAP_GIV_DAI]: transformUnipoolInfo( + data[StakingType.HONEYSWAP_GIV_DAI], + ), + [StakingType.SUSHISWAP_ETH_GIV]: transformUnipoolInfo( + data[StakingType.SUSHISWAP_ETH_GIV], ), [RegenFarmType.FOX_HNY]: transformUnipoolInfo( data[RegenFarmType.FOX_HNY], diff --git a/src/lib/subgraph/subgraphQueryBuilder.ts b/src/lib/subgraph/subgraphQueryBuilder.ts index 115144f534..bb868879c0 100644 --- a/src/lib/subgraph/subgraphQueryBuilder.ts +++ b/src/lib/subgraph/subgraphQueryBuilder.ts @@ -10,7 +10,7 @@ import { getGivStakingConfig } from '@/helpers/networkProvider'; import config from '@/configuration'; const uniswapConfig = config.MAINNET_CONFIG.pools.find( - p => p.type === StakingType.UNISWAPV3, + p => p.type === StakingType.UNISWAPV3_ETH_GIV, ) as UniswapV3PoolStakingConfig; export class SubgraphQueryBuilder { @@ -25,6 +25,8 @@ export class SubgraphQueryBuilder { rewardsSushiSwap rewardPerTokenPaidHoneyswap rewardsHoneyswap + rewardPerTokenPaidHoneyswapGivDai + rewardsHoneyswapGivDai rewardPerTokenPaidBalancer rewardsBalancer rewardPerTokenPaidUniswapV2GivDai @@ -39,6 +41,8 @@ export class SubgraphQueryBuilder { sushiSwapLpStaked honeyswapLp honeyswapLpStaked + honeyswapGivDaiLp + honeyswapGivDaiLpStaked givStaked allocationCount givDropClaimed @@ -198,7 +202,7 @@ export class SubgraphQueryBuilder { static getMainnetQuery = (address: string): string => { const uniswapConfig = config.MAINNET_CONFIG.pools.find( - c => c.type === StakingType.UNISWAPV3, + c => c.type === StakingType.UNISWAPV3_ETH_GIV, ) as UniswapV3PoolStakingConfig; return ` @@ -208,7 +212,7 @@ export class SubgraphQueryBuilder { ${SubgraphQueryBuilder.generateUnipoolInfoQueries([ getGivStakingConfig(config.MAINNET_CONFIG), ...config.MAINNET_CONFIG.pools.filter( - c => c.type !== StakingType.UNISWAPV3, + c => c.type !== StakingType.UNISWAPV3_ETH_GIV, ), ...config.MAINNET_CONFIG.regenFarms, ...config.XDAI_CONFIG.regenFarms, @@ -234,7 +238,7 @@ export class SubgraphQueryBuilder { uniswapV2EthGivPair: ${SubgraphQueryBuilder.getPairInfoQuery( config.XDAI_CONFIG.pools.find( - c => c.type === StakingType.SUSHISWAP, + c => c.type === StakingType.SUSHISWAP_ETH_GIV, )?.POOL_ADDRESS || '', )} } diff --git a/src/types/config.ts b/src/types/config.ts index 6be5f4f2ff..4c5a264f23 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -4,14 +4,24 @@ export interface BasicStakingConfig { BUY_LINK?: string; farmStartTimeMS?: number; } - -export enum StakingType { - UNISWAPV2 = 'UniswapV2', - UNISWAPV3 = 'UniswapV3', +export enum StakingPlatform { + GIVETH = 'Staking', + UNISWAP = 'Uniswap', BALANCER = 'Balancer', - SUSHISWAP = 'Sushiswap', HONEYSWAP = 'Honeyswap', - GIV_LM = 'Staking', + SUSHISWAP = 'Sushiswap', +} +export enum StakingType { + UNISWAPV2_GIV_DAI = 'UniswapV2_GIV_DAI', + UNISWAPV3_ETH_GIV = 'UniswapV3', // ETH-GIV + BALANCER_ETH_GIV = 'Balancer', // ETH-GIV + SUSHISWAP_ETH_GIV = 'Sushiswap', // ETH-GIV + HONEYSWAP_GIV_HNY = 'Honeyswap_GIV_HNY', + HONEYSWAP_GIV_DAI = 'Honeyswap_GIV_DAI', + GIV_LM = 'GIV_LM', + + HONEYSWAP_FOX_HNY = 'Honeyswap_FOX_HNY', + UNISWAPV2_CULT_ETH = 'UniswapV2_CULT_ETH', } export enum RegenFarmType { @@ -33,6 +43,7 @@ export type PoolStakingConfig = export interface SimplePoolStakingConfig extends BasicStakingConfig { POOL_ADDRESS: string; type: StakingType; + platform: StakingPlatform; title: string; description?: string; provideLiquidityLink?: string; diff --git a/src/types/subgraph.ts b/src/types/subgraph.ts index 5b86b4f3ec..9069c19b64 100644 --- a/src/types/subgraph.ts +++ b/src/types/subgraph.ts @@ -8,6 +8,8 @@ export interface IBalances { rewardsSushiSwap: string; rewardPerTokenPaidHoneyswap: string; rewardsHoneyswap: string; + rewardPerTokenPaidHoneyswapGivDai: string; + rewardsHoneyswapGivDai: string; rewardPerTokenPaidBalancer: string; rewardsBalancer: string; rewardPerTokenPaidUniswapV2GivDai: string; @@ -22,6 +24,8 @@ export interface IBalances { sushiSwapLpStaked: string; honeyswapLp: string; honeyswapLpStaked: string; + honeyswapGivDaiLp: string; + honeyswapGivDaiLpStaked: string; givStaked: string; allocationCount: number; givDropClaimed: boolean; @@ -50,6 +54,8 @@ export const ZeroBalances: IBalances = { rewardsSushiSwap: '0', rewardPerTokenPaidHoneyswap: '0', rewardsHoneyswap: '0', + rewardPerTokenPaidHoneyswapGivDai: '0', + rewardsHoneyswapGivDai: '0', rewardPerTokenPaidBalancer: '0', rewardsBalancer: '0', rewardPerTokenPaidUniswapV2GivDai: '0', @@ -64,6 +70,8 @@ export const ZeroBalances: IBalances = { sushiSwapLpStaked: '0', honeyswapLp: '0', honeyswapLpStaked: '0', + honeyswapGivDaiLp: '0', + honeyswapGivDaiLpStaked: '0', givStaked: '0', allocationCount: 0, givDropClaimed: false, From f6d2f250ffc3ff78d51773a8dd5990c0386589e5 Mon Sep 17 00:00:00 2001 From: Cherik Date: Tue, 24 May 2022 21:36:19 +0430 Subject: [PATCH 177/257] fix active and uniswapv3 misusage --- src/components/cards/BaseStakingCard.tsx | 45 ++++++++++++------------ src/components/cards/Stake.tsx | 4 +-- 2 files changed, 23 insertions(+), 26 deletions(-) diff --git a/src/components/cards/BaseStakingCard.tsx b/src/components/cards/BaseStakingCard.tsx index 2f24bf7e92..6097c84109 100644 --- a/src/components/cards/BaseStakingCard.tsx +++ b/src/components/cards/BaseStakingCard.tsx @@ -144,8 +144,6 @@ const BaseStakingCard: FC = ({ active, } = poolStakingConfig; - const isInactive = !active || type === StakingType.UNISWAPV3_ETH_GIV; - const { apr, earned, @@ -201,12 +199,10 @@ const BaseStakingCard: FC = ({ setStarted(farmStartTimeMS ? getNowUnixMS() > farmStartTimeMS : true); }, [farmStartTimeMS]); - // if(isInactive) return null - return ( <> - {isInactive && disableModal && ( + {!active && disableModal && ( @@ -291,9 +287,7 @@ const BaseStakingCard: FC = ({ APR - {isInactive ? ( -
N/A %
- ) : ( + {active ? ( <> = ({ + ) : ( +
N/A %
)}
Claimable - {isInactive ? ( -
N/A
- ) : ( + {active ? ( `${formatWeiHelper( rewardLiquidPart, )} ${rewardTokenSymbol}` + ) : ( +
N/A
)}
@@ -350,12 +346,12 @@ const BaseStakingCard: FC = ({ - {isInactive ? ( -
N/A
- ) : ( + {active ? ( formatWeiHelper( rewardStream, ) + ) : ( +
N/A
)}
@@ -371,7 +367,7 @@ const BaseStakingCard: FC = ({ /> )} setShowHarvestModal(true)} label='HARVEST REWARDS' buttonType='primary' @@ -382,13 +378,13 @@ const BaseStakingCard: FC = ({ label='STAKE' size='small' disabled={ - BN(userNotStakedAmount).isZero() || - isInactive + !active || + BN(userNotStakedAmount).isZero() } onClick={() => setShowStakeModal(true)} /> - {isInactive + {type === StakingType.UNISWAPV3_ETH_GIV ? `${userNotStakedAmount.toNumber()} ${unit}` : `${formatWeiHelper( userNotStakedAmount, @@ -405,7 +401,7 @@ const BaseStakingCard: FC = ({ } /> - {isInactive + {type === StakingType.UNISWAPV3_ETH_GIV ? `${stakedLpAmount.toNumber()} ${unit}` : `${formatWeiHelper( stakedLpAmount, @@ -413,7 +409,7 @@ const BaseStakingCard: FC = ({ - {!isInactive && ( + {active && ( = ({ : 'PROVIDE LIQUIDITY' } onClick={() => { - if (isInactive) { + if ( + type === + StakingType.UNISWAPV3_ETH_GIV + ) { setShowUniV3APRModal(true); } else { window.open( @@ -465,7 +464,7 @@ const BaseStakingCard: FC = ({ /> )} {showStakeModal && - (isInactive ? ( + (type === StakingType.UNISWAPV3_ETH_GIV ? ( = ({ /> ))} {showUnStakeModal && - (isInactive ? ( + (type === StakingType.UNISWAPV3_ETH_GIV ? ( = ({ index }) => { promiseQueue.push(promise); }); config.MAINNET_CONFIG.pools.forEach(poolStakingConfig => { - if (poolStakingConfig.type === StakingType.UNISWAPV3_ETH_GIV) - return; + if (poolStakingConfig.active === false) return; const unipool = mainnetValues[poolStakingConfig.type]; const unipoolHelper = unipool && new UnipoolHelper(unipool); From f379a6bb5c13c015e7306bbb3c2317aaefb8dc34 Mon Sep 17 00:00:00 2001 From: Cherik Date: Tue, 24 May 2022 21:37:20 +0430 Subject: [PATCH 178/257] fix AmountInput unit --- src/components/AmountInput.tsx | 28 ++++++++++------------------ 1 file changed, 10 insertions(+), 18 deletions(-) diff --git a/src/components/AmountInput.tsx b/src/components/AmountInput.tsx index 30c2d1c365..874c421c87 100644 --- a/src/components/AmountInput.tsx +++ b/src/components/AmountInput.tsx @@ -4,7 +4,7 @@ import { FC, useState, useCallback, Dispatch, SetStateAction } from 'react'; import styled from 'styled-components'; import { captureException } from '@sentry/nextjs'; import { formatWeiHelper } from '@/helpers/number'; -import { PoolStakingConfig } from '@/types/config'; +import { PoolStakingConfig, StakingPlatform } from '@/types/config'; import { Flex } from './styled-components/Flex'; import { NumericalInput } from '@/components/input/index'; @@ -60,23 +60,15 @@ export const AmountInput: FC = ({ Available: - {poolStakingConfig.type === 'Staking' ? ( - -   - {formatWeiHelper(maxAmount)} -   - {poolStakingConfig.title} -   - - ) : ( - -   - {formatWeiHelper(maxAmount)} -   - {poolStakingConfig.title} -  LP - - )} + +   + {formatWeiHelper(maxAmount)} +   + {poolStakingConfig.title} +   + {poolStakingConfig.platform !== + StakingPlatform.GIVETH && 'LP'} + { From 03fa89d68eb569c6437eb51e45b6d8b106382717 Mon Sep 17 00:00:00 2001 From: Mateo Daza Date: Tue, 24 May 2022 18:07:25 -0500 Subject: [PATCH 179/257] moves logout and get token to user thunk --- src/components/menu/MenuWallet.tsx | 8 ++------ src/features/user/user.slice.ts | 15 +++++++-------- src/features/user/user.thunks.ts | 24 ++++++++++++++++++++++-- src/services/token.ts | 22 ---------------------- 4 files changed, 31 insertions(+), 38 deletions(-) diff --git a/src/components/menu/MenuWallet.tsx b/src/components/menu/MenuWallet.tsx index dac691755c..ab44f45ad0 100644 --- a/src/components/menu/MenuWallet.tsx +++ b/src/components/menu/MenuWallet.tsx @@ -26,8 +26,7 @@ import { setShowCompleteProfile, setShowWalletModal, } from '@/features/modal/modal.sclie'; -import { logoutToken } from '@/services/token'; -import { signOut } from '@/features/user/user.slice'; +import { signOut } from '@/features/user/user.thunks'; const MenuWallet = () => { const [isMounted, setIsMounted] = useState(false); @@ -138,10 +137,7 @@ const MenuWallet = () => { ))} {isSignedIn && ( { - await logoutToken(token!); - dispatch(signOut()); - }} + onClick={() => dispatch(signOut(token!))} theme={theme} > Sign out diff --git a/src/features/user/user.slice.ts b/src/features/user/user.slice.ts index 65af64e225..dc295782bb 100644 --- a/src/features/user/user.slice.ts +++ b/src/features/user/user.slice.ts @@ -1,6 +1,6 @@ import { createSlice, PayloadAction } from '@reduxjs/toolkit'; import { IUser } from '@/apollo/types/types'; -import { fetchUserByAddress, signToGetToken } from './user.thunks'; +import { fetchUserByAddress, signToGetToken, signOut } from './user.thunks'; import StorageLabel from '@/lib/localStorage'; import { compareAddresses } from '@/lib/helpers'; @@ -34,12 +34,6 @@ export const userSlice = createSlice({ setBalance: (state, action: PayloadAction) => { state.balance = action.payload; }, - signOut: state => { - localStorage.removeItem(StorageLabel.USER); - localStorage.removeItem(StorageLabel.TOKEN); - state.token = undefined; - state.isSignedIn = false; - }, incrementLikedProjectsCount: state => { if (state.userData) { state.userData.likedProjectsCount = @@ -91,6 +85,12 @@ export const userSlice = createSlice({ ); localStorage.setItem(StorageLabel.TOKEN, action.payload); state.isSignedIn = true; + }) + .addCase(signOut.fulfilled, state => { + localStorage.removeItem(StorageLabel.USER); + localStorage.removeItem(StorageLabel.TOKEN); + state.token = undefined; + state.isSignedIn = false; }); }, }); @@ -99,7 +99,6 @@ export const { setIsSignedIn, setToken, setBalance, - signOut, incrementLikedProjectsCount, decrementLikedProjectsCount, } = userSlice.actions; diff --git a/src/features/user/user.thunks.ts b/src/features/user/user.thunks.ts index d605b510e8..d1a5ae27b6 100644 --- a/src/features/user/user.thunks.ts +++ b/src/features/user/user.thunks.ts @@ -3,8 +3,9 @@ import { gqlRequest } from '@/helpers/requests'; import { GET_USER_BY_ADDRESS } from './user.queries'; import { ISignToGetToken } from './user.types'; import { createSiweMessage } from '@/lib/helpers'; -import { getToken } from '@/services/token'; import { RootState } from '../store'; +import { postRequest } from '@/helpers/requests'; +import config from '@/configuration'; export const fetchUserByAddress = createAsyncThunk( 'user/fetchUser', @@ -34,7 +35,14 @@ export const signToGetToken = createAsyncThunk( if (!state.user.userData) { await dispatch(fetchUserByAddress(address)); } - const token = await getToken(signature, message, nonce); + const token = await postRequest( + `${config.MICROSERVICES.authentication}/authentication`, + { + signature, + message, + nonce, + }, + ); return token.jwt; } else { return Promise.reject('Signing failed'); @@ -45,3 +53,15 @@ export const signToGetToken = createAsyncThunk( } }, ); + +export const signOut = createAsyncThunk( + 'user/signOut', + async (token: string) => { + return await postRequest( + `${config.MICROSERVICES.authentication}/logout`, + { + jwt: token, + }, + ); + }, +); diff --git a/src/services/token.ts b/src/services/token.ts index f22d1e78a9..bf87de4df3 100644 --- a/src/services/token.ts +++ b/src/services/token.ts @@ -6,7 +6,6 @@ import { initializeApollo } from '@/apollo/apolloClient'; import { LOGIN_USER } from '@/apollo/gql/gqlAuth'; import { showToastError } from '@/lib/helpers'; import config from '@/configuration'; -import { postRequest } from '@/helpers/requests'; const apolloClient = initializeApollo(); @@ -45,27 +44,6 @@ export async function __oldWay_getToken( } } -export async function getToken( - signature: string, - message: string, - nonce: string, -) { - return await postRequest( - `${config.MICROSERVICES.authentication}/authentication`, - { - signature, - message, - nonce, - }, - ); -} - -export async function logoutToken(jwt: string) { - return await postRequest(`${config.MICROSERVICES.authentication}/logout`, { - jwt, - }); -} - export const fetchPrice = async ( chainId: number, tokenAddress: string | undefined, From 970888a5694f9407932c31009ae09f33ba00b087 Mon Sep 17 00:00:00 2001 From: Cherik Date: Wed, 25 May 2022 11:52:40 +0430 Subject: [PATCH 180/257] fix givback double calc --- src/components/modals/HarvestAll.tsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/components/modals/HarvestAll.tsx b/src/components/modals/HarvestAll.tsx index 15a1768387..114952e8ee 100644 --- a/src/components/modals/HarvestAll.tsx +++ b/src/components/modals/HarvestAll.tsx @@ -173,13 +173,13 @@ export const HarvestAllModal: FC = ({ //calculate Liquid Sum useEffect(() => { - setSumLiquid(rewardLiquidPart.add(givbackLiquidPart).add(earnedLiquid)); - }, [rewardLiquidPart, givbackLiquidPart, earnedLiquid]); + setSumLiquid(rewardLiquidPart.add(earnedLiquid)); // earnedLiquid includes the givback liquid part + }, [rewardLiquidPart, earnedLiquid]); //calculate Stream Sum useEffect(() => { - setSumStream(BigNumber.sum(rewardStream, givBackStream, earnedStream)); - }, [rewardStream, givBackStream, earnedStream]); + setSumStream(BigNumber.sum(rewardStream, earnedStream)); // earnedLiquid includes the givback stream part + }, [rewardStream, earnedStream]); useEffect(() => { if (!tokenDistroHelper) return; From c3626d5a9989b060c22b38ef9d2fc2c0a1ec2a98 Mon Sep 17 00:00:00 2001 From: Cherik Date: Wed, 25 May 2022 11:54:12 +0430 Subject: [PATCH 181/257] fix typo in comments --- src/components/modals/HarvestAll.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/modals/HarvestAll.tsx b/src/components/modals/HarvestAll.tsx index 114952e8ee..323b80bd35 100644 --- a/src/components/modals/HarvestAll.tsx +++ b/src/components/modals/HarvestAll.tsx @@ -178,7 +178,7 @@ export const HarvestAllModal: FC = ({ //calculate Stream Sum useEffect(() => { - setSumStream(BigNumber.sum(rewardStream, earnedStream)); // earnedLiquid includes the givback stream part + setSumStream(BigNumber.sum(rewardStream, earnedStream)); // earnedStream includes the givback stream part }, [rewardStream, earnedStream]); useEffect(() => { From 5b67172f9a47d3503549d083c2d829f1d8452ea8 Mon Sep 17 00:00:00 2001 From: Amin Latifi Date: Wed, 25 May 2022 16:19:57 +0430 Subject: [PATCH 182/257] Revert subgraph config --- src/config/development.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/config/development.ts b/src/config/development.ts index 1d9e8d7290..988fc31e06 100644 --- a/src/config/development.ts +++ b/src/config/development.ts @@ -32,7 +32,7 @@ const config: EnvConfig = { blockExplorerName: ['Etherscan'], blockExplorerUrls: ['https://kovan.etherscan.io'], subgraphAddress: - 'https://api.thegraph.com/subgraphs/name/mohammadranjbarz/giv-economy-kovan-deployment-seven', + 'https://api.thegraph.com/subgraphs/name/giveth/giveth-economy-kovan-staging', TOKEN_ADDRESS: '0x29434A25abd94AE882aA883eea81585Aaa5b078D', WETH_TOKEN_ADDRESS: '0xd0a1e359811322d97991e03f863a0c30c2cf029c', @@ -155,7 +155,7 @@ const config: EnvConfig = { blockExplorerName: ['Blockscout'], blockExplorerUrls: ['https://blockscout.com/xdai/mainnet'], subgraphAddress: - 'https://api.thegraph.com/subgraphs/name/mohammadranjbarz/giv-economy-xdai-deployment-seven', + 'https://api.thegraph.com/subgraphs/name/giveth/giveth-economy-xdai-staging', TOKEN_ADDRESS: '0x83a8eea6427985C523a0c4d9d3E62C051B6580d3', MERKLE_ADDRESS: '0xc87403C70c9FBfb594d98d3B5E695BBE4C694188', From 7d618c2767d9121bfe38353eaec5c378807a2a3a Mon Sep 17 00:00:00 2001 From: Mateo Daza Date: Wed, 25 May 2022 20:35:17 -0500 Subject: [PATCH 183/257] issue #784 --- src/config/development.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/config/development.ts b/src/config/development.ts index 3117f17342..7c5c9febae 100644 --- a/src/config/development.ts +++ b/src/config/development.ts @@ -132,8 +132,9 @@ const config: EnvConfig = { regenFarmType: RegenFarmType.CULT_ETH, regenFarmIntro: { title: 'CULT', - description: - 'The purpose of CULT is to empower and fund those building and contributing towards our decentralized future.', + description: `The purpose of CULT is to empower those building and contributing to our decentralized future. + Our society makes it as difficult as possible to break away from societal, economic and other norms, and CULT serves to fund and support those who are working to take back our future. CULT is a reminder that the power in people is stronger than the people in power. CULT is the governance token of the Cult DAO. Every transaction of the CULT token allows you to contribute & fast-forward economic & societal change by contributing a 0.4% tax to the treasury. + Fight from within until you get out, or change the system in doing so.`, link: 'https://cultdao.io/', }, farmStartTimeMS: 1646306818206, From 46858f45f9c56aa1bc5251d7f4e98bd519cea035 Mon Sep 17 00:00:00 2001 From: Mateo Daza Date: Wed, 25 May 2022 20:48:00 -0500 Subject: [PATCH 184/257] #785 --- src/components/GIVfrens.tsx | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/components/GIVfrens.tsx b/src/components/GIVfrens.tsx index 7bf1ca5a5f..21d9a88338 100644 --- a/src/components/GIVfrens.tsx +++ b/src/components/GIVfrens.tsx @@ -30,9 +30,13 @@ interface IGIVfrensProps { network: number; } +interface IChangeNetworkModal { + network: number; +} + export const GIVfrens: FC = ({ regenFarms, network }) => { const { chainId } = useWeb3React(); - + console.log({ chainId }); if (regenFarms.length === 0) return null; return ( @@ -55,6 +59,7 @@ export const GIVfrens: FC = ({ regenFarms, network }) => { {regenFarms.map((poolStakingConfig, index) => { + console.log({ chainId }); const regenStream = config.NETWORKS_CONFIG[ network ].regenStreams.find( @@ -90,7 +95,9 @@ export const GIVfrens: FC = ({ regenFarms, network }) => { {chainId !== poolStakingConfig?.network && ( <> - + )} @@ -101,18 +108,19 @@ export const GIVfrens: FC = ({ regenFarms, network }) => { ); }; -const DAOChangeNetworkModal = () => { +const DAOChangeNetworkModal = ({ network }: IChangeNetworkModal) => { + const networkLabel = network === 100 ? 'Gnosis chain' : 'Mainnet'; return ( Switch network - This RegenFarm is only available on Gnosis chain. + This RegenFarm is only available on {networkLabel} switchNetwork(config.XDAI_NETWORK_NUMBER)} + label={`Switch to ${networkLabel}`} + onClick={() => switchNetwork(network)} /> ); From f480c269061024d018ba7f8b731f0c37ceaf36b8 Mon Sep 17 00:00:00 2001 From: Mateo Daza Date: Wed, 25 May 2022 21:14:27 -0500 Subject: [PATCH 185/257] #786 --- src/components/modals/Stake.tsx | 16 ++++++++++++++-- src/components/modals/UnStake.tsx | 11 +++++++++-- src/config/development.ts | 2 ++ src/types/config.ts | 14 +++++++++----- 4 files changed, 34 insertions(+), 9 deletions(-) diff --git a/src/components/modals/Stake.tsx b/src/components/modals/Stake.tsx index 52a9f45787..adfa6d6cf9 100644 --- a/src/components/modals/Stake.tsx +++ b/src/components/modals/Stake.tsx @@ -61,8 +61,14 @@ export const StakeModal: FC = ({ ); const { chainId, library } = useWeb3React(); - const { title, LM_ADDRESS, POOL_ADDRESS, GARDEN_ADDRESS } = - poolStakingConfig; + const { + title, + LM_ADDRESS, + POOL_ADDRESS, + GARDEN_ADDRESS, + TOKEN_ADDRESS, + regenFarmIntro, + } = poolStakingConfig; const [permit, setPermit] = useState(false); useEffect(() => { @@ -384,6 +390,8 @@ export const StakeModal: FC = ({ title={title} walletNetwork={chainId} txHash={txHash} + rewardTokenAddress={TOKEN_ADDRESS} + rewardTokenSymbol={regenFarmIntro?.title} /> )} {chainId && stakeState === StakeState.CONFIRMED && ( @@ -391,6 +399,8 @@ export const StakeModal: FC = ({ title={title} walletNetwork={chainId} txHash={txHash} + rewardTokenAddress={TOKEN_ADDRESS} + rewardTokenSymbol={regenFarmIntro?.title} /> )} {chainId && stakeState === StakeState.ERROR && ( @@ -398,6 +408,8 @@ export const StakeModal: FC = ({ title='Something went wrong!' walletNetwork={chainId} txHash={txHash} + rewardTokenAddress={TOKEN_ADDRESS} + rewardTokenSymbol={regenFarmIntro?.title} /> )} diff --git a/src/components/modals/UnStake.tsx b/src/components/modals/UnStake.tsx index ecc1500189..174be027b5 100644 --- a/src/components/modals/UnStake.tsx +++ b/src/components/modals/UnStake.tsx @@ -46,7 +46,8 @@ export const UnStakeModal: FC = ({ ); const { library, chainId } = useWeb3React(); - const { title, LM_ADDRESS, GARDEN_ADDRESS } = poolStakingConfig; + const { title, LM_ADDRESS, GARDEN_ADDRESS, TOKEN_ADDRESS, regenFarmIntro } = + poolStakingConfig; const onWithdraw = async () => { setLabel('PENDING UNSTAKE'); @@ -135,13 +136,17 @@ export const UnStakeModal: FC = ({ title={title} walletNetwork={chainId} txHash={txHash} + rewardTokenAddress={TOKEN_ADDRESS} + rewardTokenSymbol={regenFarmIntro?.title} /> )} {chainId && stakeState === StakeState.CONFIRMED && ( )} {chainId && stakeState === StakeState.ERROR && ( @@ -149,6 +154,8 @@ export const UnStakeModal: FC = ({ title='Something went wrong!' walletNetwork={chainId} txHash={txHash} + rewardTokenAddress={TOKEN_ADDRESS} + rewardTokenSymbol={regenFarmIntro?.title} /> )} diff --git a/src/config/development.ts b/src/config/development.ts index 7c5c9febae..1570acd8d4 100644 --- a/src/config/development.ts +++ b/src/config/development.ts @@ -120,6 +120,7 @@ const config: EnvConfig = { { POOL_ADDRESS: '0x6bb32725aa31b1a99e7c782e0605b0fb57e4b9e6', LM_ADDRESS: '0x9d23d449af3e2c07a286688c85ff5d3d4c219d79', + TOKEN_ADDRESS: '0x3e4d3FadEE2338D420bb5E5cB26aAd96c165476c', type: StakingType.UNISWAPV2_CULT_ETH, platform: StakingPlatform.UNISWAP, network: 42, @@ -234,6 +235,7 @@ const config: EnvConfig = { { POOL_ADDRESS: '0xD28C07F802212F04AF41834ec0CC81d2d283124B', LM_ADDRESS: '0x06851400866e065972ff21e1ECdE035b4772736d', + TOKEN_ADDRESS: '0x18ce354571ba71bc7b3d633b254954c5a9cfc195', type: StakingType.HONEYSWAP_FOX_HNY, platform: StakingPlatform.HONEYSWAP, network: 100, diff --git a/src/types/config.ts b/src/types/config.ts index 98c3f7d75c..deb1a06496 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -42,6 +42,7 @@ export type PoolStakingConfig = export interface SimplePoolStakingConfig extends BasicStakingConfig { POOL_ADDRESS: string; + TOKEN_ADDRESS?: string; type: StakingType; platform: StakingPlatform; title: string; @@ -50,6 +51,7 @@ export interface SimplePoolStakingConfig extends BasicStakingConfig { unit: string; active: boolean; network?: number; + regenFarmIntro?: RegenFarmIntroConfig; } export interface UniswapV3PoolStakingConfig extends SimplePoolStakingConfig { @@ -69,14 +71,16 @@ export interface BalancerPoolStakingConfig extends SimplePoolStakingConfig { POOL_ID: string; } +export interface RegenFarmIntroConfig { + title: string; + description: string; + link: string; +} + export interface RegenPoolStakingConfig extends SimplePoolStakingConfig { regenStreamType: StreamType; regenFarmType: RegenFarmType; - regenFarmIntro?: { - title: string; - description: string; - link: string; - }; + regenFarmIntro?: RegenFarmIntroConfig; } export interface GasPreference { From 8ad8711d01de33b60cc6f9af9f4e1ddde5b9a2a3 Mon Sep 17 00:00:00 2001 From: Mateo Daza Date: Thu, 26 May 2022 08:22:03 -0500 Subject: [PATCH 186/257] removes console logs --- src/components/GIVfrens.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/components/GIVfrens.tsx b/src/components/GIVfrens.tsx index 21d9a88338..d74fd8ea72 100644 --- a/src/components/GIVfrens.tsx +++ b/src/components/GIVfrens.tsx @@ -36,7 +36,6 @@ interface IChangeNetworkModal { export const GIVfrens: FC = ({ regenFarms, network }) => { const { chainId } = useWeb3React(); - console.log({ chainId }); if (regenFarms.length === 0) return null; return ( @@ -59,7 +58,6 @@ export const GIVfrens: FC = ({ regenFarms, network }) => { {regenFarms.map((poolStakingConfig, index) => { - console.log({ chainId }); const regenStream = config.NETWORKS_CONFIG[ network ].regenStreams.find( From cbb926e4361beddfac5017857ed9d1c6618e7cf3 Mon Sep 17 00:00:00 2001 From: Ramin Date: Fri, 27 May 2022 18:11:10 +0430 Subject: [PATCH 187/257] #655 show txHash for failed donations --- src/components/views/donate/helpers.tsx | 11 ++++++++--- src/services/donation.ts | 3 ++- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/components/views/donate/helpers.tsx b/src/components/views/donate/helpers.tsx index 3869e37e72..16a335d380 100644 --- a/src/components/views/donate/helpers.tsx +++ b/src/components/views/donate/helpers.tsx @@ -135,10 +135,15 @@ export const confirmDonation = async (props: IConfirmDonation) => { const code = error.data?.code; if (code === ('INSUFFICIENT_FUNDS' || 'UNPREDICTABLE_GAS_LIMIT')) { showToastError('Insufficient Funds'); - } else if (error.replacement && error.cancelled === true) { - setTxHash(error.replacement.hash); + } else if ( + (error.replacement && error.cancelled === true) || + error.reason === 'transaction failed' + ) { + setTxHash(error.replacement?.hash || error.transactionHash); setShowFailedModal(true); - showToastError('Transaction cancelled!'); + showToastError( + `Transaction ${error.cancelled ? 'cancelled' : 'failed'}!`, + ); updateDonation(donationId, EDonationStatus.FAILED); } else { setShowFailedModal(true); diff --git a/src/services/donation.ts b/src/services/donation.ts index 67b4a11052..9ecc8a2c96 100644 --- a/src/services/donation.ts +++ b/src/services/donation.ts @@ -6,13 +6,14 @@ import { } from '@/apollo/gql/gqlDonations'; import { client } from '@/apollo/apolloClient'; import { IConfirmDonation } from '@/components/views/donate/helpers'; +import { EDonationStatus } from '@/apollo/types/gqlEnums'; interface IOnTxHash extends IConfirmDonation { txHash: string; nonce: number; } -export const updateDonation = (donationId: number, status: string) => { +export const updateDonation = (donationId: number, status: EDonationStatus) => { client .mutate({ mutation: UPDATE_DONATION_STATUS, From 12a55cd52a3228b64749a6fd073d5b965abeb9a0 Mon Sep 17 00:00:00 2001 From: Cherik Date: Fri, 27 May 2022 21:09:21 +0430 Subject: [PATCH 188/257] remove DAOChangeNetworkModal --- src/components/GIVfrens.sc.tsx | 10 ----- src/components/GIVfrens.tsx | 74 +--------------------------------- 2 files changed, 2 insertions(+), 82 deletions(-) diff --git a/src/components/GIVfrens.sc.tsx b/src/components/GIVfrens.sc.tsx index 55816eb0d2..53cd10ab21 100644 --- a/src/components/GIVfrens.sc.tsx +++ b/src/components/GIVfrens.sc.tsx @@ -63,13 +63,3 @@ export const DAOContainer = styled(Col)` position: relative; padding-top: 24px; `; - -export const DAOChangeNetwork = styled.div` - position: absolute; - left: 0; - top: 0; - right: 0; - bottom: 0; - backdrop-filter: blur(2px); - z-index: 2; -`; diff --git a/src/components/GIVfrens.tsx b/src/components/GIVfrens.tsx index d74fd8ea72..0052b9ee97 100644 --- a/src/components/GIVfrens.tsx +++ b/src/components/GIVfrens.tsx @@ -1,29 +1,14 @@ import React, { FC } from 'react'; -import { - brandColors, - Button, - Caption, - H3, - IconInfo16, - neutralColors, -} from '@giveth/ui-design-system'; +import { H3 } from '@giveth/ui-design-system'; import { useWeb3React } from '@web3-react/core'; -import styled from 'styled-components'; import { RegenPoolStakingConfig } from '@/types/config'; -import { - DAOContainer, - GIVfrensLink, - Subtitle, - DAOChangeNetwork, -} from '@/components/GIVfrens.sc'; +import { DAOContainer, GIVfrensLink, Subtitle } from '@/components/GIVfrens.sc'; import { PoolRow } from '@/components/homeTabs/GIVfarm.sc'; import StakingPoolCard from '@/components/cards/StakingPoolCard'; import { Col, Row } from './Grid'; import config from '@/configuration'; import { givEconomySupportedNetworks } from '@/lib/constants/constants'; import { RegenStreamCard } from './RegenStreamCard'; -import { Flex } from './styled-components/Flex'; -import { switchNetwork } from '@/lib/wallet'; interface IGIVfrensProps { regenFarms: RegenPoolStakingConfig[]; @@ -90,14 +75,6 @@ export const GIVfrens: FC = ({ regenFarms, network }) => { )} - {chainId !== poolStakingConfig?.network && ( - <> - - - - )} ); })} @@ -105,50 +82,3 @@ export const GIVfrens: FC = ({ regenFarms, network }) => { ); }; - -const DAOChangeNetworkModal = ({ network }: IChangeNetworkModal) => { - const networkLabel = network === 100 ? 'Gnosis chain' : 'Mainnet'; - return ( - - - - Switch network - - This RegenFarm is only available on {networkLabel} - switchNetwork(network)} - /> - - ); -}; - -const DAOChangeNetworkModalContainer = styled.div` - background-color: ${neutralColors.gray[100]}; - color: ${brandColors.giv[300]}; - border: 1px solid ${brandColors.giv[300]}; - border-radius: 8px; - width: 320px; - z-index: 4; - position: absolute; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - opacity: 2; - padding: 16px; -`; - -const Title = styled(Caption)` - font-weight: bold; -`; - -const Desc = styled(Caption)` - margin-left: 32px; - margin-bottom: 16px; -`; - -const ChangeButton = styled(Button)` - color: ${brandColors.giv[300]}; - margin-left: auto; -`; From 335da7359c82c705eaa78629923b93755ba1aa11 Mon Sep 17 00:00:00 2001 From: Cherik Date: Fri, 27 May 2022 21:09:35 +0430 Subject: [PATCH 189/257] fix config --- src/config/development.ts | 2 -- src/types/config.ts | 2 -- 2 files changed, 4 deletions(-) diff --git a/src/config/development.ts b/src/config/development.ts index 1570acd8d4..7c5c9febae 100644 --- a/src/config/development.ts +++ b/src/config/development.ts @@ -120,7 +120,6 @@ const config: EnvConfig = { { POOL_ADDRESS: '0x6bb32725aa31b1a99e7c782e0605b0fb57e4b9e6', LM_ADDRESS: '0x9d23d449af3e2c07a286688c85ff5d3d4c219d79', - TOKEN_ADDRESS: '0x3e4d3FadEE2338D420bb5E5cB26aAd96c165476c', type: StakingType.UNISWAPV2_CULT_ETH, platform: StakingPlatform.UNISWAP, network: 42, @@ -235,7 +234,6 @@ const config: EnvConfig = { { POOL_ADDRESS: '0xD28C07F802212F04AF41834ec0CC81d2d283124B', LM_ADDRESS: '0x06851400866e065972ff21e1ECdE035b4772736d', - TOKEN_ADDRESS: '0x18ce354571ba71bc7b3d633b254954c5a9cfc195', type: StakingType.HONEYSWAP_FOX_HNY, platform: StakingPlatform.HONEYSWAP, network: 100, diff --git a/src/types/config.ts b/src/types/config.ts index deb1a06496..a7a918cdf5 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -42,7 +42,6 @@ export type PoolStakingConfig = export interface SimplePoolStakingConfig extends BasicStakingConfig { POOL_ADDRESS: string; - TOKEN_ADDRESS?: string; type: StakingType; platform: StakingPlatform; title: string; @@ -51,7 +50,6 @@ export interface SimplePoolStakingConfig extends BasicStakingConfig { unit: string; active: boolean; network?: number; - regenFarmIntro?: RegenFarmIntroConfig; } export interface UniswapV3PoolStakingConfig extends SimplePoolStakingConfig { From 115a648d728096d07b04afae7ed4717da64ba974 Mon Sep 17 00:00:00 2001 From: Cherik Date: Fri, 27 May 2022 21:10:39 +0430 Subject: [PATCH 190/257] fix stake modal --- src/components/modals/Stake.tsx | 34 +++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/src/components/modals/Stake.tsx b/src/components/modals/Stake.tsx index adfa6d6cf9..3d8a9934fd 100644 --- a/src/components/modals/Stake.tsx +++ b/src/components/modals/Stake.tsx @@ -16,7 +16,6 @@ import { Contract, ethers } from 'ethers'; import { captureException } from '@sentry/nextjs'; import { Modal } from './Modal'; import { Flex } from '../styled-components/Flex'; -import { PoolStakingConfig } from '@/types/config'; import { StakingPoolImages } from '../StakingPoolImages'; import { AmountInput } from '../AmountInput'; import { @@ -34,9 +33,11 @@ import { StakeState } from '@/lib/staking'; import ToggleSwitch from '../styled-components/Switch'; import { abi as ERC20_ABI } from '@/artifacts/ERC20.json'; import { IModal } from '@/types/common'; +import type { PoolStakingConfig, RegenStreamConfig } from '@/types/config'; interface IStakeModalProps extends IModal { poolStakingConfig: PoolStakingConfig; + regenStreamConfig?: RegenStreamConfig; maxAmount: BigNumber; } @@ -51,25 +52,20 @@ const loadingAnimationOptions = { export const StakeModal: FC = ({ poolStakingConfig, + regenStreamConfig, maxAmount, setShowModal, }) => { const [amount, setAmount] = useState('0'); const [txHash, setTxHash] = useState(''); + const [permit, setPermit] = useState(false); const [stakeState, setStakeState] = useState( StakeState.APPROVE, ); const { chainId, library } = useWeb3React(); - const { - title, - LM_ADDRESS, - POOL_ADDRESS, - GARDEN_ADDRESS, - TOKEN_ADDRESS, - regenFarmIntro, - } = poolStakingConfig; - const [permit, setPermit] = useState(false); + const { title, LM_ADDRESS, POOL_ADDRESS, GARDEN_ADDRESS } = + poolStakingConfig; useEffect(() => { if (GARDEN_ADDRESS) { @@ -390,8 +386,10 @@ export const StakeModal: FC = ({ title={title} walletNetwork={chainId} txHash={txHash} - rewardTokenAddress={TOKEN_ADDRESS} - rewardTokenSymbol={regenFarmIntro?.title} + rewardTokenAddress={ + regenStreamConfig?.rewardTokenAddress + } + rewardTokenSymbol={regenStreamConfig?.rewardTokenSymbol} /> )} {chainId && stakeState === StakeState.CONFIRMED && ( @@ -399,8 +397,10 @@ export const StakeModal: FC = ({ title={title} walletNetwork={chainId} txHash={txHash} - rewardTokenAddress={TOKEN_ADDRESS} - rewardTokenSymbol={regenFarmIntro?.title} + rewardTokenAddress={ + regenStreamConfig?.rewardTokenAddress + } + rewardTokenSymbol={regenStreamConfig?.rewardTokenSymbol} /> )} {chainId && stakeState === StakeState.ERROR && ( @@ -408,8 +408,10 @@ export const StakeModal: FC = ({ title='Something went wrong!' walletNetwork={chainId} txHash={txHash} - rewardTokenAddress={TOKEN_ADDRESS} - rewardTokenSymbol={regenFarmIntro?.title} + rewardTokenAddress={ + regenStreamConfig?.rewardTokenAddress + } + rewardTokenSymbol={regenStreamConfig?.rewardTokenSymbol} /> )} From 942eb7f5750c8205d809712ee1f3751b8799e10e Mon Sep 17 00:00:00 2001 From: Cherik Date: Fri, 27 May 2022 21:10:46 +0430 Subject: [PATCH 191/257] fix unstake modal --- src/components/modals/UnStake.tsx | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/components/modals/UnStake.tsx b/src/components/modals/UnStake.tsx index 174be027b5..1ff888defa 100644 --- a/src/components/modals/UnStake.tsx +++ b/src/components/modals/UnStake.tsx @@ -6,7 +6,6 @@ import { BigNumber } from 'ethers'; import { useWeb3React } from '@web3-react/core'; import { Modal } from './Modal'; import { Flex } from '../styled-components/Flex'; -import { PoolStakingConfig } from '@/types/config'; import { StakingPoolImages } from '../StakingPoolImages'; import { AmountInput } from '../AmountInput'; import { unwrapToken, withdrawTokens } from '@/lib/stakingPool'; @@ -18,6 +17,7 @@ import { } from './ConfirmSubmit'; import { StakeState } from '@/lib/staking'; import { IModal } from '@/types/common'; +import type { PoolStakingConfig, RegenStreamConfig } from '@/types/config'; const loadingAnimationOptions = { loop: true, @@ -30,11 +30,13 @@ const loadingAnimationOptions = { interface IUnStakeModalProps extends IModal { poolStakingConfig: PoolStakingConfig; + regenStreamConfig?: RegenStreamConfig; maxAmount: BigNumber; } export const UnStakeModal: FC = ({ poolStakingConfig, + regenStreamConfig, maxAmount, setShowModal, }) => { @@ -46,8 +48,7 @@ export const UnStakeModal: FC = ({ ); const { library, chainId } = useWeb3React(); - const { title, LM_ADDRESS, GARDEN_ADDRESS, TOKEN_ADDRESS, regenFarmIntro } = - poolStakingConfig; + const { title, LM_ADDRESS, GARDEN_ADDRESS } = poolStakingConfig; const onWithdraw = async () => { setLabel('PENDING UNSTAKE'); @@ -136,8 +137,10 @@ export const UnStakeModal: FC = ({ title={title} walletNetwork={chainId} txHash={txHash} - rewardTokenAddress={TOKEN_ADDRESS} - rewardTokenSymbol={regenFarmIntro?.title} + rewardTokenAddress={ + regenStreamConfig?.rewardTokenAddress + } + rewardTokenSymbol={regenStreamConfig?.rewardTokenSymbol} /> )} {chainId && stakeState === StakeState.CONFIRMED && ( @@ -145,8 +148,10 @@ export const UnStakeModal: FC = ({ title={title} walletNetwork={chainId} txHash={txHash} - rewardTokenAddress={TOKEN_ADDRESS} - rewardTokenSymbol={regenFarmIntro?.title} + rewardTokenAddress={ + regenStreamConfig?.rewardTokenAddress + } + rewardTokenSymbol={regenStreamConfig?.rewardTokenSymbol} /> )} {chainId && stakeState === StakeState.ERROR && ( @@ -154,8 +159,10 @@ export const UnStakeModal: FC = ({ title='Something went wrong!' walletNetwork={chainId} txHash={txHash} - rewardTokenAddress={TOKEN_ADDRESS} - rewardTokenSymbol={regenFarmIntro?.title} + rewardTokenAddress={ + regenStreamConfig?.rewardTokenAddress + } + rewardTokenSymbol={regenStreamConfig?.rewardTokenSymbol} /> )} From 234f3078904ad449f738ba0444e3cea9c9839b31 Mon Sep 17 00:00:00 2001 From: Cherik Date: Fri, 27 May 2022 21:51:13 +0430 Subject: [PATCH 192/257] update BaseStakingCard --- src/components/cards/BaseStakingCard.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/components/cards/BaseStakingCard.tsx b/src/components/cards/BaseStakingCard.tsx index 6097c84109..9083fd01fd 100644 --- a/src/components/cards/BaseStakingCard.tsx +++ b/src/components/cards/BaseStakingCard.tsx @@ -480,6 +480,7 @@ const BaseStakingCard: FC = ({ ))} @@ -501,6 +502,7 @@ const BaseStakingCard: FC = ({ ))} From 91bdc193de67ded3f234ae3aa1a181e209d04a0c Mon Sep 17 00:00:00 2001 From: Cherik Date: Fri, 27 May 2022 21:58:26 +0430 Subject: [PATCH 193/257] Revert "remove DAOChangeNetworkModal" This reverts commit 12a55cd52a3228b64749a6fd073d5b965abeb9a0. --- src/components/GIVfrens.sc.tsx | 10 +++++ src/components/GIVfrens.tsx | 74 +++++++++++++++++++++++++++++++++- 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/src/components/GIVfrens.sc.tsx b/src/components/GIVfrens.sc.tsx index 53cd10ab21..55816eb0d2 100644 --- a/src/components/GIVfrens.sc.tsx +++ b/src/components/GIVfrens.sc.tsx @@ -63,3 +63,13 @@ export const DAOContainer = styled(Col)` position: relative; padding-top: 24px; `; + +export const DAOChangeNetwork = styled.div` + position: absolute; + left: 0; + top: 0; + right: 0; + bottom: 0; + backdrop-filter: blur(2px); + z-index: 2; +`; diff --git a/src/components/GIVfrens.tsx b/src/components/GIVfrens.tsx index 0052b9ee97..d74fd8ea72 100644 --- a/src/components/GIVfrens.tsx +++ b/src/components/GIVfrens.tsx @@ -1,14 +1,29 @@ import React, { FC } from 'react'; -import { H3 } from '@giveth/ui-design-system'; +import { + brandColors, + Button, + Caption, + H3, + IconInfo16, + neutralColors, +} from '@giveth/ui-design-system'; import { useWeb3React } from '@web3-react/core'; +import styled from 'styled-components'; import { RegenPoolStakingConfig } from '@/types/config'; -import { DAOContainer, GIVfrensLink, Subtitle } from '@/components/GIVfrens.sc'; +import { + DAOContainer, + GIVfrensLink, + Subtitle, + DAOChangeNetwork, +} from '@/components/GIVfrens.sc'; import { PoolRow } from '@/components/homeTabs/GIVfarm.sc'; import StakingPoolCard from '@/components/cards/StakingPoolCard'; import { Col, Row } from './Grid'; import config from '@/configuration'; import { givEconomySupportedNetworks } from '@/lib/constants/constants'; import { RegenStreamCard } from './RegenStreamCard'; +import { Flex } from './styled-components/Flex'; +import { switchNetwork } from '@/lib/wallet'; interface IGIVfrensProps { regenFarms: RegenPoolStakingConfig[]; @@ -75,6 +90,14 @@ export const GIVfrens: FC = ({ regenFarms, network }) => { )} + {chainId !== poolStakingConfig?.network && ( + <> + + + + )} ); })} @@ -82,3 +105,50 @@ export const GIVfrens: FC = ({ regenFarms, network }) => { ); }; + +const DAOChangeNetworkModal = ({ network }: IChangeNetworkModal) => { + const networkLabel = network === 100 ? 'Gnosis chain' : 'Mainnet'; + return ( + + + + Switch network + + This RegenFarm is only available on {networkLabel} + switchNetwork(network)} + /> + + ); +}; + +const DAOChangeNetworkModalContainer = styled.div` + background-color: ${neutralColors.gray[100]}; + color: ${brandColors.giv[300]}; + border: 1px solid ${brandColors.giv[300]}; + border-radius: 8px; + width: 320px; + z-index: 4; + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + opacity: 2; + padding: 16px; +`; + +const Title = styled(Caption)` + font-weight: bold; +`; + +const Desc = styled(Caption)` + margin-left: 32px; + margin-bottom: 16px; +`; + +const ChangeButton = styled(Button)` + color: ${brandColors.giv[300]}; + margin-left: auto; +`; From 99e692abfde6e69d7d9a4a1a1233bceb57ec6e31 Mon Sep 17 00:00:00 2001 From: Cherik Date: Fri, 27 May 2022 22:11:05 +0430 Subject: [PATCH 194/257] fix cult stream in harvest modal --- src/components/modals/HarvestAll.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/components/modals/HarvestAll.tsx b/src/components/modals/HarvestAll.tsx index 323b80bd35..443c2255ed 100644 --- a/src/components/modals/HarvestAll.tsx +++ b/src/components/modals/HarvestAll.tsx @@ -159,6 +159,9 @@ export const HarvestAllModal: FC = ({ case StreamType.FOX: lockedAmount = BN(balances.foxAllocatedTokens); break; + case StreamType.CULT: + lockedAmount = BN(balances.cultAllocatedTokens); + break; default: lockedAmount = ethers.constants.Zero; } @@ -169,7 +172,7 @@ export const HarvestAllModal: FC = ({ tokenDistroHelper.getStreamPartTokenPerWeek(lockedAmount), ); setGivBackStream(tokenDistroHelper.getStreamPartTokenPerWeek(givback)); - }, [earned, balances, tokenDistroHelper, givback]); + }, [earned, balances, tokenDistroHelper, givback, regenStreamConfig]); //calculate Liquid Sum useEffect(() => { From 217e4f779c433672a3161118052277b1c64ef828 Mon Sep 17 00:00:00 2001 From: Cherik Date: Fri, 27 May 2022 23:15:06 +0430 Subject: [PATCH 195/257] change number to config --- src/components/GIVfrens.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/components/GIVfrens.tsx b/src/components/GIVfrens.tsx index d74fd8ea72..42b6540730 100644 --- a/src/components/GIVfrens.tsx +++ b/src/components/GIVfrens.tsx @@ -107,7 +107,8 @@ export const GIVfrens: FC = ({ regenFarms, network }) => { }; const DAOChangeNetworkModal = ({ network }: IChangeNetworkModal) => { - const networkLabel = network === 100 ? 'Gnosis chain' : 'Mainnet'; + const networkLabel = + network === config.XDAI_NETWORK_NUMBER ? 'Gnosis chain' : 'Mainnet'; return ( From 35763e59be57bb2d7a7b59237e04a1ae1704ee07 Mon Sep 17 00:00:00 2001 From: Mateo Daza Date: Fri, 27 May 2022 15:02:54 -0500 Subject: [PATCH 196/257] hotfix adds uniswapv2subgraph for mainnet --- src/config/development.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/config/development.ts b/src/config/development.ts index 7c5c9febae..e7c71770f6 100644 --- a/src/config/development.ts +++ b/src/config/development.ts @@ -103,6 +103,8 @@ const config: EnvConfig = { active: false, }, ], + uniswapV2Subgraph: + 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2', regenStreams: [ { tokenDistroAddress: From e779ce492dd35501db0c4e0a3e511f666191e97f Mon Sep 17 00:00:00 2001 From: Ramin Date: Sat, 28 May 2022 01:11:59 +0430 Subject: [PATCH 197/257] #789 fix donating from a purple list address fails to trigger warning about GIVbacks --- src/apollo/gql/gqlPurpleList.ts | 5 ++++ src/apollo/types/gqlTypes.ts | 6 +++++ .../views/donate/CryptoDonation.tsx | 3 +++ src/components/views/donate/GIVBackToast.tsx | 20 ++++++++-------- src/hooks/usePurpleList.tsx | 23 +++++++++++++++++++ 5 files changed, 48 insertions(+), 9 deletions(-) create mode 100644 src/apollo/gql/gqlPurpleList.ts create mode 100644 src/hooks/usePurpleList.tsx diff --git a/src/apollo/gql/gqlPurpleList.ts b/src/apollo/gql/gqlPurpleList.ts new file mode 100644 index 0000000000..7fc624ae31 --- /dev/null +++ b/src/apollo/gql/gqlPurpleList.ts @@ -0,0 +1,5 @@ +export const CHECK_PURPLE_LIST = ` + query walletAddressIsPurpleListed($address: String!) { + walletAddressIsPurpleListed(address: $address) + } +`; diff --git a/src/apollo/types/gqlTypes.ts b/src/apollo/types/gqlTypes.ts index 8f2c213b99..8b0dfb8ee7 100644 --- a/src/apollo/types/gqlTypes.ts +++ b/src/apollo/types/gqlTypes.ts @@ -60,6 +60,12 @@ export interface ISuggestedProjectsGQL { }; } +export interface ICheckPurpleListGQL { + data: { + walletAddressIsPurpleListed: boolean; + }; +} + export interface IProjectAcceptedToken { id?: string; symbol: string; diff --git a/src/components/views/donate/CryptoDonation.tsx b/src/components/views/donate/CryptoDonation.tsx index 050d0ca704..12b4a164ca 100644 --- a/src/components/views/donate/CryptoDonation.tsx +++ b/src/components/views/donate/CryptoDonation.tsx @@ -59,6 +59,7 @@ import { setShowSignWithWallet, setShowWalletModal, } from '@/features/modal/modal.sclie'; +import usePurpleList from '@/hooks/usePurpleList'; const ethereumChain = config.PRIMARY_NETWORK; const xdaiChain = config.SECONDARY_NETWORK; @@ -85,6 +86,7 @@ const CryptoDonation = (props: { state => state.user, ); const { ethPrice } = usePrice(); + const isPurpleListed = usePurpleList(); const { project, setSuccessDonation } = props; const { organization, verified, id: projectId, status } = project; @@ -446,6 +448,7 @@ const CryptoDonation = (props: { )} diff --git a/src/components/views/donate/GIVBackToast.tsx b/src/components/views/donate/GIVBackToast.tsx index d5a1e19edf..25aebb57c8 100644 --- a/src/components/views/donate/GIVBackToast.tsx +++ b/src/components/views/donate/GIVBackToast.tsx @@ -9,14 +9,19 @@ import ExternalLink from '@/components/ExternalLink'; const GIVBackToast = (props: { projectEligible?: boolean; tokenEligible?: boolean; + userEligible?: boolean; }) => { - const { projectEligible, tokenEligible } = props; - let message, color, boldColor, backgroundColor; - if (!projectEligible) { - message = 'This project is not eligible for GIVbacks.'; - color = brandColors.mustard[700]; - boldColor = brandColors.mustard[800]; + const { projectEligible, tokenEligible, userEligible } = props; + let message, + color = brandColors.mustard[700], + boldColor = brandColors.mustard[800], backgroundColor = brandColors.mustard[200]; + + if (!userEligible) { + message = + 'This wallet address is associated with a Giveth project, therefore, donations made from this address are not eligible for GIVbacks.'; + } else if (!projectEligible) { + message = 'This project is not eligible for GIVbacks.'; } else if (tokenEligible) { message = 'This token is eligible for GIVbacks.'; color = brandColors.giv[300]; @@ -35,9 +40,6 @@ const GIVBackToast = (props: { . ); - color = brandColors.mustard[700]; - boldColor = brandColors.mustard[800]; - backgroundColor = brandColors.mustard[200]; } return ( diff --git a/src/hooks/usePurpleList.tsx b/src/hooks/usePurpleList.tsx new file mode 100644 index 0000000000..f40eddaec6 --- /dev/null +++ b/src/hooks/usePurpleList.tsx @@ -0,0 +1,23 @@ +import { useWeb3React } from '@web3-react/core'; +import { useEffect, useState } from 'react'; +import { CHECK_PURPLE_LIST } from '@/apollo/gql/gqlPurpleList'; +import { ICheckPurpleListGQL } from '@/apollo/types/gqlTypes'; +import { gqlRequest } from '@/helpers/requests'; + +export default function usePurpleList() { + const { account: address } = useWeb3React(); + + const [isPurpleList, setIsPurpleList] = useState(false); + + useEffect(() => { + if (address) { + gqlRequest(CHECK_PURPLE_LIST, { address }) + .then((res: ICheckPurpleListGQL) => { + setIsPurpleList(res.data?.walletAddressIsPurpleListed); + }) + .catch(console.log); + } + }, [address]); + + return isPurpleList; +} From bc848011873040e0b696a05f3b648f76db93bf8a Mon Sep 17 00:00:00 2001 From: Ramin Date: Sat, 28 May 2022 01:22:13 +0430 Subject: [PATCH 198/257] #772 show error on fail saving donation --- src/components/views/donate/helpers.tsx | 37 +++++++++++++++++-------- src/lib/helpers.ts | 3 +- src/services/donation.ts | 3 +- 3 files changed, 29 insertions(+), 14 deletions(-) diff --git a/src/components/views/donate/helpers.tsx b/src/components/views/donate/helpers.tsx index 3869e37e72..c028e77e22 100644 --- a/src/components/views/donate/helpers.tsx +++ b/src/components/views/donate/helpers.tsx @@ -104,7 +104,8 @@ export const confirmDonation = async (props: IConfirmDonation) => { const { library } = web3Context; const { walletAddress } = project; const { address } = token; - let donationId = 0; + let donationId = 0, + donationSaved = false; try { const toAddress = isAddressENS(walletAddress!) @@ -118,32 +119,46 @@ export const confirmDonation = async (props: IConfirmDonation) => { const txCallbacks = { onTxHash: async (txHash: string, nonce: number) => { - donationId = await saveDonation({ nonce, txHash, ...props }); setTxHash(txHash); - setDonationSaved(true); + saveDonation({ nonce, txHash, ...props }) + .then(res => { + donationId = res; + setDonationSaved(true); + donationSaved = true; + }) + .catch(() => { + showToastError('Error saving donation!'); + setShowFailedModal(true); + setDonating(false); + }); }, onReceipt: async (txHash: string) => { updateDonation(donationId, EDonationStatus.VERIFIED); - setSuccessDonation({ txHash, givBackEligible }); + donationSaved && + setSuccessDonation({ txHash, givBackEligible }); }, }; await sendTransaction(library, transactionObj, txCallbacks, address); } catch (error: any) { - setDonating(false); - setDonationSaved(false); const code = error.data?.code; if (code === ('INSUFFICIENT_FUNDS' || 'UNPREDICTABLE_GAS_LIMIT')) { showToastError('Insufficient Funds'); - } else if (error.replacement && error.cancelled === true) { - setTxHash(error.replacement.hash); - setShowFailedModal(true); - showToastError('Transaction cancelled!'); + } else if ( + (error.replacement && error.cancelled === true) || + error.reason === 'transaction failed' + ) { + setTxHash(error.replacement?.hash || error.transactionHash); + showToastError( + `Transaction ${error.cancelled ? 'cancelled' : 'failed'}!`, + ); updateDonation(donationId, EDonationStatus.FAILED); } else { - setShowFailedModal(true); showToastError(error); } + setShowFailedModal(true); + setDonating(false); + setDonationSaved(false); captureException(error, { tags: { section: 'confirmDonation', diff --git a/src/lib/helpers.ts b/src/lib/helpers.ts index 8265e84f59..82cbd50d77 100644 --- a/src/lib/helpers.ts +++ b/src/lib/helpers.ts @@ -203,9 +203,8 @@ export async function sendTransaction( txCallbacks.onReceipt(tx.hash); } - console.log('stTxn ---> : ', { tx, receipt }); + console.log('Tx ---> : ', { tx, receipt }); } catch (error: any) { - console.log('Error sending transaction: ', { error }); if (error.replacement && !error.cancelled) { // Speed up the process by replacing the transaction txCallbacks.onReceipt(error.replacement.hash); diff --git a/src/services/donation.ts b/src/services/donation.ts index 67b4a11052..26093f705f 100644 --- a/src/services/donation.ts +++ b/src/services/donation.ts @@ -57,9 +57,10 @@ export async function saveDonation(props: IOnTxHash) { section: 'createDonation', }, }); + console.log(error); throw error; } - console.log('DONATION SUCCESS: ', { donationId }); + console.log('DONATION ID: ', { donationId }); return donationId; } From 2ea5511d250d72614984e6c29be0723edc563b58 Mon Sep 17 00:00:00 2001 From: Ramin Date: Sat, 28 May 2022 02:25:43 +0430 Subject: [PATCH 199/257] fix error on connecting Torus --- src/features/user/user.slice.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/features/user/user.slice.ts b/src/features/user/user.slice.ts index dc295782bb..c976547a6c 100644 --- a/src/features/user/user.slice.ts +++ b/src/features/user/user.slice.ts @@ -65,7 +65,7 @@ export const userSlice = createSlice({ if ( compareAddresses( localAddress, - action.payload.data.userByAddress.walletAddress, + action.payload.data.userByAddress?.walletAddress, ) ) { state.token = From 5591e5024dc65bbdfde0167efe065bd70bd5f71a Mon Sep 17 00:00:00 2001 From: Ramin Date: Sat, 28 May 2022 02:31:05 +0430 Subject: [PATCH 200/257] #822 prevent opening metamask popup --- src/components/controller/user.ctrl.tsx | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/components/controller/user.ctrl.tsx b/src/components/controller/user.ctrl.tsx index 46e96997d1..5d52f6ca83 100644 --- a/src/components/controller/user.ctrl.tsx +++ b/src/components/controller/user.ctrl.tsx @@ -2,6 +2,7 @@ import { useWeb3React } from '@web3-react/core'; import { useEffect } from 'react'; import { formatEther } from '@ethersproject/units'; import { captureException } from '@sentry/nextjs'; +import { InjectedConnector } from '@web3-react/injected-connector'; import { useAppDispatch } from '@/features/hooks'; import { setBalance, @@ -22,9 +23,11 @@ const UserController = () => { useEffect(() => { const selectedWalletName = localStorage.getItem(StorageLabel.WALLET); const wallet = walletsArray.find(w => w.value === selectedWalletName); - if (wallet) { - activate(wallet.connector, err => { - console.log('err', err); + if (wallet && wallet.connector instanceof InjectedConnector) { + wallet.connector.isAuthorized().then(isAuthorized => { + if (isAuthorized) { + activate(wallet.connector, console.log).then(); + } }); } }, [activate]); From 777ba661a63db7b6a63f5258e65ad87c51d66fba Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 29 May 2022 11:52:50 +0430 Subject: [PATCH 201/257] add types to subgraph initialstate --- src/features/subgraph/subgraph.slice.ts | 39 ++++++++++++------------- 1 file changed, 18 insertions(+), 21 deletions(-) diff --git a/src/features/subgraph/subgraph.slice.ts b/src/features/subgraph/subgraph.slice.ts index efd370a9ee..4c798123ba 100644 --- a/src/features/subgraph/subgraph.slice.ts +++ b/src/features/subgraph/subgraph.slice.ts @@ -15,10 +15,27 @@ export const defaultSubgraphValues: ISubgraphState = { allPositions: [], }; -const initialState = { +const initialState: { + currentValues: ISubgraphState; + mainnetValues: ISubgraphState; + xDaiValues: ISubgraphState; + ethPrice: string; + givPrice: string; + mainnetThirdPartyTokensPrice: { + [tokenAddress: string]: string; + }; + xDaiThirdPartyTokensPrice: { + [tokenAddress: string]: string; + }; + status: string; +} = { currentValues: defaultSubgraphValues, mainnetValues: defaultSubgraphValues, xDaiValues: defaultSubgraphValues, + ethPrice: '0', + givPrice: '0', + mainnetThirdPartyTokensPrice: {}, + xDaiThirdPartyTokensPrice: {}, status: 'idle', }; @@ -28,9 +45,6 @@ export const subgraphSlice = createSlice({ reducers: {}, extraReducers: builder => { builder - .addCase(fetchCurrentInfoAsync.pending, state => { - state.status = 'loading'; - }) .addCase(fetchCurrentInfoAsync.fulfilled, (state, action) => { state.status = 'idle'; state.currentValues = action.payload.response; @@ -41,30 +55,13 @@ export const subgraphSlice = createSlice({ state.xDaiValues = action.payload.response; } }) - .addCase(fetchCurrentInfoAsync.rejected, state => { - state.status = 'failed'; - }); - builder - .addCase(fetchXDaiInfoAsync.pending, state => { - state.status = 'loading'; - }) .addCase(fetchXDaiInfoAsync.fulfilled, (state, action) => { state.status = 'idle'; state.xDaiValues = action.payload; }) - .addCase(fetchXDaiInfoAsync.rejected, state => { - state.status = 'failed'; - }); - builder - .addCase(fetchMainnetInfoAsync.pending, state => { - state.status = 'loading'; - }) .addCase(fetchMainnetInfoAsync.fulfilled, (state, action) => { state.status = 'idle'; state.mainnetValues = action.payload; - }) - .addCase(fetchMainnetInfoAsync.rejected, state => { - state.status = 'failed'; }); }, }); From 86ae40c250baa012cdda33fa137e1caab59cd48a Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 29 May 2022 12:17:12 +0430 Subject: [PATCH 202/257] add more requests method --- src/helpers/requests.ts | 64 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 60 insertions(+), 4 deletions(-) diff --git a/src/helpers/requests.ts b/src/helpers/requests.ts index 403ecadb74..5dd95772d7 100644 --- a/src/helpers/requests.ts +++ b/src/helpers/requests.ts @@ -2,14 +2,17 @@ import { isSSRMode } from '@/lib/helpers'; import links from '@/lib/constants/links'; import StorageLabel from '@/lib/localStorage'; -export function postRequest( +export function sendRequest( url: string, - body: {} = {}, + method: 'POST' | 'GET', + authorization: boolean = false, + body?: {}, additionalHeaders: HeadersInit = {}, additionalOptions: RequestInit = {}, ) { const token = !isSSRMode ? localStorage.getItem(StorageLabel.TOKEN) : null; - const Authorization = token ? `Bearer ${token}` : undefined; + const Authorization = + authorization && token ? `Bearer ${token}` : undefined; const defaultHeaders = { 'Content-Type': 'application/json', ...additionalHeaders, @@ -22,7 +25,7 @@ export function postRequest( : { ...defaultHeaders }; try { return fetch(url, { - method: 'POST', + method, headers, body: JSON.stringify(body), ...additionalOptions, @@ -41,7 +44,59 @@ export function postRequest( } } +export function getRequest( + url: string, + authorization: boolean = false, + additionalHeaders: HeadersInit = {}, + additionalOptions: RequestInit = {}, +) { + return sendRequest( + url, + 'GET', + authorization, + undefined, + additionalHeaders, + additionalOptions, + ); +} + +export function postRequest( + url: string, + authorization: boolean = false, + body: {} = {}, + additionalHeaders: HeadersInit = {}, + additionalOptions: RequestInit = {}, +) { + return sendRequest( + url, + 'POST', + authorization, + body, + additionalHeaders, + additionalOptions, + ); +} + export function gqlRequest( + url: string, + query: string, + variables: {} = {}, + additionalHeaders: HeadersInit = {}, + additionalOptions: RequestInit = {}, +) { + return postRequest( + url, + true, + { + query, + variables, + }, + additionalHeaders, + additionalOptions, + ); +} + +export function backendGQLRequest( query: string, variables: {} = {}, additionalHeaders: HeadersInit = {}, @@ -49,6 +104,7 @@ export function gqlRequest( ) { return postRequest( links.BACKEND, + true, { query, variables, From 11fc674ebc15c9883e509b7b933c91bb7bc483ff Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 29 May 2022 12:17:30 +0430 Subject: [PATCH 203/257] update requests usage --- src/features/user/user.thunks.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/features/user/user.thunks.ts b/src/features/user/user.thunks.ts index d1a5ae27b6..f52d314729 100644 --- a/src/features/user/user.thunks.ts +++ b/src/features/user/user.thunks.ts @@ -1,5 +1,5 @@ import { createAsyncThunk } from '@reduxjs/toolkit'; -import { gqlRequest } from '@/helpers/requests'; +import { backendGQLRequest } from '@/helpers/requests'; import { GET_USER_BY_ADDRESS } from './user.queries'; import { ISignToGetToken } from './user.types'; import { createSiweMessage } from '@/lib/helpers'; @@ -10,7 +10,7 @@ import config from '@/configuration'; export const fetchUserByAddress = createAsyncThunk( 'user/fetchUser', async (address: string) => { - return gqlRequest(GET_USER_BY_ADDRESS, { address }); + return backendGQLRequest(GET_USER_BY_ADDRESS, { address }); }, ); @@ -37,6 +37,7 @@ export const signToGetToken = createAsyncThunk( } const token = await postRequest( `${config.MICROSERVICES.authentication}/authentication`, + true, { signature, message, @@ -59,6 +60,7 @@ export const signOut = createAsyncThunk( async (token: string) => { return await postRequest( `${config.MICROSERVICES.authentication}/logout`, + true, { jwt: token, }, From 01e6a41160070ca2a48d42cb96682c6c2df0c3d5 Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 29 May 2022 12:38:43 +0430 Subject: [PATCH 204/257] remove PriceProvider from _app --- pages/_app.tsx | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/pages/_app.tsx b/pages/_app.tsx index 3bb0aaff11..d6ae6e99ca 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -8,7 +8,6 @@ import NProgress from 'nprogress'; import { useRouter } from 'next/router'; import { Provider } from 'react-redux'; -import { PriceProvider } from '@/context/price.context'; import { GeneralProvider } from '@/context/general.context'; import { useApollo } from '@/apollo/apolloClient'; import { HeaderWrapper } from '@/components/Header/HeaderWrapper'; @@ -61,16 +60,12 @@ function MyApp({ Component, pageProps }: AppProps) { - - {/* */} - - - - - - - {/* */} - + + + + + + From cb6b246836644720eb25c3d7d9cd90c383545d33 Mon Sep 17 00:00:00 2001 From: Cherik Date: Sun, 29 May 2022 12:44:21 +0430 Subject: [PATCH 205/257] add fetchEthPriceAsync reducer --- src/features/subgraph/subgraph.services.ts | 40 ++++++++++++++++++++++ src/features/subgraph/subgraph.slice.ts | 5 +++ src/features/subgraph/subgraph.thunks.ts | 14 +++++++- 3 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/features/subgraph/subgraph.services.ts b/src/features/subgraph/subgraph.services.ts index 582e4c3038..79845d7808 100644 --- a/src/features/subgraph/subgraph.services.ts +++ b/src/features/subgraph/subgraph.services.ts @@ -4,6 +4,7 @@ import { transformSubgraphData } from '@/lib/subgraph/subgraphDataTransform'; import { SubgraphQueryBuilder } from '@/lib/subgraph/subgraphQueryBuilder'; import { fetchSubgraph } from '@/services/subgraph.service'; import { defaultSubgraphValues } from './subgraph.slice'; +import { getRequest } from '@/helpers/requests'; export const fetchMainnetInfo = async (userAddress = '') => { try { @@ -40,3 +41,42 @@ export const fetchXDaiInfo = async (userAddress = '') => { return defaultSubgraphValues; } }; + +export const fetchUniswapSubgraphTokenPrice = async ( + subgraphUrl: string | undefined, + tokenAddress: string, +): Promise => { + if (!subgraphUrl || !tokenAddress) return '0'; + + try { + const query = ` + { + token(id:"${tokenAddress.toLowerCase()}") { + derivedETH + } + } + `; + const body = { query }; + const res = await fetch(subgraphUrl, { + method: 'POST', + body: JSON.stringify(body), + }); + const { data } = await res.json(); + return data?.token?.derivedETH || '0'; + } catch (e) { + console.error('Error fetching token price:', tokenAddress, e); + captureException(e, { + tags: { + section: 'fetUniswapSubgraphTokenPrice', + }, + }); + return '0'; + } +}; + +export const fetchEthPrice = async (): Promise => { + const res = await getRequest( + 'https://feathers.giveth.io/conversionRates?from=ETH&to=USD&interval=hourly', + ); + return res.rate; +}; diff --git a/src/features/subgraph/subgraph.slice.ts b/src/features/subgraph/subgraph.slice.ts index 4c798123ba..b92f5c4c61 100644 --- a/src/features/subgraph/subgraph.slice.ts +++ b/src/features/subgraph/subgraph.slice.ts @@ -5,6 +5,7 @@ import { fetchCurrentInfoAsync, fetchXDaiInfoAsync, fetchMainnetInfoAsync, + fetchEthPriceAsync, } from './subgraph.thunks'; import type { ISubgraphState } from './subgraph.types'; @@ -62,6 +63,10 @@ export const subgraphSlice = createSlice({ .addCase(fetchMainnetInfoAsync.fulfilled, (state, action) => { state.status = 'idle'; state.mainnetValues = action.payload; + }) + .addCase(fetchEthPriceAsync.fulfilled, (state, action) => { + state.status = 'idle'; + state.ethPrice = action.payload; }); }, }); diff --git a/src/features/subgraph/subgraph.thunks.ts b/src/features/subgraph/subgraph.thunks.ts index 4a310ed269..652e5f1f05 100644 --- a/src/features/subgraph/subgraph.thunks.ts +++ b/src/features/subgraph/subgraph.thunks.ts @@ -1,6 +1,10 @@ import { createAsyncThunk } from '@reduxjs/toolkit'; import config from '@/configuration'; -import { fetchXDaiInfo, fetchMainnetInfo } from './subgraph.services'; +import { + fetchXDaiInfo, + fetchMainnetInfo, + fetchEthPrice, +} from './subgraph.services'; import { ICurrentInfo } from './subgraph.types'; export const fetchXDaiInfoAsync = createAsyncThunk( @@ -32,3 +36,11 @@ export const fetchCurrentInfoAsync = createAsyncThunk( return { response, chainId: props.chainId }; }, ); + +export const fetchEthPriceAsync = createAsyncThunk( + 'subgraph/fetchEthPrice', + async () => { + const rate = await fetchEthPrice(); + return rate; + }, +); From bb399e24ea33aa5c1b65b64679d1d0232be5c8da Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 01:13:03 +0430 Subject: [PATCH 206/257] remove price from subgraph --- src/features/subgraph/subgraph.services.ts | 40 ---------------------- src/features/subgraph/subgraph.slice.ts | 17 --------- src/features/subgraph/subgraph.thunks.ts | 14 +------- 3 files changed, 1 insertion(+), 70 deletions(-) diff --git a/src/features/subgraph/subgraph.services.ts b/src/features/subgraph/subgraph.services.ts index 79845d7808..582e4c3038 100644 --- a/src/features/subgraph/subgraph.services.ts +++ b/src/features/subgraph/subgraph.services.ts @@ -4,7 +4,6 @@ import { transformSubgraphData } from '@/lib/subgraph/subgraphDataTransform'; import { SubgraphQueryBuilder } from '@/lib/subgraph/subgraphQueryBuilder'; import { fetchSubgraph } from '@/services/subgraph.service'; import { defaultSubgraphValues } from './subgraph.slice'; -import { getRequest } from '@/helpers/requests'; export const fetchMainnetInfo = async (userAddress = '') => { try { @@ -41,42 +40,3 @@ export const fetchXDaiInfo = async (userAddress = '') => { return defaultSubgraphValues; } }; - -export const fetchUniswapSubgraphTokenPrice = async ( - subgraphUrl: string | undefined, - tokenAddress: string, -): Promise => { - if (!subgraphUrl || !tokenAddress) return '0'; - - try { - const query = ` - { - token(id:"${tokenAddress.toLowerCase()}") { - derivedETH - } - } - `; - const body = { query }; - const res = await fetch(subgraphUrl, { - method: 'POST', - body: JSON.stringify(body), - }); - const { data } = await res.json(); - return data?.token?.derivedETH || '0'; - } catch (e) { - console.error('Error fetching token price:', tokenAddress, e); - captureException(e, { - tags: { - section: 'fetUniswapSubgraphTokenPrice', - }, - }); - return '0'; - } -}; - -export const fetchEthPrice = async (): Promise => { - const res = await getRequest( - 'https://feathers.giveth.io/conversionRates?from=ETH&to=USD&interval=hourly', - ); - return res.rate; -}; diff --git a/src/features/subgraph/subgraph.slice.ts b/src/features/subgraph/subgraph.slice.ts index b92f5c4c61..3ddcf26f59 100644 --- a/src/features/subgraph/subgraph.slice.ts +++ b/src/features/subgraph/subgraph.slice.ts @@ -5,7 +5,6 @@ import { fetchCurrentInfoAsync, fetchXDaiInfoAsync, fetchMainnetInfoAsync, - fetchEthPriceAsync, } from './subgraph.thunks'; import type { ISubgraphState } from './subgraph.types'; @@ -20,23 +19,11 @@ const initialState: { currentValues: ISubgraphState; mainnetValues: ISubgraphState; xDaiValues: ISubgraphState; - ethPrice: string; - givPrice: string; - mainnetThirdPartyTokensPrice: { - [tokenAddress: string]: string; - }; - xDaiThirdPartyTokensPrice: { - [tokenAddress: string]: string; - }; status: string; } = { currentValues: defaultSubgraphValues, mainnetValues: defaultSubgraphValues, xDaiValues: defaultSubgraphValues, - ethPrice: '0', - givPrice: '0', - mainnetThirdPartyTokensPrice: {}, - xDaiThirdPartyTokensPrice: {}, status: 'idle', }; @@ -63,10 +50,6 @@ export const subgraphSlice = createSlice({ .addCase(fetchMainnetInfoAsync.fulfilled, (state, action) => { state.status = 'idle'; state.mainnetValues = action.payload; - }) - .addCase(fetchEthPriceAsync.fulfilled, (state, action) => { - state.status = 'idle'; - state.ethPrice = action.payload; }); }, }); diff --git a/src/features/subgraph/subgraph.thunks.ts b/src/features/subgraph/subgraph.thunks.ts index 652e5f1f05..4a310ed269 100644 --- a/src/features/subgraph/subgraph.thunks.ts +++ b/src/features/subgraph/subgraph.thunks.ts @@ -1,10 +1,6 @@ import { createAsyncThunk } from '@reduxjs/toolkit'; import config from '@/configuration'; -import { - fetchXDaiInfo, - fetchMainnetInfo, - fetchEthPrice, -} from './subgraph.services'; +import { fetchXDaiInfo, fetchMainnetInfo } from './subgraph.services'; import { ICurrentInfo } from './subgraph.types'; export const fetchXDaiInfoAsync = createAsyncThunk( @@ -36,11 +32,3 @@ export const fetchCurrentInfoAsync = createAsyncThunk( return { response, chainId: props.chainId }; }, ); - -export const fetchEthPriceAsync = createAsyncThunk( - 'subgraph/fetchEthPrice', - async () => { - const rate = await fetchEthPrice(); - return rate; - }, -); From 50c12486b4320791ea20172d9e4edaaf5e8482f5 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 01:13:46 +0430 Subject: [PATCH 207/257] add authorization to gqlRequest --- src/helpers/requests.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/helpers/requests.ts b/src/helpers/requests.ts index 5dd95772d7..5c8a3cdd26 100644 --- a/src/helpers/requests.ts +++ b/src/helpers/requests.ts @@ -79,6 +79,7 @@ export function postRequest( export function gqlRequest( url: string, + authorization: boolean = false, query: string, variables: {} = {}, additionalHeaders: HeadersInit = {}, @@ -86,7 +87,7 @@ export function gqlRequest( ) { return postRequest( url, - true, + authorization, { query, variables, From 35d6c1fc96d4121a215c17148e3ed49956f4adb9 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 01:14:18 +0430 Subject: [PATCH 208/257] make uniswapV2Subgraph required --- src/config/production.ts | 2 ++ src/types/config.ts | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/config/production.ts b/src/config/production.ts index 3dbae335f0..4f2047a527 100644 --- a/src/config/production.ts +++ b/src/config/production.ts @@ -103,6 +103,8 @@ const config: EnvConfig = { active: false, }, ], + uniswapV2Subgraph: + 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2', regenStreams: [], regenFarms: [], }, diff --git a/src/types/config.ts b/src/types/config.ts index a7a918cdf5..2002f37ea2 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -118,7 +118,7 @@ export interface BasicNetworkConfig { | BalancerPoolStakingConfig | UniswapV3PoolStakingConfig >; - uniswapV2Subgraph?: string; + uniswapV2Subgraph: string; regenStreams: RegenStreamConfig[]; regenFarms: RegenPoolStakingConfig[]; From e9f4925c8747fbd89ae56dec76de9b7d70568f70 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 01:14:40 +0430 Subject: [PATCH 209/257] add price queries --- src/features/price/price.queries.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/features/price/price.queries.ts diff --git a/src/features/price/price.queries.ts b/src/features/price/price.queries.ts new file mode 100644 index 0000000000..4185a4b6dc --- /dev/null +++ b/src/features/price/price.queries.ts @@ -0,0 +1,18 @@ +export const FETCH_MAINNET_TOKEN_PRICE = `query FetchMainnetTokenPrice($tokenId: String!, $daiId:String){ + token: token(id: $tokenId) { + id + symbol + derivedETH + } + daitoken: token(id: $daiId) { + id + symbol + derivedETH + } + }`; + +export const FETCH_GNOSIS_TOKEN_PRICE = `query FetchGnosisTokenPrice($id: String!){ + token(id: $id) { + derivedETH + } + }`; From 1eb4d069b9b67d34133bc20cc71594c94cabd412 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 01:15:02 +0430 Subject: [PATCH 210/257] add price service --- src/features/price/price.services.ts | 50 ++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/features/price/price.services.ts diff --git a/src/features/price/price.services.ts b/src/features/price/price.services.ts new file mode 100644 index 0000000000..8ce5ae01eb --- /dev/null +++ b/src/features/price/price.services.ts @@ -0,0 +1,50 @@ +import BigNumber from 'bignumber.js'; +import config from '@/configuration'; +import { getRequest, gqlRequest } from '@/helpers/requests'; +import { + FETCH_MAINNET_TOKEN_PRICE, + FETCH_GNOSIS_TOKEN_PRICE, +} from './price.queries'; + +export const fetchEthPrice = async (): Promise => { + const res = await getRequest( + 'https://feathers.giveth.io/conversionRates?from=ETH&to=USD&interval=hourly', + ); + return res.rate; +}; + +export const fetchMainnetTokenPrice = async ( + tokenId: string, +): Promise => { + const query = FETCH_MAINNET_TOKEN_PRICE; + const variables = { + tokenId: tokenId.toLowerCase(), + daiId: '0x6b175474e89094c44da98b954eedeac495271d0f'.toLowerCase(), + }; + const { data } = await gqlRequest( + config.MAINNET_CONFIG.uniswapV2Subgraph, + false, + query, + variables, + ); + const givEth = new BigNumber(data.givtoken.derivedETH); + const daiEth = new BigNumber(data.daitoken.derivedETH); + return givEth.div(daiEth).toString(); +}; + +export const fetchGnosisTokenPrice = async ( + tokenId: string, +): Promise => { + const query = FETCH_GNOSIS_TOKEN_PRICE; + const variables = { + id: tokenId.toLowerCase(), + }; + const { data } = await gqlRequest( + config.XDAI_CONFIG.uniswapV2Subgraph, + false, + query, + variables, + ); + console.log('data', data); + return '10'; +}; From f53dc538510e4b4139236313ff2d68810f56c6dd Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 01:15:48 +0430 Subject: [PATCH 211/257] add price thunks --- src/features/price/price.thunks.ts | 72 ++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 src/features/price/price.thunks.ts diff --git a/src/features/price/price.thunks.ts b/src/features/price/price.thunks.ts new file mode 100644 index 0000000000..fbd7f6d404 --- /dev/null +++ b/src/features/price/price.thunks.ts @@ -0,0 +1,72 @@ +import { createAsyncThunk } from '@reduxjs/toolkit'; +import config from '@/configuration'; +import { + fetchEthPrice, + fetchGnosisTokenPrice, + fetchMainnetTokenPrice, +} from './price.services'; + +export const fetchEthPriceAsync = createAsyncThunk( + 'subgraph/fetchEthPrice', + async () => { + const rate = await fetchEthPrice(); + return rate; + }, +); + +export const fetchGIVPriceAsync = createAsyncThunk( + 'subgraph/fetchGIVPrice', + async (chainId: number) => { + if (chainId === config.XDAI_NETWORK_NUMBER) { + return await fetchGnosisTokenPrice( + config.XDAI_CONFIG.TOKEN_ADDRESS, + ); + } else if (chainId === config.MAINNET_NETWORK_NUMBER) { + return await fetchMainnetTokenPrice( + config.MAINNET_CONFIG.TOKEN_ADDRESS, + ); + } + }, +); + +export const fetchMainnetThirdPartyTokensPriceAsync = createAsyncThunk( + 'subgraph/fetchMainnetThirdPartyTokensPrice', + async () => { + const promises: Promise[] = []; + config.MAINNET_CONFIG.regenStreams.forEach(streamConfig => { + const tokenAddress = + streamConfig.tokenAddressOnUniswapV2.toLowerCase(); + promises.push(fetchMainnetTokenPrice(tokenAddress)); + }); + return Promise.all(promises).then(prices => { + let res: { [x: string]: string } = {}; + config.MAINNET_CONFIG.regenStreams.forEach((streamConfig, idx) => { + const tokenAddress = + streamConfig.tokenAddressOnUniswapV2.toLowerCase(); + res[tokenAddress] = prices[idx]; + }); + return res; + }); + }, +); + +export const fetchGnosisThirdPartyTokensPriceAsync = createAsyncThunk( + 'subgraph/fetchGnosisThirdPartyTokensPric', + async () => { + const promises: Promise[] = []; + config.XDAI_CONFIG.regenStreams.forEach(streamConfig => { + const tokenAddress = + streamConfig.tokenAddressOnUniswapV2.toLowerCase(); + promises.push(fetchGnosisTokenPrice(tokenAddress)); + }); + return Promise.all(promises).then(prices => { + let res: { [x: string]: string } = {}; + config.XDAI_CONFIG.regenStreams.forEach((streamConfig, idx) => { + const tokenAddress = + streamConfig.tokenAddressOnUniswapV2.toLowerCase(); + res[tokenAddress] = prices[idx]; + }); + return res; + }); + }, +); From 3564cd02082ac8852ca005323a90cac204e14c75 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 01:20:47 +0430 Subject: [PATCH 212/257] add price slice --- src/features/price/price.slice.ts | 52 ++++++++++++++++++++++++++++++ src/features/price/price.thunks.ts | 7 ++-- 2 files changed, 54 insertions(+), 5 deletions(-) create mode 100644 src/features/price/price.slice.ts diff --git a/src/features/price/price.slice.ts b/src/features/price/price.slice.ts new file mode 100644 index 0000000000..f9a9bcf55e --- /dev/null +++ b/src/features/price/price.slice.ts @@ -0,0 +1,52 @@ +import { createSlice } from '@reduxjs/toolkit'; +import { + fetchEthPriceAsync, + fetchGIVPriceAsync, + fetchGnosisThirdPartyTokensPriceAsync, + fetchMainnetThirdPartyTokensPriceAsync, +} from './price.thunks'; + +const initialState: { + ethPrice: string; + givPrice: string; + mainnetThirdPartyTokensPrice: { + [tokenAddress: string]: string; + }; + xDaiThirdPartyTokensPrice: { + [tokenAddress: string]: string; + }; +} = { + ethPrice: '0', + givPrice: '0', + mainnetThirdPartyTokensPrice: {}, + xDaiThirdPartyTokensPrice: {}, +}; + +export const priceSlice = createSlice({ + name: 'price', + initialState, + reducers: {}, + extraReducers: builder => { + builder + .addCase(fetchEthPriceAsync.fulfilled, (state, action) => { + state.ethPrice = action.payload; + }) + .addCase(fetchGIVPriceAsync.fulfilled, (state, action) => { + state.givPrice = action.payload; + }) + .addCase( + fetchMainnetThirdPartyTokensPriceAsync.fulfilled, + (state, action) => { + state.mainnetThirdPartyTokensPrice = action.payload; + }, + ) + .addCase( + fetchGnosisThirdPartyTokensPriceAsync.fulfilled, + (state, action) => { + state.xDaiThirdPartyTokensPrice = action.payload; + }, + ); + }, +}); + +export default priceSlice.reducer; diff --git a/src/features/price/price.thunks.ts b/src/features/price/price.thunks.ts index fbd7f6d404..cfe80d9732 100644 --- a/src/features/price/price.thunks.ts +++ b/src/features/price/price.thunks.ts @@ -17,15 +17,12 @@ export const fetchEthPriceAsync = createAsyncThunk( export const fetchGIVPriceAsync = createAsyncThunk( 'subgraph/fetchGIVPrice', async (chainId: number) => { - if (chainId === config.XDAI_NETWORK_NUMBER) { - return await fetchGnosisTokenPrice( - config.XDAI_CONFIG.TOKEN_ADDRESS, - ); - } else if (chainId === config.MAINNET_NETWORK_NUMBER) { + if (chainId === config.MAINNET_NETWORK_NUMBER) { return await fetchMainnetTokenPrice( config.MAINNET_CONFIG.TOKEN_ADDRESS, ); } + return await fetchGnosisTokenPrice(config.XDAI_CONFIG.TOKEN_ADDRESS); }, ); From dccc91e4bd64e97fb9e87e67d4ee70f11649e0dd Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 01:21:01 +0430 Subject: [PATCH 213/257] add price to store --- src/features/store.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/features/store.ts b/src/features/store.ts index 13e39bf40d..328358ab30 100644 --- a/src/features/store.ts +++ b/src/features/store.ts @@ -3,11 +3,14 @@ import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit'; import subgraphReducer from './subgraph/subgraph.slice'; import modalReducer from './modal/modal.sclie'; import userReducer from './user/user.slice'; +import priceReducer from './price/price.slice'; + export const store = configureStore({ reducer: { subgraph: subgraphReducer, modal: modalReducer, user: userReducer, + price: priceReducer, }, }); From 65ead62843131554bb86c06bcbc5e78449c5d62c Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 01:28:55 +0430 Subject: [PATCH 214/257] add price controller --- src/components/controller/price.ctrl.tsx | 25 ++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 src/components/controller/price.ctrl.tsx diff --git a/src/components/controller/price.ctrl.tsx b/src/components/controller/price.ctrl.tsx new file mode 100644 index 0000000000..bc4028d94a --- /dev/null +++ b/src/components/controller/price.ctrl.tsx @@ -0,0 +1,25 @@ +import { useWeb3React } from '@web3-react/core'; +import { useEffect } from 'react'; +import { useAppDispatch } from '@/features/hooks'; +import { + fetchEthPriceAsync, + fetchGIVPriceAsync, + fetchGnosisThirdPartyTokensPriceAsync, + fetchMainnetThirdPartyTokensPriceAsync, +} from '@/features/price/price.thunks'; + +const PriceController = () => { + const dispatch = useAppDispatch(); + const { chainId } = useWeb3React(); + + useEffect(() => { + const _chainId = chainId ?? 0; + dispatch(fetchEthPriceAsync()); + dispatch(fetchGIVPriceAsync(_chainId)); + dispatch(fetchMainnetThirdPartyTokensPriceAsync()); + dispatch(fetchGnosisThirdPartyTokensPriceAsync()); + }, [chainId]); + return null; +}; + +export default PriceController; From ad9d4c02a71484edab4b9ab82ad82b025e6bb9d8 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 02:08:27 +0430 Subject: [PATCH 215/257] fix thunks name --- src/features/price/price.thunks.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/features/price/price.thunks.ts b/src/features/price/price.thunks.ts index cfe80d9732..b66e9106fc 100644 --- a/src/features/price/price.thunks.ts +++ b/src/features/price/price.thunks.ts @@ -7,7 +7,7 @@ import { } from './price.services'; export const fetchEthPriceAsync = createAsyncThunk( - 'subgraph/fetchEthPrice', + 'price/fetchEthPrice', async () => { const rate = await fetchEthPrice(); return rate; @@ -15,7 +15,7 @@ export const fetchEthPriceAsync = createAsyncThunk( ); export const fetchGIVPriceAsync = createAsyncThunk( - 'subgraph/fetchGIVPrice', + 'price/fetchGIVPrice', async (chainId: number) => { if (chainId === config.MAINNET_NETWORK_NUMBER) { return await fetchMainnetTokenPrice( @@ -27,7 +27,7 @@ export const fetchGIVPriceAsync = createAsyncThunk( ); export const fetchMainnetThirdPartyTokensPriceAsync = createAsyncThunk( - 'subgraph/fetchMainnetThirdPartyTokensPrice', + 'price/fetchMainnetThirdPartyTokensPrice', async () => { const promises: Promise[] = []; config.MAINNET_CONFIG.regenStreams.forEach(streamConfig => { @@ -48,7 +48,7 @@ export const fetchMainnetThirdPartyTokensPriceAsync = createAsyncThunk( ); export const fetchGnosisThirdPartyTokensPriceAsync = createAsyncThunk( - 'subgraph/fetchGnosisThirdPartyTokensPric', + 'price/fetchGnosisThirdPartyTokensPric', async () => { const promises: Promise[] = []; config.XDAI_CONFIG.regenStreams.forEach(streamConfig => { From 6957bd8b3ecc84742db4cb7ddae5220a98112095 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 02:08:37 +0430 Subject: [PATCH 216/257] add controller to _app --- pages/_app.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pages/_app.tsx b/pages/_app.tsx index d6ae6e99ca..c320ea4f35 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -18,6 +18,7 @@ import { store } from '@/features/store'; import SubgraphController from '@/components/controller/subgraph.ctrl'; import UserController from '@/components/controller/user.ctrl'; import ModalController from '@/components/controller/modal.ctrl'; +import PriceController from '@/components/controller/price.ctrl'; import type { AppProps } from 'next/app'; function getLibrary(provider: ExternalProvider) { @@ -60,6 +61,7 @@ function MyApp({ Component, pageProps }: AppProps) { + From a1532fcf3c931fea8bfea9431ce9d589360b0c86 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 02:09:27 +0430 Subject: [PATCH 217/257] add price in RegenStreamCard --- src/components/RegenStreamCard.tsx | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/components/RegenStreamCard.tsx b/src/components/RegenStreamCard.tsx index 83bb23bdc8..3df40135f8 100644 --- a/src/components/RegenStreamCard.tsx +++ b/src/components/RegenStreamCard.tsx @@ -29,9 +29,9 @@ import { IconFox } from '@/components/Icons/Fox'; import { IconCult } from '@/components/Icons/Cult'; import { Flex } from './styled-components/Flex'; import { HarvestAllModal } from './modals/HarvestAll'; -import { usePrice } from '@/context/price.context'; import { useAppSelector } from '@/features/hooks'; import useRegenTokenDistroHelper from '@/hooks/useRegenTokenDistroHelper'; +import config from '@/configuration'; interface RegenStreamProps { network: number; @@ -68,13 +68,16 @@ export const RegenStreamCard: FC = ({ ); const currentValues = useAppSelector(state => state.subgraph.currentValues); const { balances } = currentValues; - - const { getTokenPrice } = usePrice(); + const { mainnetThirdPartyTokensPrice, xDaiThirdPartyTokensPrice } = + useAppSelector(state => state.price); useEffect(() => { - const price = getTokenPrice( - streamConfig.tokenAddressOnUniswapV2, - network, + const currentPrice = + network === config.MAINNET_NETWORK_NUMBER + ? mainnetThirdPartyTokensPrice + : xDaiThirdPartyTokensPrice; + const price = new BigNumber( + currentPrice[streamConfig.tokenAddressOnUniswapV2], ); if (!price || price.isNaN()) return; @@ -83,10 +86,11 @@ export const RegenStreamCard: FC = ({ )).toFixed(2); setUSDAmount(usd); }, [ - getTokenPrice, rewardLiquidPart, network, streamConfig.tokenAddressOnUniswapV2, + mainnetThirdPartyTokensPrice, + xDaiThirdPartyTokensPrice, ]); useEffect(() => { switch (streamConfig.type) { From dc888bc445db7ff37c288e751e4066e177d9fbab Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 02:09:45 +0430 Subject: [PATCH 218/257] add price in RewardCard --- src/components/RewardCard.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/components/RewardCard.tsx b/src/components/RewardCard.tsx index 26243bf74a..8401bcf504 100644 --- a/src/components/RewardCard.tsx +++ b/src/components/RewardCard.tsx @@ -21,8 +21,8 @@ import { IconEthereum } from './Icons/Eth'; import { IconGnosisChain } from './Icons/GnosisChain'; import { WhatisStreamModal } from '@/components/modals/WhatisStream'; import { WrongNetworkInnerModal } from './modals/WrongNetwork'; -import { usePrice } from '@/context/price.context'; import useGIVTokenDistroHelper from '@/hooks/useGIVTokenDistroHelper'; +import { useAppSelector } from '@/features/hooks'; interface IRewardCardProps { title?: string; liquidAmount: ethers.BigNumber; @@ -57,10 +57,10 @@ export const RewardCard: FC = ({ const [usdAmount, setUSDAmount] = useState('0'); const [showWhatIsGIVstreamModal, setShowWhatIsGIVstreamModal] = useState(false); - const { givPrice } = usePrice(); + const givPrice = useAppSelector(state => state.price.givPrice); const { givTokenDistroHelper } = useGIVTokenDistroHelper(); useEffect(() => { - const price = tokenPrice || givPrice; + const price = tokenPrice || new BigNumber(givPrice); if (!price || price.isNaN()) return; const usd = (+ethers.utils.formatEther( From e284accd7fa37d064ae738ff1b00fc2755a50542 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 02:09:56 +0430 Subject: [PATCH 219/257] add price in GIVdropHarvestModal --- src/components/modals/GIVdropHarvestModal.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/components/modals/GIVdropHarvestModal.tsx b/src/components/modals/GIVdropHarvestModal.tsx index 8f5443e201..2dc1ae936f 100644 --- a/src/components/modals/GIVdropHarvestModal.tsx +++ b/src/components/modals/GIVdropHarvestModal.tsx @@ -44,7 +44,6 @@ import { showFailedClaim, } from '../toasts/claim'; import config from '@/configuration'; -import { usePrice } from '@/context/price.context'; import { IModal } from '@/types/common'; import { useAppSelector } from '@/features/hooks'; import type { TransactionResponse } from '@ethersproject/providers'; @@ -93,7 +92,7 @@ export const GIVdropHarvestModal: FC = ({ ); const { givTokenDistroHelper } = useGIVTokenDistroHelper(); const { balances } = useAppSelector(state => state.subgraph.currentValues); - const { givPrice } = usePrice(); + const givPrice = useAppSelector(state => state.price.givPrice); const { account, library } = useWeb3React(); @@ -123,7 +122,8 @@ export const GIVdropHarvestModal: FC = ({ }, [givdropAmount, givTokenDistroHelper, claimableNow, givBackLiquidPart]); const calcUSD = (amount: string) => { - return givPrice.isNaN() ? '0' : givPrice.times(amount).toFixed(2); + const _givPrice = new BigNumber(givPrice); + return _givPrice.isNaN() ? '0' : _givPrice.times(amount).toFixed(2); }; const onClaim = async () => { From 1c469fcf0da9896dd7a522efbf5dac62d3464c4c Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 02:10:06 +0430 Subject: [PATCH 220/257] add price in HarvestAllModal --- src/components/modals/HarvestAll.tsx | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/components/modals/HarvestAll.tsx b/src/components/modals/HarvestAll.tsx index 443c2255ed..112931a8ae 100644 --- a/src/components/modals/HarvestAll.tsx +++ b/src/components/modals/HarvestAll.tsx @@ -58,7 +58,6 @@ import { claimReward, fetchAirDropClaimData } from '@/lib/claim'; import config from '@/configuration'; import { IconWithTooltip } from '../IconWithToolTip'; import { AmountBoxWithPrice } from '@/components/AmountBoxWithPrice'; -import { usePrice } from '@/context/price.context'; import { getPoolIconWithName } from '../cards/BaseStakingCard'; import { IModal } from '@/types/common'; import { useAppSelector } from '@/features/hooks'; @@ -109,7 +108,11 @@ export const HarvestAllModal: FC = ({ const [state, setState] = useState(HarvestStates.HARVEST); const tokenSymbol = regenStreamConfig?.rewardTokenSymbol || 'GIV'; const { balances } = useAppSelector(state => state.subgraph.currentValues); - const { givPrice, getTokenPrice } = usePrice(); + const { + mainnetThirdPartyTokensPrice, + xDaiThirdPartyTokensPrice, + givPrice, + } = useAppSelector(state => state.price); const { account, library } = useWeb3React(); const [txHash, setTxHash] = useState(''); //GIVdrop TODO: Should we show Givdrop in new design? @@ -138,10 +141,15 @@ export const HarvestAllModal: FC = ({ : BN(balances.givbackLiquidPart); }, [regenStreamConfig, balances.givbackLiquidPart]); const tokenPrice = useMemo(() => { - return regenStreamConfig - ? getTokenPrice(regenStreamConfig.tokenAddressOnUniswapV2, network) + const currentPrice = + network === config.MAINNET_NETWORK_NUMBER + ? mainnetThirdPartyTokensPrice + : xDaiThirdPartyTokensPrice; + const price = regenStreamConfig + ? currentPrice[regenStreamConfig.tokenAddressOnUniswapV2] : givPrice; - }, [getTokenPrice, givPrice, network, regenStreamConfig]); + return new BigNumber(price); + }, [givPrice, network, regenStreamConfig]); useEffect(() => { if (!tokenDistroHelper) return; @@ -290,7 +298,7 @@ export const HarvestAllModal: FC = ({ const modalTitle = regenStreamConfig ? 'RegenFarm Rewards' : title; const calcUSD = (amount: string) => { - const price = tokenPrice || givPrice; + const price = tokenPrice || new BigNumber(givPrice); return price.isNaN() ? '0' : price.times(amount).toFixed(2); }; From 6a3b58f52d782924041652f3774d9fbbaef4e47f Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 02:10:27 +0430 Subject: [PATCH 221/257] add price in CryptoDonation --- src/components/views/donate/CryptoDonation.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/components/views/donate/CryptoDonation.tsx b/src/components/views/donate/CryptoDonation.tsx index 050d0ca704..ad17b7ea57 100644 --- a/src/components/views/donate/CryptoDonation.tsx +++ b/src/components/views/donate/CryptoDonation.tsx @@ -25,7 +25,6 @@ import { InsufficientFundModal } from '@/components/modals/InsufficientFund'; import { IProject } from '@/apollo/types/types'; import { fetchPrice } from '@/services/token'; import { switchNetwork } from '@/lib/wallet'; -import { usePrice } from '@/context/price.context'; import GeminiModal from './GeminiModal'; import config from '@/configuration'; import TokenPicker from './TokenPicker'; @@ -84,7 +83,7 @@ const CryptoDonation = (props: { const { isEnabled, isSignedIn, balance } = useAppSelector( state => state.user, ); - const { ethPrice } = usePrice(); + const ethPrice = useAppSelector(state => state.price.ethPrice); const { project, setSuccessDonation } = props; const { organization, verified, id: projectId, status } = project; From 55a6038449110b1ad14c44f1f87991bb8b41cfe4 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 10:26:58 +0430 Subject: [PATCH 222/257] fix production subgraphAddress --- src/config/production.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config/production.ts b/src/config/production.ts index 4f2047a527..05fd406ea1 100644 --- a/src/config/production.ts +++ b/src/config/production.ts @@ -126,7 +126,7 @@ const config: EnvConfig = { blockExplorerName: ['Blockscout'], blockExplorerUrls: ['https://blockscout.com/xdai/mainnet'], subgraphAddress: - 'https://api.thegraph.com/subgraphs/name/giveth/giveth-economy-xdai', + 'https://api.thegraph.com/subgraphs/name/aminlatifi/giveth-economy-xdai', TOKEN_ADDRESS: '0x4f4F9b8D5B4d0Dc10506e5551B0513B61fD59e75', MERKLE_ADDRESS: '0xFad63adEFb8203F7605F25f6a921c8bf45604A5e', From ab34a877620d277ee9ad1d148b08bdafc79d67a8 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 10:27:36 +0430 Subject: [PATCH 223/257] return correct number from fetchGnosisTokenPrice --- src/features/price/price.services.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/features/price/price.services.ts b/src/features/price/price.services.ts index 8ce5ae01eb..ebeaaacac4 100644 --- a/src/features/price/price.services.ts +++ b/src/features/price/price.services.ts @@ -45,6 +45,5 @@ export const fetchGnosisTokenPrice = async ( query, variables, ); - console.log('data', data); - return '10'; + return data?.token?.derivedETH || '0'; }; From 6691a8c399ceb1f2b2854b9d0c9f52736d0e1367 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 10:36:59 +0430 Subject: [PATCH 224/257] convert gqlRequest to backendGQLRequest --- src/hooks/usePurpleList.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/hooks/usePurpleList.tsx b/src/hooks/usePurpleList.tsx index f40eddaec6..4e8d7ff066 100644 --- a/src/hooks/usePurpleList.tsx +++ b/src/hooks/usePurpleList.tsx @@ -2,7 +2,7 @@ import { useWeb3React } from '@web3-react/core'; import { useEffect, useState } from 'react'; import { CHECK_PURPLE_LIST } from '@/apollo/gql/gqlPurpleList'; import { ICheckPurpleListGQL } from '@/apollo/types/gqlTypes'; -import { gqlRequest } from '@/helpers/requests'; +import { backendGQLRequest } from '@/helpers/requests'; export default function usePurpleList() { const { account: address } = useWeb3React(); @@ -11,7 +11,7 @@ export default function usePurpleList() { useEffect(() => { if (address) { - gqlRequest(CHECK_PURPLE_LIST, { address }) + backendGQLRequest(CHECK_PURPLE_LIST, { address }) .then((res: ICheckPurpleListGQL) => { setIsPurpleList(res.data?.walletAddressIsPurpleListed); }) From d2860fa05423fdec206e24d8a6a2ba3bdefa8e64 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 11:53:46 +0430 Subject: [PATCH 225/257] use tokenAddressOnUniswapV2 for price --- src/config/development.ts | 2 ++ src/config/production.ts | 2 ++ src/features/price/price.thunks.ts | 6 ++++-- src/types/config.ts | 1 + 4 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/config/development.ts b/src/config/development.ts index e7c71770f6..6f0d9718dd 100644 --- a/src/config/development.ts +++ b/src/config/development.ts @@ -39,6 +39,7 @@ const config: EnvConfig = { 'https://api.thegraph.com/subgraphs/name/giveth/giveth-economy-kovan-staging', TOKEN_ADDRESS: '0x29434A25abd94AE882aA883eea81585Aaa5b078D', + tokenAddressOnUniswapV2: '0x900db999074d9277c5da2a43f252d74366230da0', WETH_TOKEN_ADDRESS: '0xd0a1e359811322d97991e03f863a0c30c2cf029c', TOKEN_DISTRO_ADDRESS: '0x2C84Ab41b53C52959a794830fe296Fd717c33337', GIV: { @@ -165,6 +166,7 @@ const config: EnvConfig = { 'https://api.thegraph.com/subgraphs/name/giveth/giveth-economy-xdai-staging', TOKEN_ADDRESS: '0x83a8eea6427985C523a0c4d9d3E62C051B6580d3', + tokenAddressOnUniswapV2: '0x4f4F9b8D5B4d0Dc10506e5551B0513B61fD59e75', MERKLE_ADDRESS: '0xc87403C70c9FBfb594d98d3B5E695BBE4C694188', TOKEN_DISTRO_ADDRESS: '0x18a46865AAbAf416a970eaA8625CFC430D2364A1', diff --git a/src/config/production.ts b/src/config/production.ts index 05fd406ea1..ee4035f850 100644 --- a/src/config/production.ts +++ b/src/config/production.ts @@ -38,6 +38,7 @@ const config: EnvConfig = { 'https://api.thegraph.com/subgraphs/name/aminlatifi/giveth-economy', TOKEN_ADDRESS: '0x900db999074d9277c5da2a43f252d74366230da0', + tokenAddressOnUniswapV2: '0x900db999074d9277c5da2a43f252d74366230da0', WETH_TOKEN_ADDRESS: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', TOKEN_DISTRO_ADDRESS: '0x87dE995F6744B75bBe0255A973081142aDb61f4d', GIV: { @@ -129,6 +130,7 @@ const config: EnvConfig = { 'https://api.thegraph.com/subgraphs/name/aminlatifi/giveth-economy-xdai', TOKEN_ADDRESS: '0x4f4F9b8D5B4d0Dc10506e5551B0513B61fD59e75', + tokenAddressOnUniswapV2: '0x4f4F9b8D5B4d0Dc10506e5551B0513B61fD59e75', MERKLE_ADDRESS: '0xFad63adEFb8203F7605F25f6a921c8bf45604A5e', TOKEN_DISTRO_ADDRESS: '0xc0dbDcA66a0636236fAbe1B3C16B1bD4C84bB1E1', diff --git a/src/features/price/price.thunks.ts b/src/features/price/price.thunks.ts index b66e9106fc..3350718ae7 100644 --- a/src/features/price/price.thunks.ts +++ b/src/features/price/price.thunks.ts @@ -19,10 +19,12 @@ export const fetchGIVPriceAsync = createAsyncThunk( async (chainId: number) => { if (chainId === config.MAINNET_NETWORK_NUMBER) { return await fetchMainnetTokenPrice( - config.MAINNET_CONFIG.TOKEN_ADDRESS, + config.MAINNET_CONFIG.tokenAddressOnUniswapV2, ); } - return await fetchGnosisTokenPrice(config.XDAI_CONFIG.TOKEN_ADDRESS); + return await fetchGnosisTokenPrice( + config.XDAI_CONFIG.tokenAddressOnUniswapV2, + ); }, ); diff --git a/src/types/config.ts b/src/types/config.ts index 2002f37ea2..97d9ada2d4 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -98,6 +98,7 @@ export interface RegenStreamConfig { export interface BasicNetworkConfig { TOKEN_ADDRESS: string; + tokenAddressOnUniswapV2: string; // For price purpose TOKEN_DISTRO_ADDRESS: string; GIV: BasicStakingConfig; nodeUrl: string; From 518eed7e4af427e6208d21568d1ff85a70fd7be7 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 14:47:19 +0430 Subject: [PATCH 226/257] Update src/features/price/price.services.ts Co-authored-by: Amin Latifi --- src/features/price/price.services.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/features/price/price.services.ts b/src/features/price/price.services.ts index ebeaaacac4..6a5513108d 100644 --- a/src/features/price/price.services.ts +++ b/src/features/price/price.services.ts @@ -27,7 +27,7 @@ export const fetchMainnetTokenPrice = async ( query, variables, ); - const givEth = new BigNumber(data.givtoken.derivedETH); + const tokenEthPrice = new BigNumber(data.token.derivedETH); const daiEth = new BigNumber(data.daitoken.derivedETH); return givEth.div(daiEth).toString(); }; From 2f644def5c5def249318edc7c33fb59986dcb15f Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 14:47:29 +0430 Subject: [PATCH 227/257] Update src/features/price/price.services.ts Co-authored-by: Amin Latifi --- src/features/price/price.services.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/features/price/price.services.ts b/src/features/price/price.services.ts index 6a5513108d..788c52a16d 100644 --- a/src/features/price/price.services.ts +++ b/src/features/price/price.services.ts @@ -28,7 +28,7 @@ export const fetchMainnetTokenPrice = async ( variables, ); const tokenEthPrice = new BigNumber(data.token.derivedETH); - const daiEth = new BigNumber(data.daitoken.derivedETH); + const daiEthPrice = new BigNumber(data.daitoken.derivedETH); return givEth.div(daiEth).toString(); }; From 8c77ae90a3f3fd7ec66aa13661f37f3eb3da3d46 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 14:47:35 +0430 Subject: [PATCH 228/257] Update src/types/config.ts Co-authored-by: Amin Latifi --- src/types/config.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/types/config.ts b/src/types/config.ts index 97d9ada2d4..a8fd483b15 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -98,7 +98,7 @@ export interface RegenStreamConfig { export interface BasicNetworkConfig { TOKEN_ADDRESS: string; - tokenAddressOnUniswapV2: string; // For price purpose + tokenAddressOnUniswapV2: string; // For price purpose in test env, on production this must have the same value of `TOKEN_ADDRESS` TOKEN_DISTRO_ADDRESS: string; GIV: BasicStakingConfig; nodeUrl: string; From 381cbd36527db65172c8d379b8e7ee12074be910 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 14:51:32 +0430 Subject: [PATCH 229/257] update varible names --- src/features/price/price.services.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/features/price/price.services.ts b/src/features/price/price.services.ts index 788c52a16d..14a1e0d993 100644 --- a/src/features/price/price.services.ts +++ b/src/features/price/price.services.ts @@ -29,7 +29,7 @@ export const fetchMainnetTokenPrice = async ( ); const tokenEthPrice = new BigNumber(data.token.derivedETH); const daiEthPrice = new BigNumber(data.daitoken.derivedETH); - return givEth.div(daiEth).toString(); + return tokenEthPrice.div(daiEthPrice).toString(); }; export const fetchGnosisTokenPrice = async ( From e06d7bce55c02c6de3a0950ac3e62731b29a3c30 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 14:52:01 +0430 Subject: [PATCH 230/257] remoce price context file --- src/context/price.context.tsx | 237 ---------------------------------- 1 file changed, 237 deletions(-) delete mode 100644 src/context/price.context.tsx diff --git a/src/context/price.context.tsx b/src/context/price.context.tsx deleted file mode 100644 index 9175de5d74..0000000000 --- a/src/context/price.context.tsx +++ /dev/null @@ -1,237 +0,0 @@ -import { - createContext, - FC, - useCallback, - useContext, - useEffect, - useState, -} from 'react'; -import BigNumber from 'bignumber.js'; -import { useWeb3React } from '@web3-react/core'; -import { captureException } from '@sentry/nextjs'; -import { Zero } from '@/helpers/number'; -import config from '@/configuration'; -import { useLiquidityPositions } from '@/hooks/useLiquidityPositions'; -import { useAppSelector } from '@/features/hooks'; - -export interface IPriceContext { - givPrice: BigNumber; - getTokenPrice: (address: string, network: number) => BigNumber; - ethPrice: BigNumber; -} - -const priceDefaultValue: IPriceContext = { - givPrice: Zero, - getTokenPrice: () => Zero, - ethPrice: Zero, -}; - -const fetchUniswapSubgraphTokenPrice = async ( - subgraphUrl: string | undefined, - tokenAddress: string, -): Promise => { - if (!subgraphUrl || !tokenAddress) return Zero; - - try { - const query = ` - { - token(id:"${tokenAddress.toLowerCase()}") { - derivedETH - } - } - `; - const body = { query }; - const res = await fetch(subgraphUrl, { - method: 'POST', - body: JSON.stringify(body), - }); - const { data } = await res.json(); - return new BigNumber(data?.token?.derivedETH || 0); - } catch (e) { - console.error('Error fetching token price:', tokenAddress, e); - captureException(e, { - tags: { - section: 'fetUniswapSubgraphTokenPrice', - }, - }); - return Zero; - } -}; - -const PriceContext = createContext(priceDefaultValue); - -PriceContext.displayName = 'PriceContext'; - -export const PriceProvider: FC = ({ children }) => { - const { chainId } = useWeb3React(); - const xDaiValues = useAppSelector(state => state.subgraph.xDaiValues); - const { pool } = useLiquidityPositions(); - - const [currentPrice, setCurrentPrice] = useState(Zero); - const [mainnetPrice, setMainnetPrice] = useState(Zero); - const [xDaiPrice, setXDaiPrice] = useState(Zero); - const [ethPrice, setEthPrice] = useState(Zero); - const [mainnetThirdPartyTokensPrice, setMainnetThirdPartTokensPrice] = - useState<{ - [tokenAddress: string]: BigNumber; - }>({}); - const [xDaiThirdPartyTokensPrice, setXDaiThirdPartTokensPrice] = useState<{ - [tokenAddress: string]: BigNumber; - }>({}); - - const getTokenPrice = useCallback( - (tokenAddress: string, network: number): BigNumber => { - switch (network) { - case config.MAINNET_NETWORK_NUMBER: - return ( - mainnetThirdPartyTokensPrice[ - tokenAddress.toLowerCase() - ] || Zero - ); - - case config.XDAI_NETWORK_NUMBER: - return ( - xDaiThirdPartyTokensPrice[tokenAddress.toLowerCase()] || - Zero - ); - } - return Zero; - }, - [mainnetThirdPartyTokensPrice, xDaiThirdPartyTokensPrice], - ); - - useEffect(() => { - const { uniswapV2EthGivPair } = xDaiValues; - if (uniswapV2EthGivPair) { - const { token0, token1, reserve0, reserve1 } = uniswapV2EthGivPair; - const { TOKEN_ADDRESS } = config.XDAI_CONFIG; - - switch (TOKEN_ADDRESS.toLowerCase()) { - case token0.toLowerCase(): - setXDaiPrice( - ethPrice - .times(reserve1.toString()) - .div(reserve0.toString()), - ); - break; - case token1.toLowerCase(): - setXDaiPrice( - ethPrice - .times(reserve0.toString()) - .div(reserve1.toString()), - ); - break; - default: - console.error( - 'Non of UniswapV2Pair tokens is GIV, ', - uniswapV2EthGivPair, - ); - } - } - }, [xDaiValues, ethPrice]); - - useEffect(() => { - if (pool) { - const { token1, token0, token0Price, token1Price } = pool; - switch (config.MAINNET_CONFIG.TOKEN_ADDRESS.toLowerCase()) { - case token0.address.toLowerCase(): - setMainnetPrice(ethPrice.times(token0Price.toFixed(18))); - break; - - case token1.address.toLowerCase(): - setMainnetPrice(ethPrice.times(token1Price.toFixed(18))); - break; - - default: - console.error('Non of UniswapV3Pool tokens is GIV'); - } - } - }, [pool, ethPrice]); - - useEffect(() => { - // fetch('https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD') - fetch( - 'https://feathers.giveth.io/conversionRates?from=ETH&to=USD&interval=hourly', - ) - .then(async res => { - const data = await res.json(); - setEthPrice(new BigNumber(data.rate)); - }) - .catch(error => { - console.error( - 'Error on getting eth price from crypto-compare:', - error, - ); - captureException(error, { - tags: { - section: 'fetEthPrice', - }, - }); - }); - - const { MAINNET_CONFIG, XDAI_CONFIG } = config; - if (MAINNET_CONFIG.uniswapV2Subgraph) { - MAINNET_CONFIG.regenStreams.forEach(streamConfig => { - fetchUniswapSubgraphTokenPrice( - MAINNET_CONFIG.uniswapV2Subgraph, - streamConfig.tokenAddressOnUniswapV2, - ).then(price => - setMainnetThirdPartTokensPrice({ - ...mainnetThirdPartyTokensPrice, - [streamConfig.tokenAddressOnUniswapV2.toLowerCase()]: - price, - }), - ); - }); - } - if (XDAI_CONFIG.uniswapV2Subgraph) { - XDAI_CONFIG.regenStreams.forEach(streamConfig => { - fetchUniswapSubgraphTokenPrice( - XDAI_CONFIG.uniswapV2Subgraph, - streamConfig.tokenAddressOnUniswapV2, - ).then(price => { - setXDaiThirdPartTokensPrice({ - ...xDaiThirdPartyTokensPrice, - [streamConfig.tokenAddressOnUniswapV2.toLowerCase()]: - price, - }); - }); - }); - } - }, []); - - useEffect(() => { - switch (chainId) { - case config.XDAI_NETWORK_NUMBER: - setCurrentPrice(xDaiPrice); - break; - - case config.MAINNET_NETWORK_NUMBER: - default: - setCurrentPrice(mainnetPrice); - break; - } - }, [chainId, xDaiPrice, mainnetPrice]); - - return ( - - {children} - - ); -}; - -export function usePrice() { - const context = useContext(PriceContext); - - if (!context) { - throw new Error('Price balance context not found!'); - } - - return context; -} From af4f4f9476b9ad8369f0b541ebf540a28dc3e60c Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 20:29:20 +0430 Subject: [PATCH 231/257] fix compare address --- src/lib/helpers.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/lib/helpers.ts b/src/lib/helpers.ts index 82cbd50d77..c353efcd29 100644 --- a/src/lib/helpers.ts +++ b/src/lib/helpers.ts @@ -121,6 +121,7 @@ export const compareAddresses = ( add1: string | undefined | null, add2: string | undefined | null, ) => { + if (!add1 || !add2) return false; return add1?.toLowerCase() === add2?.toLowerCase(); }; From 7edd0b7fad7f211d020abb6d2706af3b8a4f0fd3 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 30 May 2022 20:29:33 +0430 Subject: [PATCH 232/257] remove user and token from local storage --- src/features/user/user.slice.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/features/user/user.slice.ts b/src/features/user/user.slice.ts index dc295782bb..8df2fb104f 100644 --- a/src/features/user/user.slice.ts +++ b/src/features/user/user.slice.ts @@ -59,13 +59,13 @@ export const userSlice = createSlice({ }; }>, ) => { - const localAddress = localStorage - .getItem(StorageLabel.USER) - ?.toLocaleLowerCase(); + const localAddress = localStorage.getItem( + StorageLabel.USER, + ); if ( compareAddresses( localAddress, - action.payload.data.userByAddress.walletAddress, + action.payload.data?.userByAddress?.walletAddress, ) ) { state.token = @@ -73,6 +73,9 @@ export const userSlice = createSlice({ undefined; } else { state.token = undefined; + state.isSignedIn = false; + localStorage.removeItem(StorageLabel.USER); + localStorage.removeItem(StorageLabel.TOKEN); } state.userData = action.payload.data?.userByAddress; }, From caa5dd163d550d9c7980d53bf515a8ee7f51d51c Mon Sep 17 00:00:00 2001 From: Mateo Daza Date: Mon, 30 May 2022 15:03:03 -0500 Subject: [PATCH 233/257] hotfix for #820 --- src/components/GIVfrens.tsx | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/components/GIVfrens.tsx b/src/components/GIVfrens.tsx index 42b6540730..6db01b7d13 100644 --- a/src/components/GIVfrens.tsx +++ b/src/components/GIVfrens.tsx @@ -23,6 +23,7 @@ import config from '@/configuration'; import { givEconomySupportedNetworks } from '@/lib/constants/constants'; import { RegenStreamCard } from './RegenStreamCard'; import { Flex } from './styled-components/Flex'; +import { InjectedConnector } from '@web3-react/injected-connector'; import { switchNetwork } from '@/lib/wallet'; interface IGIVfrensProps { @@ -107,8 +108,18 @@ export const GIVfrens: FC = ({ regenFarms, network }) => { }; const DAOChangeNetworkModal = ({ network }: IChangeNetworkModal) => { + const { account, activate } = useWeb3React(); const networkLabel = network === config.XDAI_NETWORK_NUMBER ? 'Gnosis chain' : 'Mainnet'; + + const checkWalletAndSwitchNetwork = async (network: number) => { + if (!account) { + await activate(new InjectedConnector({})); + } + if (account) { + await switchNetwork(network); + } + }; return ( @@ -119,7 +130,7 @@ const DAOChangeNetworkModal = ({ network }: IChangeNetworkModal) => { switchNetwork(network)} + onClick={() => checkWalletAndSwitchNetwork(network)} /> ); From 73a42d17f209edc8e2881b6a4f9fa316e55254ff Mon Sep 17 00:00:00 2001 From: Cherik Date: Tue, 31 May 2022 00:57:04 +0430 Subject: [PATCH 234/257] add more checks --- src/features/user/user.slice.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/features/user/user.slice.ts b/src/features/user/user.slice.ts index ebac825cb4..8df2fb104f 100644 --- a/src/features/user/user.slice.ts +++ b/src/features/user/user.slice.ts @@ -65,7 +65,7 @@ export const userSlice = createSlice({ if ( compareAddresses( localAddress, - action.payload.data.userByAddress?.walletAddress, + action.payload.data?.userByAddress?.walletAddress, ) ) { state.token = From ae1f16cf6434240a766081668ed865862a126e7a Mon Sep 17 00:00:00 2001 From: Cherik Date: Tue, 31 May 2022 00:59:34 +0430 Subject: [PATCH 235/257] fix import orders --- src/components/GIVfrens.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/GIVfrens.tsx b/src/components/GIVfrens.tsx index 6db01b7d13..1e76503727 100644 --- a/src/components/GIVfrens.tsx +++ b/src/components/GIVfrens.tsx @@ -9,6 +9,7 @@ import { } from '@giveth/ui-design-system'; import { useWeb3React } from '@web3-react/core'; import styled from 'styled-components'; +import { InjectedConnector } from '@web3-react/injected-connector'; import { RegenPoolStakingConfig } from '@/types/config'; import { DAOContainer, @@ -23,7 +24,6 @@ import config from '@/configuration'; import { givEconomySupportedNetworks } from '@/lib/constants/constants'; import { RegenStreamCard } from './RegenStreamCard'; import { Flex } from './styled-components/Flex'; -import { InjectedConnector } from '@web3-react/injected-connector'; import { switchNetwork } from '@/lib/wallet'; interface IGIVfrensProps { From f10be71d033552ceac44acd8871d9edb3f337056 Mon Sep 17 00:00:00 2001 From: mitch Date: Mon, 30 May 2022 16:14:33 -0600 Subject: [PATCH 236/257] add xdai icon to xdai givfarm --- src/components/Icons/xDAI.tsx | 15 +++++++++++++++ src/components/StakingPoolImages.tsx | 3 +++ src/config/development.ts | 6 +++--- 3 files changed, 21 insertions(+), 3 deletions(-) create mode 100644 src/components/Icons/xDAI.tsx diff --git a/src/components/Icons/xDAI.tsx b/src/components/Icons/xDAI.tsx new file mode 100644 index 0000000000..cf9638fec6 --- /dev/null +++ b/src/components/Icons/xDAI.tsx @@ -0,0 +1,15 @@ +import React, { FC } from 'react'; +import Image from 'next/image'; +import { ICurrencyIconProps } from './type'; + +export const IconxDAI: FC = ({ size = 16 }) => { + return ( + honeyswap + ); +}; diff --git a/src/components/StakingPoolImages.tsx b/src/components/StakingPoolImages.tsx index 0358c2265b..c912549a32 100644 --- a/src/components/StakingPoolImages.tsx +++ b/src/components/StakingPoolImages.tsx @@ -7,6 +7,7 @@ import { IconHoneyswap } from './Icons/Honeyswap'; import { IconFox } from '@/components/Icons/Fox'; import { IconDai } from '@/components/Icons/Dai'; import { IconElk } from '@/components/Icons/Elk'; +import { IconxDAI } from '@/components/Icons/xDAI'; import { IconCult } from '@/components/Icons/Cult'; interface IStakingPoolImagesProps { title: string; @@ -28,6 +29,8 @@ export const getCurIconWithName = (currency: string) => { return ; case 'CULT': return ; + case 'xDAI': + return ; default: break; } diff --git a/src/config/development.ts b/src/config/development.ts index 6f0d9718dd..08157a22ad 100644 --- a/src/config/development.ts +++ b/src/config/development.ts @@ -136,7 +136,7 @@ const config: EnvConfig = { regenFarmIntro: { title: 'CULT', description: `The purpose of CULT is to empower those building and contributing to our decentralized future. - Our society makes it as difficult as possible to break away from societal, economic and other norms, and CULT serves to fund and support those who are working to take back our future. CULT is a reminder that the power in people is stronger than the people in power. CULT is the governance token of the Cult DAO. Every transaction of the CULT token allows you to contribute & fast-forward economic & societal change by contributing a 0.4% tax to the treasury. + Our society makes it as difficult as possible to break away from societal, economic and other norms, and CULT serves to fund and support those who are working to take back our future. CULT is a reminder that the power in people is stronger than the people in power. CULT is the governance token of the Cult DAO. Every transaction of the CULT token allows you to contribute & fast-forward economic & societal change by contributing a 0.4% tax to the treasury. Fight from within until you get out, or change the system in doing so.`, link: 'https://cultdao.io/', }, @@ -209,8 +209,8 @@ const config: EnvConfig = { LM_ADDRESS: '0xe2c436E177C39A5D18AF6923Fc2Fc673f4729C05', type: StakingType.HONEYSWAP_GIV_DAI, platform: StakingPlatform.HONEYSWAP, - title: 'GIV / DAI', - description: '50% GIV, 50% DAI', + title: 'GIV / xDAI', + description: '50% GIV, 50% xDAI', provideLiquidityLink: 'https://app.honeyswap.org/#/add/0x83a8eea6427985C523a0c4d9d3E62C051B6580d3/0x97c4dD5cE204b8c1F2f3B8fBfBBDC771d867d18c', unit: 'LP', From 96baebd987491a5366f9890e0a0aba9fb024d4d9 Mon Sep 17 00:00:00 2001 From: Mateo Daza Date: Mon, 30 May 2022 21:08:36 -0500 Subject: [PATCH 237/257] hotfix #784 --- src/components/cards/StakingCardIntro.tsx | 1 + src/config/development.ts | 4 +--- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/components/cards/StakingCardIntro.tsx b/src/components/cards/StakingCardIntro.tsx index 065ae73c70..6903d45ddc 100644 --- a/src/components/cards/StakingCardIntro.tsx +++ b/src/components/cards/StakingCardIntro.tsx @@ -65,6 +65,7 @@ const Back = styled.div` const Description = styled(Caption)` padding: 32px; margin-bottom: 138px; + white-space: pre-line; `; const LearnMoreButton = styled(ButtonLink)` diff --git a/src/config/development.ts b/src/config/development.ts index 6f0d9718dd..1f364c2acd 100644 --- a/src/config/development.ts +++ b/src/config/development.ts @@ -135,9 +135,7 @@ const config: EnvConfig = { regenFarmType: RegenFarmType.CULT_ETH, regenFarmIntro: { title: 'CULT', - description: `The purpose of CULT is to empower those building and contributing to our decentralized future. - Our society makes it as difficult as possible to break away from societal, economic and other norms, and CULT serves to fund and support those who are working to take back our future. CULT is a reminder that the power in people is stronger than the people in power. CULT is the governance token of the Cult DAO. Every transaction of the CULT token allows you to contribute & fast-forward economic & societal change by contributing a 0.4% tax to the treasury. - Fight from within until you get out, or change the system in doing so.`, + description: `The purpose of CULT is to empower those building and contributing to our decentralized future. Our society makes it as difficult as possible to break away from societal, economic and other norms, and CULT serves to fund and support those who are working to take back our future. CULT is a reminder that the power in people is stronger than the people in power.\n\n CULT is the governance token of the Cult DAO. Every transaction of the CULT token allows you to contribute & fast-forward economic & societal change by contributing a 0.4% tax to the treasury. Fight from within until you get out, or change the system in doing so.`, link: 'https://cultdao.io/', }, farmStartTimeMS: 1646306818206, From 72e26ad9606efae08058d4527b5d3bffed08f862 Mon Sep 17 00:00:00 2001 From: Mateo Daza Date: Mon, 30 May 2022 21:11:58 -0500 Subject: [PATCH 238/257] hotfix #820 --- src/components/GIVfrens.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/src/components/GIVfrens.tsx b/src/components/GIVfrens.tsx index 6db01b7d13..63cbbd91b7 100644 --- a/src/components/GIVfrens.tsx +++ b/src/components/GIVfrens.tsx @@ -115,6 +115,7 @@ const DAOChangeNetworkModal = ({ network }: IChangeNetworkModal) => { const checkWalletAndSwitchNetwork = async (network: number) => { if (!account) { await activate(new InjectedConnector({})); + await switchNetwork(network); } if (account) { await switchNetwork(network); From c0427ab04f4943fefecdd8e3e43c2d03c0f828dc Mon Sep 17 00:00:00 2001 From: Amin Latifi Date: Tue, 31 May 2022 10:15:14 +0430 Subject: [PATCH 239/257] Support other tokens image in add token Refs #834 --- src/lib/metamask/index.ts | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/src/lib/metamask/index.ts b/src/lib/metamask/index.ts index 0b818c7b82..4ded68655e 100644 --- a/src/lib/metamask/index.ts +++ b/src/lib/metamask/index.ts @@ -11,14 +11,31 @@ declare let window: any; const { MAINNET_CONFIG, XDAI_CONFIG } = config; -const tokenImage = - 'https://raw.githubusercontent.com/Giveth/giveth-design-assets/master/02-logos/GIV%20Token/GIVToken_200x200.png'; +const getTokenImage = (symbol: string): string | undefined => { + let _symbol = symbol.toLowerCase(); + + // GIV test token, DRGIV, DRGIV2, DRGIV3, ... + if (_symbol.startsWith('drgiv')) _symbol = 'giv'; + // TestFox, etc + else if (_symbol.startsWith('test')) _symbol = _symbol.slice(4); + + switch (_symbol) { + case 'giv': + return 'https://raw.githubusercontent.com/Giveth/giveth-design-assets/master/02-logos/GIV%20Token/GIVToken_200x200.png'; + case 'cult': + return 'https://raw.githubusercontent.com/Giveth/giveth-dapps-v2/develop/public/images/currencies/cult/64.svg'; + case 'fox': + return 'https://raw.githubusercontent.com/Giveth/giveth-dapps-v2/develop/public/images/currencies/fox/64.svg'; + } + + return undefined; +}; interface ITokenOptins { address: string; symbol: string; decimals: number; - image: string; + image?: string; } const fetchTokenInfo = async ( @@ -35,7 +52,7 @@ const fetchTokenInfo = async ( address: address, symbol: _symbol, decimals: _decimal, - image: tokenImage, + image: getTokenImage(_symbol), }; } catch (error) { console.error('error in fetchTokenInfo', error); From 1388e7d9e485dad6ccfe5be7e7e6f894dc658dbc Mon Sep 17 00:00:00 2001 From: Amin Latifi Date: Tue, 31 May 2022 10:51:51 +0430 Subject: [PATCH 240/257] Fixed a linting issue --- src/components/GIVfrens.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/GIVfrens.tsx b/src/components/GIVfrens.tsx index 63cbbd91b7..ce6ff87610 100644 --- a/src/components/GIVfrens.tsx +++ b/src/components/GIVfrens.tsx @@ -9,6 +9,7 @@ import { } from '@giveth/ui-design-system'; import { useWeb3React } from '@web3-react/core'; import styled from 'styled-components'; +import { InjectedConnector } from '@web3-react/injected-connector'; import { RegenPoolStakingConfig } from '@/types/config'; import { DAOContainer, @@ -23,7 +24,6 @@ import config from '@/configuration'; import { givEconomySupportedNetworks } from '@/lib/constants/constants'; import { RegenStreamCard } from './RegenStreamCard'; import { Flex } from './styled-components/Flex'; -import { InjectedConnector } from '@web3-react/injected-connector'; import { switchNetwork } from '@/lib/wallet'; interface IGIVfrensProps { From a689574e40927a26a6c2f2aa9c37f5a3d5bee8fc Mon Sep 17 00:00:00 2001 From: Ramin Date: Tue, 31 May 2022 15:55:52 +0430 Subject: [PATCH 241/257] move textarea to styled components --- src/components/controller/modal.ctrl.tsx | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/components/controller/modal.ctrl.tsx b/src/components/controller/modal.ctrl.tsx index a20ec74deb..26fa854c7c 100644 --- a/src/components/controller/modal.ctrl.tsx +++ b/src/components/controller/modal.ctrl.tsx @@ -1,3 +1,5 @@ +import { useWeb3React } from '@web3-react/core'; +import { useEffect } from 'react'; import WalletModal from '@/components/modals/WalletModal'; import WelcomeModal from '@/components/modals/WelcomeModal'; import { FirstWelcomeModal } from '@/components/modals/FirstWelcomeModal'; @@ -22,6 +24,14 @@ const ModalController = () => { } = useAppSelector(state => state.modal); const dispatch = useAppDispatch(); + const { active } = useWeb3React(); + + useEffect(() => { + if (showWelcomeModal) { + dispatch(setShowWelcomeModal(false)); + } + }, [active]); + return ( <> {showWalletModal && ( From 2105a0a536f3a743f1bdc333c9a882b99add49f1 Mon Sep 17 00:00:00 2001 From: Ramin Date: Tue, 31 May 2022 16:26:00 +0430 Subject: [PATCH 242/257] feat #569 fix scroll to similar projects on project donate card --- .../views/project/ProjectDonateCard.tsx | 17 +++++++++++------ .../views/project/SimilarProjects.tsx | 2 +- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/components/views/project/ProjectDonateCard.tsx b/src/components/views/project/ProjectDonateCard.tsx index 0ed66345ea..65d508efbc 100644 --- a/src/components/views/project/ProjectDonateCard.tsx +++ b/src/components/views/project/ProjectDonateCard.tsx @@ -39,8 +39,6 @@ import { VerificationModal } from '@/components/modals/VerificationModal'; import { mediaQueries } from '@/lib/constants/constants'; import ProjectCardOrgBadge from '../../project-card/ProjectCardOrgBadge'; import ExternalLink from '@/components/ExternalLink'; -import InternalLink from '@/components/InternalLink'; -import Routes from '@/lib/constants/Routes'; import { useAppDispatch, useAppSelector } from '@/features/hooks'; import { setShowSignWithWallet } from '@/features/modal/modal.sclie'; import { @@ -96,6 +94,11 @@ const ProjectDonateCard = ({ const wrapperRef = useRef(null); const [wrapperHeight, setWrapperHeight] = useState(0); + const scrollToSimilarProjects = () => { + const el = document.getElementById('similar-projects'); + if (el) el.scrollIntoView({ behavior: 'smooth' }); + }; + const likeUnlikeProject = async () => { if (!isSignedIn) { dispatch(setShowSignWithWallet(true)); @@ -307,10 +310,9 @@ const ProjectDonateCard = ({ href={links.REPORT_ISSUE} title='Report an issue' /> - +
+ View similar projects +
)} @@ -333,6 +335,9 @@ const Links = styled.div` display: flex; flex-direction: column; gap: 8px; + > div { + cursor: pointer; + } `; const BlueBar = styled.div` diff --git a/src/components/views/project/SimilarProjects.tsx b/src/components/views/project/SimilarProjects.tsx index db7e710523..85a072eb4f 100644 --- a/src/components/views/project/SimilarProjects.tsx +++ b/src/components/views/project/SimilarProjects.tsx @@ -70,7 +70,7 @@ const SimilarProjects = (props: { slug: string }) => { if (!suggestedProjects || suggestedProjects.length === 0) return null; return ( - +
Similar projects
Date: Tue, 31 May 2022 07:25:37 -0500 Subject: [PATCH 243/257] build hotfix --- src/components/GIVfrens.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/src/components/GIVfrens.tsx b/src/components/GIVfrens.tsx index ce6ff87610..9fee816d3f 100644 --- a/src/components/GIVfrens.tsx +++ b/src/components/GIVfrens.tsx @@ -7,6 +7,7 @@ import { IconInfo16, neutralColors, } from '@giveth/ui-design-system'; +import { InjectedConnector } from '@web3-react/injected-connector'; import { useWeb3React } from '@web3-react/core'; import styled from 'styled-components'; import { InjectedConnector } from '@web3-react/injected-connector'; From e55448c53c1eb7ffce80da3361e7b4ea91d16423 Mon Sep 17 00:00:00 2001 From: Mateo Daza Date: Tue, 31 May 2022 07:27:07 -0500 Subject: [PATCH 244/257] Update GIVfrens.tsx --- src/components/GIVfrens.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/src/components/GIVfrens.tsx b/src/components/GIVfrens.tsx index 9fee816d3f..3999ad68a2 100644 --- a/src/components/GIVfrens.tsx +++ b/src/components/GIVfrens.tsx @@ -10,7 +10,6 @@ import { import { InjectedConnector } from '@web3-react/injected-connector'; import { useWeb3React } from '@web3-react/core'; import styled from 'styled-components'; -import { InjectedConnector } from '@web3-react/injected-connector'; import { RegenPoolStakingConfig } from '@/types/config'; import { DAOContainer, From e71df404bb42e527015b6be676e13106bb8c7f24 Mon Sep 17 00:00:00 2001 From: alireza-sharifpour Date: Wed, 1 Jun 2022 12:31:53 +0430 Subject: [PATCH 245/257] Fixed DonationCard styles --- src/components/project-card/ProjectCard.tsx | 81 +++++++++++-------- .../project-card/ProjectCardOrgBadge.tsx | 6 +- 2 files changed, 52 insertions(+), 35 deletions(-) diff --git a/src/components/project-card/ProjectCard.tsx b/src/components/project-card/ProjectCard.tsx index d6ecfa4028..9a72bc5e61 100644 --- a/src/components/project-card/ProjectCard.tsx +++ b/src/components/project-card/ProjectCard.tsx @@ -78,6 +78,7 @@ const ProjectCard = (props: IProjectCard) => { isOtherOrganization={ organization?.label !== ORGANIZATION.giveth } + isVerified={verified} >
@@ -110,35 +111,40 @@ const ProjectCard = (props: IProjectCard) => { Raised -
- - {verified && ( - <> - - - VERIFIED - - - - +
+ + <> + + -
- GIVBACK ELIGIBLE -
- - )} -
+ VERIFIED + + + + + + + GIVBACK ELIGIBLE + + + + + + )} @@ -152,10 +158,12 @@ const DonateButton = styled(ButtonLink)` flex: 1; `; -const CustomizedDonateButton = styled(DonateButton)` +const CustomizedDonateButton = styled(DonateButton)<{ isHover: boolean }>` margin: 25px 0; - ${mediaQueries.desktop} { + ${mediaQueries.laptop} { margin: 25px 12px; + opacity: ${props => (props.isHover ? '1' : '0')}; + transition: opacity 0.3s ease-in-out; } `; @@ -183,10 +191,6 @@ const GivBackIconContainer = styled.div` transform: scale(0.8); `; -const BadgesContainer = styled(Flex)` - min-height: 25px; -`; - const LastUpdatedContainer = styled(Subline)<{ isHover?: boolean }>` position: absolute; bottom: 20px; @@ -220,19 +224,30 @@ const Description = styled(P)` const CardBody = styled.div<{ isOtherOrganization?: boolean; isHover?: boolean; + isVerified?: boolean; }>` padding: 26px; padding-top: 32px; position: absolute; left: 0; right: 0; - top: 200px; + top: ${props => (props.isVerified ? '192px' : '227px')}; background-color: ${neutralColors.gray[100]}; transition: top 0.3s ease; border-radius: ${props => props.isOtherOrganization ? '0 12px 12px 12px' : '12px'}; - ${mediaQueries.desktop} { - top: ${props => (props.isHover ? '130px' : '200px')}; + ${mediaQueries.laptop} { + top: ${props => { + if (props.isHover && props.isVerified) { + return '109px'; + } else if (props.isHover && !props.isVerified) { + return '151px'; + } else if (!props.isVerified) { + return '221px'; + } else if (props.isVerified) { + return '186px'; + } + }}; } `; @@ -261,13 +276,15 @@ const ImagePlaceholder = styled.div` const Wrapper = styled.div` position: relative; width: 100%; + max-width: 443px; border-radius: ${cardRadius}; + margin: 0 auto; background: white; overflow: hidden; box-shadow: ${Shadow.Neutral[400]}; height: 536px; cursor: pointer; - ${mediaQueries.desktop} { + ${mediaQueries.laptop} { height: 472px; } `; diff --git a/src/components/project-card/ProjectCardOrgBadge.tsx b/src/components/project-card/ProjectCardOrgBadge.tsx index 492ce565dc..9e68ee2f9a 100644 --- a/src/components/project-card/ProjectCardOrgBadge.tsx +++ b/src/components/project-card/ProjectCardOrgBadge.tsx @@ -78,11 +78,11 @@ const HomeViewContainer = styled(FlexCenter)<{ isHover: boolean }>` gap: 8px; padding: 0 24px; position: absolute; - bottom: 24px; + bottom: 32px; transition: bottom 0.3s ease; border-top-right-radius: 12px; - ${mediaQueries.desktop} { - bottom: ${props => (props.isHover ? '96px' : '26px')}; + ${mediaQueries.laptop} { + bottom: ${props => (props.isHover ? '116px' : '39px')}; } `; From 9d811b5c49fb990cd927313aa05593c2698df794 Mon Sep 17 00:00:00 2001 From: Ramin Date: Wed, 1 Jun 2022 16:04:38 +0430 Subject: [PATCH 246/257] Feat #730 implement donation status badge and filter for my account, public view and single project view --- pages/account.tsx | 2 +- pages/user/[address].tsx | 2 +- src/apollo/gql/gqlDonations.ts | 2 + src/apollo/gql/gqlUser.ts | 2 + src/components/badges/DonationStatusBadge.tsx | 72 +++++++++++++++++++ .../views/project/ProjectDonationTable.tsx | 71 ++++++++++-------- .../views/project/ProjectDonations.tsx | 5 +- src/components/views/project/ProjectIndex.tsx | 22 +++++- .../donationsTab/DonationsTable.tsx | 37 +++++----- .../PublicProfileDonationsTab.tsx | 4 +- 10 files changed, 163 insertions(+), 56 deletions(-) create mode 100644 src/components/badges/DonationStatusBadge.tsx diff --git a/pages/account.tsx b/pages/account.tsx index eb6954b505..1592d88e5a 100644 --- a/pages/account.tsx +++ b/pages/account.tsx @@ -17,7 +17,7 @@ const UserRoute: FC = () => { Giveth | {user?.name} {user ? ( - + ) : (
Not logged in or user not found
diff --git a/pages/user/[address].tsx b/pages/user/[address].tsx index ab21b6cf60..a0a8ef2cf4 100644 --- a/pages/user/[address].tsx +++ b/pages/user/[address].tsx @@ -28,7 +28,7 @@ const UserRoute: FC = ({ user }) => { Giveth | {user.name} - + ); }; diff --git a/src/apollo/gql/gqlDonations.ts b/src/apollo/gql/gqlDonations.ts index 124650c222..26f1504ce9 100644 --- a/src/apollo/gql/gqlDonations.ts +++ b/src/apollo/gql/gqlDonations.ts @@ -8,6 +8,7 @@ export const FETCH_PROJECT_DONATIONS = gql` $projectId: Int! $searchTerm: String $orderBy: SortBy + $status: String ) { donationsByProjectId( take: $take @@ -16,6 +17,7 @@ export const FETCH_PROJECT_DONATIONS = gql` projectId: $projectId searchTerm: $searchTerm orderBy: $orderBy + status: $status ) { donations { id diff --git a/src/apollo/gql/gqlUser.ts b/src/apollo/gql/gqlUser.ts index 0a01e36191..5fc36487ce 100644 --- a/src/apollo/gql/gqlUser.ts +++ b/src/apollo/gql/gqlUser.ts @@ -71,12 +71,14 @@ export const FETCH_USER_DONATIONS = gql` $userId: Int! $orderBy: SortField! $direction: SortDirection! + $status: String ) { donationsByUserId( take: $take skip: $skip orderBy: { field: $orderBy, direction: $direction } userId: $userId + status: $status ) { donations { id diff --git a/src/components/badges/DonationStatusBadge.tsx b/src/components/badges/DonationStatusBadge.tsx new file mode 100644 index 0000000000..fda2864965 --- /dev/null +++ b/src/components/badges/DonationStatusBadge.tsx @@ -0,0 +1,72 @@ +import { FC } from 'react'; +import styled from 'styled-components'; +import { + neutralColors, + semanticColors, + SublineBold, +} from '@giveth/ui-design-system'; +import { EDonationStatus } from '@/apollo/types/gqlEnums'; + +interface IDonationStatus { + status: EDonationStatus; +} + +const DonationStatus: FC = ({ status }) => { + let _status: string = status; + if (status === EDonationStatus.VERIFIED) _status = 'success'; + return ( + + {status === EDonationStatus.PENDING && } + {_status} + + ); +}; + +const Bullet = styled.div` + width: 6px; + height: 6px; + border-radius: 50%; + background: ${neutralColors.gray[700]}; +`; + +const Container = styled(SublineBold)` + display: flex; + gap: 4px; + align-items: center; + text-transform: capitalize; + border-radius: 50px; + padding: 2px 8px; + border: 2px solid + ${props => { + switch (props.status) { + case EDonationStatus.VERIFIED: + return semanticColors.jade[300]; + case EDonationStatus.PENDING: + return neutralColors.gray[400]; + case EDonationStatus.FAILED: + return semanticColors.punch[200]; + } + }}; + color: ${props => { + switch (props.status) { + case EDonationStatus.VERIFIED: + return neutralColors.gray[700]; + case EDonationStatus.PENDING: + return neutralColors.gray[700]; + case EDonationStatus.FAILED: + return semanticColors.punch[700]; + } + }}; + background: ${props => { + switch (props.status) { + case EDonationStatus.VERIFIED: + return semanticColors.jade[100]; + case EDonationStatus.PENDING: + return 'transparent'; + case EDonationStatus.FAILED: + return semanticColors.punch[100]; + } + }}; +`; + +export default DonationStatus; diff --git a/src/components/views/project/ProjectDonationTable.tsx b/src/components/views/project/ProjectDonationTable.tsx index f678c7a881..561c191e79 100644 --- a/src/components/views/project/ProjectDonationTable.tsx +++ b/src/components/views/project/ProjectDonationTable.tsx @@ -8,22 +8,27 @@ import { IconExternalLink, neutralColors, P, - SublineBold, } from '@giveth/ui-design-system'; import { client } from '@/apollo/apolloClient'; import { FETCH_PROJECT_DONATIONS } from '@/apollo/gql/gqlDonations'; -import { IDonation } from '@/apollo/types/types'; +import { IDonation, IProject } from '@/apollo/types/types'; import SearchBox from '@/components/SearchBox'; import { Flex } from '@/components/styled-components/Flex'; import Pagination from '@/components/Pagination'; -import { smallFormatDate, formatTxLink } from '@/lib/helpers'; +import { smallFormatDate, formatTxLink, compareAddresses } from '@/lib/helpers'; import config from '@/configuration'; -import { EDirection, EDonationType } from '@/apollo/types/gqlEnums'; +import { + EDirection, + EDonationStatus, + EDonationType, +} from '@/apollo/types/gqlEnums'; import ExternalLink from '@/components/ExternalLink'; import SortIcon from '@/components/SortIcon'; import ETHIcon from '/public/images/currencies/eth/24.svg'; import GnosisIcon from '/public/images/currencies/gnosisChain/24.svg'; +import { useAppSelector } from '@/features/hooks'; +import DonationStatus from '@/components/badges/DonationStatusBadge'; const itemPerPage = 10; @@ -40,16 +45,14 @@ interface IOrder { interface IProjectDonationTable { donations: IDonation[]; - id?: string; - showTrace: boolean; totalDonations?: number; + project?: IProject; } const ProjectDonationTable = ({ donations, - id, - showTrace, totalDonations, + project, }: IProjectDonationTable) => { const [pageDonations, setPageDonations] = useState(donations); const [page, setPage] = useState(0); @@ -60,6 +63,14 @@ const ProjectDonationTable = ({ const [activeTab, setActiveTab] = useState(0); const [searchTerm, setSearchTerm] = useState(''); + const user = useAppSelector(state => state.user.userData); + + const { id, traceCampaignId, adminUser } = project || {}; + const isAdmin = compareAddresses( + adminUser?.walletAddress, + user?.walletAddress, + ); + const orderChangeHandler = (orderBy: EOrderBy) => { if (orderBy === order.by) { setOrder({ @@ -88,6 +99,7 @@ const ProjectDonationTable = ({ skip: page * itemPerPage, orderBy: { field: order.by, direction: order.direction }, searchTerm, + status: isAdmin ? null : EDonationStatus.VERIFIED, }, }); const { donationsByProjectId } = projectDonations; @@ -95,7 +107,7 @@ const ProjectDonationTable = ({ setPageDonations(donationsByProjectId.donations); } }; - fetchProjectDonations(); + fetchProjectDonations().then(); }, [page, order.by, order.direction, id, searchTerm]); useEffect(() => { @@ -112,7 +124,7 @@ const ProjectDonationTable = ({ > Donations - {showTrace && ( + {!!traceCampaignId && ( setActiveTab(1)} className={activeTab === 1 ? 'active' : ''} @@ -128,7 +140,7 @@ const ProjectDonationTable = ({ {activeTab === 0 && ( - + orderChangeHandler(EOrderBy.CreationDate) @@ -141,9 +153,8 @@ const ProjectDonationTable = ({ /> Donor - Status + {isAdmin && Status} Network - Currency orderChangeHandler(EOrderBy.TokenAmount) @@ -182,7 +193,13 @@ const ProjectDonationTable = ({ : donation.user?.name || donation.user?.firstName} - {donation.status} + {isAdmin && ( + + + + )} chain logo - - {donation.currency} - - - -

{donation.amount}

+ {donation.amount} + {donation.currency} {!donation.anonymous && ( ` margin-top: 12px; display: grid; width: 100%; - grid-template-columns: 1.25fr 2fr 1fr 1.25fr 1fr 1fr 1fr; + grid-template-columns: ${props => + props.isAdmin + ? '1.25fr 2fr 1fr 1.25fr 1fr 1fr' + : '1.25fr 2fr 1.25fr 1fr 1fr'}; min-width: 800px; `; @@ -321,11 +341,4 @@ const TableCell = styled(Flex)` gap: 8px; `; -const CurrencyBadge = styled(SublineBold)` - padding: 2px 8px; - border: 2px solid ${neutralColors.gray[400]}; - border-radius: 50px; - color: ${neutralColors.gray[700]}; -`; - export default ProjectDonationTable; diff --git a/src/components/views/project/ProjectDonations.tsx b/src/components/views/project/ProjectDonations.tsx index 681acc8a02..0995e7ee3b 100644 --- a/src/components/views/project/ProjectDonations.tsx +++ b/src/components/views/project/ProjectDonations.tsx @@ -15,7 +15,7 @@ const ProjectDonations = (props: { isDraft: boolean; }) => { const { donationsByProjectId, project, isActive, isDraft } = props; - const { totalDonations, id, traceCampaignId } = project || {}; + const { totalDonations } = project || {}; return ( <> @@ -40,9 +40,8 @@ const ProjectDonations = (props: { )} diff --git a/src/components/views/project/ProjectIndex.tsx b/src/components/views/project/ProjectIndex.tsx index 8645d683f5..4c404cf816 100644 --- a/src/components/views/project/ProjectIndex.tsx +++ b/src/components/views/project/ProjectIndex.tsx @@ -13,14 +13,19 @@ import { FETCH_PROJECT_DONATIONS } from '@/apollo/gql/gqlDonations'; import { client } from '@/apollo/apolloClient'; import { FETCH_PROJECT_BY_SLUG } from '@/apollo/gql/gqlProjects'; import { IDonation, IProject } from '@/apollo/types/types'; -import { EDirection, EProjectStatus, gqlEnums } from '@/apollo/types/gqlEnums'; +import { + EDirection, + EDonationStatus, + EProjectStatus, + gqlEnums, +} from '@/apollo/types/gqlEnums'; import InfoBadge from '@/components/badges/InfoBadge'; import { IDonationsByProjectIdGQL } from '@/apollo/types/gqlTypes'; import SuccessfulCreation from '@/components/views/create/SuccessfulCreation'; import { deviceSize, mediaQueries } from '@/lib/constants/constants'; import InlineToast from '@/components/toasts/InlineToast'; import SimilarProjects from '@/components/views/project/SimilarProjects'; -import { showToastError } from '@/lib/helpers'; +import { compareAddresses, showToastError } from '@/lib/helpers'; import { useAppSelector } from '@/features/hooks'; import { ProjectMeta } from '@/components/Metatag'; @@ -47,9 +52,19 @@ const ProjectIndex = (props: { project?: IProject }) => { const [isCancelled, setIsCancelled] = useState(false); const user = useAppSelector(state => state.user.userData); - const { description = '', title, status, id = '' } = project || {}; + const { + adminUser, + description = '', + title, + status, + id = '', + } = project || {}; const router = useRouter(); const slug = router.query.projectIdSlug as string; + const isAdmin = compareAddresses( + adminUser?.walletAddress, + user?.walletAddress, + ); const fetchProject = async () => { client @@ -88,6 +103,7 @@ const ProjectIndex = (props: { project?: IProject }) => { projectId: parseInt(id), skip: 0, take: donationsPerPage, + status: isAdmin ? null : EDonationStatus.VERIFIED, orderBy: { field: gqlEnums.CREATIONDATE, direction: EDirection.DESC, diff --git a/src/components/views/userPublicProfile/donationsTab/DonationsTable.tsx b/src/components/views/userPublicProfile/donationsTab/DonationsTable.tsx index 513addeb8a..3cfd6b1477 100644 --- a/src/components/views/userPublicProfile/donationsTab/DonationsTable.tsx +++ b/src/components/views/userPublicProfile/donationsTab/DonationsTable.tsx @@ -8,7 +8,6 @@ import { IconLink24, neutralColors, P, - SublineBold, } from '@giveth/ui-design-system'; import { formatUSD, smallFormatDate, formatTxLink } from '@/lib/helpers'; @@ -20,27 +19,29 @@ import { IOrder, } from '@/components/views/userPublicProfile/UserPublicProfile.view'; import SortIcon from '@/components/SortIcon'; +import DonationStatus from '@/components/badges/DonationStatusBadge'; interface DonationTable { donations: IWalletDonation[]; order: IOrder; changeOrder: (orderBy: EOrderBy) => void; + myAccount?: boolean; } const DonationTable: FC = ({ donations, order, changeOrder, + myAccount, }) => { return ( - + changeOrder(EOrderBy.CreationDate)}> Donated at Project - Status - Currency + {myAccount && Status} changeOrder(EOrderBy.TokenAmount)}> Amount @@ -63,12 +64,14 @@ const DonationTable: FC = ({ - {donation.status} + {myAccount && ( + + + + )} - {donation.currency} - - -

{donation.amount}

+ {donation.amount} + {donation.currency} = ({ ); }; +const Currency = styled.div` + color: ${neutralColors.gray[600]}; +`; + const RowWrapper = styled.div` display: contents; &:hover > div { @@ -111,9 +118,10 @@ const TableCell = styled(P)<{ bold?: boolean }>` font-weight: ${props => (props.bold ? 500 : 400)}; `; -const DonationTableContainer = styled.div` +const DonationTableContainer = styled.div<{ myAccount?: boolean }>` display: grid; - grid-template-columns: 1fr 4fr 1fr 1fr 1fr 1fr; + grid-template-columns: ${props => + props.myAccount ? '1fr 4fr 1fr 1fr 1fr' : '1fr 4fr 1fr 1fr'}; overflow: auto; min-width: 900px; margin: 0 10px; @@ -141,11 +149,4 @@ const ProjectTitleCell = styled(TableCell)` } `; -const CurrencyBadge = styled(SublineBold)` - padding: 2px 8px; - border: 2px solid ${neutralColors.gray[400]}; - border-radius: 50px; - color: ${neutralColors.gray[700]}; -`; - export default DonationTable; diff --git a/src/components/views/userPublicProfile/donationsTab/PublicProfileDonationsTab.tsx b/src/components/views/userPublicProfile/donationsTab/PublicProfileDonationsTab.tsx index 4d5b97b5ed..55c0702476 100644 --- a/src/components/views/userPublicProfile/donationsTab/PublicProfileDonationsTab.tsx +++ b/src/components/views/userPublicProfile/donationsTab/PublicProfileDonationsTab.tsx @@ -7,7 +7,7 @@ import { EOrderBy, IOrder, } from '../UserPublicProfile.view'; -import { EDirection } from '@/apollo/types/gqlEnums'; +import { EDirection, EDonationStatus } from '@/apollo/types/gqlEnums'; import { client } from '@/apollo/apolloClient'; import { FETCH_USER_DONATIONS } from '@/apollo/gql/gqlUser'; import { IUserDonations } from '@/apollo/types/gqlTypes'; @@ -61,6 +61,7 @@ const PublicProfileDonationsTab: FC = ({ skip: page * itemPerPage, orderBy: order.by, direction: order.direction, + status: !myAccount ? EDonationStatus.VERIFIED : null, }, }); setLoading(false); @@ -90,6 +91,7 @@ const PublicProfileDonationsTab: FC = ({ donations={donations} order={order} changeOrder={changeOrder} + myAccount={myAccount} /> )} {loading && } From 4ee38cba90e9b51e86f2af5413b5d4958656d834 Mon Sep 17 00:00:00 2001 From: Cherik Date: Wed, 1 Jun 2022 18:31:08 +0430 Subject: [PATCH 247/257] fix build issue --- src/components/GIVfrens.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/src/components/GIVfrens.tsx b/src/components/GIVfrens.tsx index 9fee816d3f..3999ad68a2 100644 --- a/src/components/GIVfrens.tsx +++ b/src/components/GIVfrens.tsx @@ -10,7 +10,6 @@ import { import { InjectedConnector } from '@web3-react/injected-connector'; import { useWeb3React } from '@web3-react/core'; import styled from 'styled-components'; -import { InjectedConnector } from '@web3-react/injected-connector'; import { RegenPoolStakingConfig } from '@/types/config'; import { DAOContainer, From a7f27270e02ef1a04b13ddacddd14cb552127259 Mon Sep 17 00:00:00 2001 From: Mateo Daza Date: Wed, 1 Jun 2022 21:07:50 -0500 Subject: [PATCH 248/257] removes user and token when unauthorized --- src/apollo/apolloClient.ts | 22 +++++++++++++++++++++- src/features/user/user.thunks.ts | 6 +++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/apollo/apolloClient.ts b/src/apollo/apolloClient.ts index 798f028e97..fa4710f7a5 100644 --- a/src/apollo/apolloClient.ts +++ b/src/apollo/apolloClient.ts @@ -1,6 +1,7 @@ import { useMemo } from 'react'; import { ApolloClient, InMemoryCache, ApolloLink } from '@apollo/client'; import { setContext } from '@apollo/client/link/context'; +import { onError } from '@apollo/client/link/error'; import gql from 'graphql-tag'; import { createUploadLink } from 'apollo-upload-client'; import merge from 'deepmerge'; @@ -8,6 +9,8 @@ import isEqual from 'lodash.isequal'; import { isSSRMode } from '@/lib/helpers'; import links from '@/lib/constants/links'; import StorageLabel from '@/lib/localStorage'; +import { store } from '@/features/store'; +import { signOut } from '@/features/user/user.thunks'; let apolloClient: any; @@ -42,9 +45,26 @@ function createApolloClient() { }; }); + const errorLink = onError(({ graphQLErrors, networkError, operation }) => { + if (graphQLErrors) + graphQLErrors.forEach(({ message, locations, path }) => + console.log(`[GraphQL error]: ${message}`, { locations, path }), + ); + + if (networkError) console.log(`[Network error]: ${networkError}`); + const { response } = operation.getContext(); + if (response.status === 401) { + // removes token and user from store + const currentToken: string | null = !ssrMode + ? localStorage.getItem(StorageLabel.TOKEN) + : null; + store.dispatch(signOut(currentToken)); + } + }); + return new ApolloClient({ ssrMode, - link: authLink.concat(httpLink), + link: errorLink.concat(authLink.concat(httpLink)), cache: new InMemoryCache(), defaultOptions: { watchQuery: { diff --git a/src/features/user/user.thunks.ts b/src/features/user/user.thunks.ts index f52d314729..737c3fde04 100644 --- a/src/features/user/user.thunks.ts +++ b/src/features/user/user.thunks.ts @@ -57,7 +57,11 @@ export const signToGetToken = createAsyncThunk( export const signOut = createAsyncThunk( 'user/signOut', - async (token: string) => { + async (token?: string | null) => { + // this is in the case we fail to grab the token from local storage + // but still want to remove the whole user + if (!token) return true; + return await postRequest( `${config.MICROSERVICES.authentication}/logout`, true, From f965ce9d04635a94a1ff01e6dec397015c55e536 Mon Sep 17 00:00:00 2001 From: Cherik Date: Thu, 2 Jun 2022 13:22:21 +0430 Subject: [PATCH 249/257] fix work without status code --- src/apollo/apolloClient.ts | 10 +++++++--- src/features/user/user.thunks.ts | 2 +- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/apollo/apolloClient.ts b/src/apollo/apolloClient.ts index fa4710f7a5..002dc14411 100644 --- a/src/apollo/apolloClient.ts +++ b/src/apollo/apolloClient.ts @@ -47,9 +47,13 @@ function createApolloClient() { const errorLink = onError(({ graphQLErrors, networkError, operation }) => { if (graphQLErrors) - graphQLErrors.forEach(({ message, locations, path }) => - console.log(`[GraphQL error]: ${message}`, { locations, path }), - ); + graphQLErrors.forEach(({ message, locations, path }) => { + console.log(`[GraphQL error]: ${message}`, { locations, path }); + if (message.toLowerCase().includes('authentication required')) { + // removes token and user from store + store.dispatch(signOut()); + } + }); if (networkError) console.log(`[Network error]: ${networkError}`); const { response } = operation.getContext(); diff --git a/src/features/user/user.thunks.ts b/src/features/user/user.thunks.ts index 737c3fde04..ff2f908f76 100644 --- a/src/features/user/user.thunks.ts +++ b/src/features/user/user.thunks.ts @@ -60,7 +60,7 @@ export const signOut = createAsyncThunk( async (token?: string | null) => { // this is in the case we fail to grab the token from local storage // but still want to remove the whole user - if (!token) return true; + if (!token) return Promise.resolve(true); return await postRequest( `${config.MICROSERVICES.authentication}/logout`, From 9de6c78b73e757f3a67efa622846d8aac7f05fa1 Mon Sep 17 00:00:00 2001 From: Ramin Date: Sun, 5 Jun 2022 21:24:29 +0430 Subject: [PATCH 250/257] #849 Add Community Call to Join page --- src/components/styled-components/Position.ts | 5 +++++ src/components/views/join/JoinEngage.tsx | 19 ++++++++++++++++--- src/lib/constants/links.ts | 2 ++ 3 files changed, 23 insertions(+), 3 deletions(-) create mode 100644 src/components/styled-components/Position.ts diff --git a/src/components/styled-components/Position.ts b/src/components/styled-components/Position.ts new file mode 100644 index 0000000000..90039f2f30 --- /dev/null +++ b/src/components/styled-components/Position.ts @@ -0,0 +1,5 @@ +import styled from 'styled-components'; + +export const Absolute = styled.div` + position: absolute; +`; diff --git a/src/components/views/join/JoinEngage.tsx b/src/components/views/join/JoinEngage.tsx index bdcfbfe94e..9aa50ee817 100644 --- a/src/components/views/join/JoinEngage.tsx +++ b/src/components/views/join/JoinEngage.tsx @@ -16,6 +16,9 @@ import reddit_icon from '/public/images/reddit_icon.svg'; import links from '@/lib/constants/links'; import { mediaQueries } from '@/lib/constants/constants'; import JoinSubscriptionCard from './JoinSubscriptionCard'; +import { FlexCenter } from '@/components/styled-components/Flex'; +import { Absolute } from '@/components/styled-components/Position'; +import { ButtonStyled } from '@/components/GeneralCard.sc'; const JoinEngage = () => { return ( @@ -29,12 +32,22 @@ const JoinEngage = () => {
- Follow our social media, and come say hello in a channel below. + You can join our Community Call every Thursday in Discord, + follow our social media, or come say hello in a channel below. We look forward to welcoming you! -
+
+ + window.open(links.ADD_TO_CALENDAR)} + /> + + + yellow flower -
+
Engage diff --git a/src/lib/constants/links.ts b/src/lib/constants/links.ts index 223884da50..dd321a8a99 100644 --- a/src/lib/constants/links.ts +++ b/src/lib/constants/links.ts @@ -40,6 +40,8 @@ const links: any = { HISTORY: 'https://docs.giveth.io/whatisgiveth/history', CALENDAR: 'https://calendar.google.com/calendar/u/1?cid=Z2l2ZXRoZG90aW9AZ21haWwuY29t', + ADD_TO_CALENDAR: + 'https://calendar.google.com/event?action=TEMPLATE&tmeid=dWZydnNoNjVmb2NvNDNrZ2htMmtzaDNydGZfMjAyMjA2MDlUMTUwMDAwWiBnaXZldGhkb3Rpb0Bt&tmsrc=givethdotio%40gmail.com&scp=ALL', }; if (!isProduction) { From c93af44d1c59f2d7e0a44debafdc8d6693f7855b Mon Sep 17 00:00:00 2001 From: Ramin Date: Sun, 5 Jun 2022 23:28:26 +0430 Subject: [PATCH 251/257] #868 fix showing complete profile on create --- src/components/views/create/CreateIndex.tsx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/components/views/create/CreateIndex.tsx b/src/components/views/create/CreateIndex.tsx index 559756c178..f568b3982f 100644 --- a/src/components/views/create/CreateIndex.tsx +++ b/src/components/views/create/CreateIndex.tsx @@ -22,9 +22,13 @@ const CreateIndex = () => { if (!isRegistered) { dispatch(setShowCompleteProfile(true)); return; + } else { + dispatch(setShowCompleteProfile(false)); } if (!isSignedIn) { dispatch(setShowSignWithWallet(true)); + } else { + dispatch(setShowSignWithWallet(false)); } } else { dispatch(setShowWelcomeModal(true)); From 1e56becf9088d42528a799757146947e656a93ac Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 6 Jun 2022 13:45:14 +0430 Subject: [PATCH 252/257] set formChange false befor publishing or preview --- src/components/views/create/CreateProject.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/src/components/views/create/CreateProject.tsx b/src/components/views/create/CreateProject.tsx index ad3fc890f2..d6db932ab5 100644 --- a/src/components/views/create/CreateProject.tsx +++ b/src/components/views/create/CreateProject.tsx @@ -209,6 +209,7 @@ const CreateProject = (props: { project?: IProjectEdition }) => { const onSubmit = async (drafted?: boolean) => { try { if (!isReadyToPublish()) return; + setFormChange(false); const address = isAddressENS(walletAddress) ? await getAddressFromENS(walletAddress, library) From 59fe16a036e255e1c7a9182257bbd1bcd4975639 Mon Sep 17 00:00:00 2001 From: Ramin Date: Mon, 6 Jun 2022 17:36:43 +0430 Subject: [PATCH 253/257] fix mobile padding --- src/components/views/join/JoinEngage.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/views/join/JoinEngage.tsx b/src/components/views/join/JoinEngage.tsx index 9aa50ee817..b698043377 100644 --- a/src/components/views/join/JoinEngage.tsx +++ b/src/components/views/join/JoinEngage.tsx @@ -143,7 +143,7 @@ const consumeArray = [ ]; const UpperSection = styled.div` - padding: 150px 0 36px; + padding: 18% 0; color: white; overflow: hidden; position: relative; From 363b7f8f6899c239e7f165ecbc19dd235323536e Mon Sep 17 00:00:00 2001 From: Ramin Date: Mon, 6 Jun 2022 19:14:37 +0430 Subject: [PATCH 254/257] make join page responsive --- src/components/GeneralCard.sc.tsx | 27 ++-- src/components/views/join/JoinEngage.tsx | 131 +++++++++--------- .../views/join/JoinSubscriptionCard.tsx | 9 +- 3 files changed, 88 insertions(+), 79 deletions(-) diff --git a/src/components/GeneralCard.sc.tsx b/src/components/GeneralCard.sc.tsx index 8b9f72be9b..4b1f5b1885 100644 --- a/src/components/GeneralCard.sc.tsx +++ b/src/components/GeneralCard.sc.tsx @@ -7,11 +7,22 @@ import { Shadow } from './styled-components/Shadow'; export const ButtonStyled = styled(Button)` text-transform: uppercase; - margin: 24px auto 0 auto; - width: 265px; - height: 66px; + margin: 24px auto 0; + width: 200px; + height: 50px; padding: 0; min-height: 33px; + * { + font-size: 12px !important; + } + + ${mediaQueries.mobileL} { + width: 265px; + height: 66px; + * { + font-size: 14px !important; + } + } `; export const Title = styled(H4)` @@ -36,10 +47,9 @@ export const HorizontalTitleSection = styled.div` flex-direction: column; text-align: left; max-width: calc(100vw - 72px); - padding: 0; ${mediaQueries.tablet} { - padding: 0 0 0 84px; + padding: 0 15px 0 70px; width: ${(props: { fullWidth?: boolean }) => props.fullWidth ? '100%' : '485px'}; } @@ -71,16 +81,17 @@ export const HorizontalWrap = styled.div` color: ${brandColors.giv[800]}; border-radius: 12px; box-shadow: ${Shadow.Dark[500]}; - margin: 26px 0; flex-direction: column; padding: 36px 32px; max-width: calc(100vw - 36px); ${mediaQueries.tablet} { flex-direction: row; - padding: 45px 72px; - max-width: 1000px; + padding: 36px 32px; min-height: 220px; width: 100%; } + ${mediaQueries.desktop} { + padding: 45px 72px; + } `; diff --git a/src/components/views/join/JoinEngage.tsx b/src/components/views/join/JoinEngage.tsx index b698043377..01e97bb391 100644 --- a/src/components/views/join/JoinEngage.tsx +++ b/src/components/views/join/JoinEngage.tsx @@ -14,61 +14,62 @@ import twitter_icon from '/public/images/twitter_icon.svg'; import youtube_icon from '/public/images/youtube_icon.svg'; import reddit_icon from '/public/images/reddit_icon.svg'; import links from '@/lib/constants/links'; -import { mediaQueries } from '@/lib/constants/constants'; import JoinSubscriptionCard from './JoinSubscriptionCard'; import { FlexCenter } from '@/components/styled-components/Flex'; -import { Absolute } from '@/components/styled-components/Position'; import { ButtonStyled } from '@/components/GeneralCard.sc'; +import { Container } from '@/components/Grid'; const JoinEngage = () => { return ( - - - Giveth is first and foremost a community of givers and - changemakers. We are passionate people working together to build - a crypto-economic system that can reward giving to good causes. - Our project is open-source, decentralized, altruistic, and - community-led. - -
- - You can join our Community Call every Thursday in Discord, - follow our social media, or come say hello in a channel below. - We look forward to welcoming you! - -
- - window.open(links.ADD_TO_CALENDAR)} - /> - + <> + + + Giveth is first and foremost a community of givers and + changemakers. We are passionate people working together to + build a crypto-economic system that can reward giving to + good causes. Our project is open-source, decentralized, + altruistic, and community-led. + +
+ + You can join our Community Call every Thursday in Discord, + follow our social media, or come say hello in a channel + below. We look forward to welcoming you! + +
+ + window.open(links.ADD_TO_CALENDAR)} + /> + - +
+ Engage + + {engageArray.map(i => ( + + ))} + +
+
+ Consume + + {consumeArray.map(i => ( + + ))} + + +
+
+ yellow flower - -
- Engage - - {engageArray.map(i => ( - - ))} - -
-
- Consume - - {consumeArray.map(i => ( - - ))} - - - - blue flower - -
-
+ + + blue flower + + ); }; @@ -142,30 +143,27 @@ const consumeArray = [ }, ]; -const UpperSection = styled.div` - padding: 18% 0; - color: white; - overflow: hidden; +const ContainerStyled = styled(Container)` + max-width: 1205px; + margin-bottom: 80px; + margin-top: 80px; position: relative; - - ${mediaQueries.tablet} { - padding: 150px 0; - } + z-index: 1; `; const LeadText = styled(Lead)` color: ${brandColors.giv[900]}; - margin: 0 20%; + max-width: 900px; + margin: 0 auto; `; const Title = styled(H2)` color: ${brandColors.giv[700]}; - margin: 7% 20%; + margin: 100px auto; position: relative; z-index: 1; `; const Section = styled.div` position: relative; text-align: center; - margin: 2% 0 0 0; `; const CardsSection = styled.div` display: flex; @@ -174,21 +172,22 @@ const CardsSection = styled.div` margin: 50px auto 0; gap: 25px; position: relative; - max-width: 1250px; z-index: 3; - padding: 18px; `; -const CardsConsumeSection = styled.div` - display: flex; +const CardsConsumeSection = styled(FlexCenter)` flex-direction: column; - justify-content: center; - align-items: center; - padding: 18px; + gap: 25px; `; const BlueFlowerComponent = styled.div` position: absolute; right: 0; - top: -100px; + top: 3100px; + z-index: 0; +`; +const YellowFlowerComponent = styled.div` + position: absolute; + left: 0; + top: 1100px; z-index: 0; `; diff --git a/src/components/views/join/JoinSubscriptionCard.tsx b/src/components/views/join/JoinSubscriptionCard.tsx index ef6c8f252b..1dd34df182 100644 --- a/src/components/views/join/JoinSubscriptionCard.tsx +++ b/src/components/views/join/JoinSubscriptionCard.tsx @@ -5,6 +5,7 @@ import { neutralColors, SublineBold, } from '@giveth/ui-design-system'; +import { ChangeEvent } from 'react'; import { mediaQueries } from '@/lib/constants/constants'; import useNewsletterSubscription from '@/hooks/useNewsletterSubscription'; @@ -44,9 +45,9 @@ const JoinSubscriptionCard = () => { , - ) => setEmail(e.target.value)} + onChange={(e: ChangeEvent) => + setEmail(e.target.value) + } /> {error && ( @@ -68,8 +69,6 @@ const JoinSubscriptionCard = () => { }; const CustomizedButtonStyled = styled(ButtonStyled)` - margin-top: 10px; - min-width: 280px; &:disabled { background-color: ${neutralColors.gray[400]}; color: white; From 38befde7b038f9eea362cee4e9f9b98e97aed671 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 6 Jun 2022 20:17:58 +0430 Subject: [PATCH 255/257] fix harvest all modal sums --- src/components/modals/HarvestAll.tsx | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/components/modals/HarvestAll.tsx b/src/components/modals/HarvestAll.tsx index 112931a8ae..0fddf5ceb7 100644 --- a/src/components/modals/HarvestAll.tsx +++ b/src/components/modals/HarvestAll.tsx @@ -62,6 +62,7 @@ import { getPoolIconWithName } from '../cards/BaseStakingCard'; import { IModal } from '@/types/common'; import { useAppSelector } from '@/features/hooks'; import { LiquidityPosition } from '@/types/nfts'; +import { Flex } from '../styled-components/Flex'; import type { TokenDistroHelper } from '@/lib/contractHelper/TokenDistroHelper'; interface IHarvestAllModalProps extends IModal { @@ -418,10 +419,9 @@ export const HarvestAllModal: FC = ({ {givBackStream != 0 && ( <> - Recieved from GIVbacks + [ Recieved from GIVbacks - + {formatWeiHelper( givBackStream, config.TOKEN_PRECISION, @@ -432,13 +432,18 @@ export const HarvestAllModal: FC = ({ {tokenSymbol}/week + + + + ] + + } direction={'left'} > From 8d1ea1a3325df782945f54b37b0b6e0b79a5f299 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 6 Jun 2022 20:18:05 +0430 Subject: [PATCH 256/257] fix mobile size --- src/components/modals/HarvestAll.sc.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/components/modals/HarvestAll.sc.tsx b/src/components/modals/HarvestAll.sc.tsx index 393cb8bb43..afc6b4e209 100644 --- a/src/components/modals/HarvestAll.sc.tsx +++ b/src/components/modals/HarvestAll.sc.tsx @@ -10,11 +10,15 @@ import { B, } from '@giveth/ui-design-system'; import styled from 'styled-components'; +import { mediaQueries } from '@/lib/constants/constants'; import { Flex } from '../styled-components/Flex'; export const HarvestAllModalContainer = styled.div` - width: 686px; + width: 100%; + ${mediaQueries.tablet} { + width: 686px; + } `; export const USDAmount = styled(P)` From b7a6cd970238344aa316115b2d78b5e1999b9682 Mon Sep 17 00:00:00 2001 From: Cherik Date: Mon, 6 Jun 2022 20:37:23 +0430 Subject: [PATCH 257/257] increase version number --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 0677608ba9..2569a640f3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "givethdapp", - "version": "2.0.6", + "version": "2.0.7", "private": true, "scripts": { "build": "next build",