diff --git a/Dockerfile b/Dockerfile index d46fa51c..846a4c62 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,25 +1,73 @@ FROM node:18-alpine AS deps -RUN apk add --no-cache libc6-compat WORKDIR /app COPY package.json package-lock.json ./ -RUN npm ci +RUN apk add --no-cache libc6-compat && npm ci FROM node:18-alpine AS builder WORKDIR /app + +# args +ARG APP_ENV +ARG NODE_ENV +ARG MONGODB +ARG GAMMA_SERVICE_URL +ARG GRAPH_URL +ARG WALLET_CONNECT_PROJECT_ID +ARG NODE_PROVIDER_MUMBAI_URL +ARG NODE_PROVIDER_BSC_TESTNET_URL +ARG NODE_PROVIDER_OPBNB_TESTNET +ARG MAIL_CLIENT +ARG MAIL_FROM +ARG MAIL_TO +ARG MAIL_ETHEREAL_HOST +ARG MAIL_ETHEREAL_PORT +ARG MAIL_ETHEREAL_USER +ARG MAIL_ETHEREAL_PSWD +ARG MAIL_SG_KEY +ARG MAIL_SG_FROM +ARG NEXT_PUBLIC_STORAGE_URL_ALPHA +ARG NEXT_PUBLIC_STORAGE_URL_GAMMA +ARG NEXT_PUBLIC_ADMIN_ACCOUNTS + + +# env +ENV APP_ENV $APP_ENV +ENV NODE_ENV $NODE_ENV +ENV MONGODB $MONGODB +ENV GAMMA_SERVICE_URL $GAMMA_SERVICE_URL +ENV GRAPH_URL $GRAPH_URL +ENV WALLET_CONNECT_PROJECT_ID $WALLET_CONNECT_PROJECT_ID +ENV NODE_PROVIDER_MUMBAI_URL $NODE_PROVIDER_MUMBAI_URL +ENV NODE_PROVIDER_BSC_TESTNET_URL $NODE_PROVIDER_BSC_TESTNET_URL +ENV NODE_PROVIDER_OPBNB_TESTNET $NODE_PROVIDER_OPBNB_TESTNET +ENV MAIL_CLIENT $MAIL_CLIENT +ENV MAIL_FROM $MAIL_FROM +ENV MAIL_TO $MAIL_TO +ENV MAIL_ETHEREAL_HOST $MAIL_ETHEREAL_HOST +ENV MAIL_ETHEREAL_PORT $MAIL_ETHEREAL_PORT +ENV MAIL_ETHEREAL_USER $MAIL_ETHEREAL_USER +ENV MAIL_ETHEREAL_PSWD $MAIL_ETHEREAL_PSWD +ENV MAIL_SG_KEY $MAIL_SG_KEY +ENV MAIL_SG_FROM $MAIL_SG_FROM +ENV NEXT_PUBLIC_STORAGE_URL_ALPHA $NEXT_PUBLIC_STORAGE_URL_ALPHA +ENV NEXT_PUBLIC_STORAGE_URL_GAMMA $NEXT_PUBLIC_STORAGE_URL_GAMMA +ENV NEXT_PUBLIC_ADMIN_ACCOUNTS $NEXT_PUBLIC_ADMIN_ACCOUNTS + + COPY --from=deps /app/node_modules ./node_modules COPY . . +RUN echo "***********************" +RUN env +RUN echo "***********************" RUN npm run build FROM node:18-alpine AS runner WORKDIR /app -ENV NODE_ENV=production -RUN addgroup --system --gid 1001 nodejs -RUN adduser --system --uid 1001 nextjs +ENV NODE_ENV production +RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nextjs COPY --from=builder /app/next.config.js ./ COPY --from=builder /app/public ./public COPY --from=builder /app/package.json ./package.json -# Automatically leverage output traces to reduce image size -# https://nextjs.org/docs/advanced-features/output-file-tracing COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static diff --git a/README.md b/README.md index 55e70c81..83918e37 100644 --- a/README.md +++ b/README.md @@ -45,27 +45,15 @@ PORT=3000 # server-side MONGODB='mongodb://localhost:27017' -NODE_ENV='development' -APP_ENV='development' GAMMA_SERVICE_URL='https://gamma-microservice-7bteynlhua-uc.a.run.app' GRAPH_URL='https://api.thegraph.com/subgraphs/name/tomasfrancizco/nof_polygon' WALLET_CONNECT_PROJECT_ID={you project ID from walletconnect.com} CHAIN_NODE_PROVIDER_URL='https://polygon-mumbai.g.alchemy.com/v2/YOUR_API_KEY' # Client-side +NEXT_PUBLIC_APP_ENV='development' NEXT_PUBLIC_STORAGE_URL_ALPHA='https://storage.googleapis.com/nof-alpha' NEXT_PUBLIC_STORAGE_URL_GAMMA='https://storage.googleapis.com/nof-gamma' -NEXT_PUBLIC_CHAIN_NAME='mumbai' -NEXT_PUBLIC_CHAIN_ID='0x13881' -NEXT_PUBLIC_CHAIN_CURRENCY='MATIC' -NEXT_PUBLIC_CHAIN_RPC_URL='https://rpc-mumbai.maticvigil.com' -NEXT_PUBLIC_CHAIN_EXPLORER_URL='https://mumbai.polygonscan.com' -NEXT_PUBLIC_DAI_ADDRESS='' -NEXT_PUBLIC_ALPHA_ADDRESS='' -NEXT_PUBLIC_GAMMA_PACKS_ADDRESS='' -NEXT_PUBLIC_GAMMA_CARDS_ADDRESS='' -NEXT_PUBLIC_GAMMA_OFFERS_ADDRESS='' -NEXT_PUBLIC_GAMMA_TICKETS_ADDRESS='' NEXT_PUBLIC_ADMIN_ACCOUNTS='0x35dad65F60c1A32c9895BE97f6bcE57D32792E83,0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266' ``` @@ -79,9 +67,9 @@ NEXT_PUBLIC_CHAIN_CURRENCY='ETH' NEXT_PUBLIC_CHAIN_RPC_URL='http://localhost:8545' ``` -## Quick commands +# Quick commands -### Install dependencies +## Install dependencies ```sh - yarn install # with yarn @@ -101,19 +89,19 @@ yarn config delete proxy yarn --network-timeout 100000 ``` -### Run App +## Run App ```sh npm run dev / yarn dev ``` -### Use App +## Use App ```sh Open browser in http://localhost:3000/ ``` -### Mock Data +## Mock Data You can load mock data from the alpha, gamma collections and have DAIs in your wallet in a local environment, with these commands: @@ -125,9 +113,9 @@ yarn deploy-mock-data # run the mock data # Then upload the hardhat addresses to your wallets ``` -## Contribution +# Contribution -### Commit changes +## Commit changes The application uses a linter for commit messages, requiring them to be specified in the following format: @@ -166,3 +154,7 @@ git reset --soft HEAD~1 ``` For more information, refer to: [commitlint](https://commitlint.js.org/#/). + +# Links + +- BNB & opBNB node provider: [nodereal.io](https://nodereal.io/) diff --git a/cloudbuild.yaml b/cloudbuild.yaml new file mode 100644 index 00000000..b8ba2f4d --- /dev/null +++ b/cloudbuild.yaml @@ -0,0 +1,99 @@ +steps: + # Para para generar un .env para que sea tomado por el step de build. + # Las variables serán tomadas de la definición del "trigger", + # "variables de sustitución", en Google Cloud Build. + # en gcp, se tiene que poner como nombre de cada variable, el unserscore + # como prefijo. Ejemplo: "_APP_ENV" + # + - name: 'gcr.io/cloud-builders/npm' + id: CreateEnv + args: ['run', 'create-env'] + env: + - NODE_ENV=${_NODE_ENV} + - MONGODB=${_MONGODB} + - GAMMA_SERVICE_URL=${_GAMMA_SERVICE_URL} + - GRAPH_URL=${_GRAPH_URL} + - WALLET_CONNECT_PROJECT_ID=${_WALLET_CONNECT_PROJECT_ID} + - NODE_PROVIDER_MUMBAI_URL=${_CHAIN_NODE_PROVIDER_URL} + - NODE_PROVIDER_BSC_TESTNET_URL=${_NODE_PROVIDER_BSC_TESTNET_URL} + - NODE_PROVIDER_OPBNB_TESTNET=${_NODE_PROVIDER_OPBNB_TESTNET} + - MAIL_CLIENT=${_MAIL_CLIENT} + - MAIL_FROM=${_MAIL_FROM} + - MAIL_TO=${_MAIL_TO} + - MAIL_ETHEREAL_HOST=${_MAIL_ETHEREAL_HOST} + - MAIL_ETHEREAL_PORT=${_MAIL_ETHEREAL_PORT} + - MAIL_ETHEREAL_USER=${_MAIL_ETHEREAL_USER} + - MAIL_ETHEREAL_PSWD=${_MAIL_ETHEREAL_PSWD} + - MAIL_SG_KEY=${_MAIL_SG_KEY} + - MAIL_SG_FROM=${_MAIL_SG_FROM} + - NEXT_PUBLIC_APP_ENV=${_NEXT_PUBLIC_APP_ENV} + - NEXT_PUBLIC_STORAGE_URL_ALPHA=${_NEXT_PUBLIC_STORAGE_URL_ALPHA} + - NEXT_PUBLIC_STORAGE_URL_GAMMA=${_NEXT_PUBLIC_STORAGE_URL_GAMMA} + - NEXT_PUBLIC_ADMIN_ACCOUNTS=${_NEXT_PUBLIC_ADMIN_ACCOUNTS} + + + # build the container images + - name: "gcr.io/cloud-builders/docker" + id: Build + args: [ + "build", + "--no-cache", + "-t", + "$_AR_HOSTNAME/$PROJECT_ID/cloud-run-source-deploy/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA", + "--build-arg", "NODE_ENV=${_NODE_ENV}", + "--build-arg", "MONGODB=${_MONGODB}", + "--build-arg", "GAMMA_SERVICE_URL=${_GAMMA_SERVICE_URL}", + "--build-arg", "GRAPH_URL=${_GRAPH_URL}", + "--build-arg", "WALLET_CONNECT_PROJECT_ID=${_WALLET_CONNECT_PROJECT_ID}", + "--build-arg", "NODE_PROVIDER_MUMBAI_URL=${_NODE_PROVIDER_MUMBAI_URL}", + "--build-arg", "NODE_PROVIDER_BSC_TESTNET_URL=${_NODE_PROVIDER_BSC_TESTNET_URL}", + "--build-arg", "NODE_PROVIDER_OPBNB_TESTNET=${_NODE_PROVIDER_OPBNB_TESTNET}", + "--build-arg", "MAIL_CLIENT=${_MAIL_CLIENT}", + "--build-arg", "MAIL_FROM=${_MAIL_FROM}", + "--build-arg", "MAIL_TO=${_MAIL_TO}", + "--build-arg", "MAIL_ETHEREAL_HOST=${_MAIL_ETHEREAL_HOST}", + "--build-arg", "MAIL_ETHEREAL_PORT=${_MAIL_ETHEREAL_PORT}", + "--build-arg", "MAIL_ETHEREAL_USER=${_MAIL_ETHEREAL_USER}", + "--build-arg", "MAIL_ETHEREAL_PSWD=${_MAIL_ETHEREAL_PSWD}", + "--build-arg", "MAIL_SG_KEY=${_MAIL_SG_KEY}", + "--build-arg", "MAIL_SG_FROM=${_MAIL_SG_FROM}", + "--build-arg", "NEXT_PUBLIC_APP_ENV=${_NEXT_PUBLIC_APP_ENV}", + "--build-arg", "NEXT_PUBLIC_STORAGE_URL_ALPHA=${_NEXT_PUBLIC_STORAGE_URL_ALPHA}", + "--build-arg", "NEXT_PUBLIC_STORAGE_URL_GAMMA=${_NEXT_PUBLIC_STORAGE_URL_GAMMA}", + "--build-arg", "NEXT_PUBLIC_ADMIN_ACCOUNTS=${_NEXT_PUBLIC_ADMIN_ACCOUNTS}", + + "." + ] + + # push the container images to Container Registry + - name: "gcr.io/cloud-builders/docker" + id: Push + args: [ + "push", + "$_AR_HOSTNAME/$PROJECT_ID/cloud-run-source-deploy/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA" + ] + + # Deploy container images to Cloud Run + - name: "gcr.io/cloud-builders/gcloud" + id: Deploy + entrypoint: gcloud + args: [ + "run", + "deploy", + "$_SERVICE_NAME", + "--platform", + "managed", + "--region", + "$_DEPLOY_REGION", + "--image", + "$_AR_HOSTNAME/$PROJECT_ID/cloud-run-source-deploy/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA", + "--labels", + "managed-by=gcp-cloud-build-deploy-cloud-run,commit-sha=$COMMIT_SHA,gcb-build-id=$BUILD_ID,gcb-trigger-id=$_TRIGGER_ID", + "--quiet", + "--allow-unauthenticated", + ] +images: + - $_AR_HOSTNAME/$PROJECT_ID/cloud-run-source-deploy/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA + +options: + logging: CLOUD_LOGGING_ONLY diff --git a/example_env b/example_env index 4a30112d..e1d5830c 100644 --- a/example_env +++ b/example_env @@ -1,7 +1,6 @@ // server-site MONGODB='mongodb://localhost:27017' NODE_ENV='development' // development, production -APP_ENV='development' GAMMA_SERVICE_URL='https://gamma-microservice-7bteynlhua-uc.a.run.app' GRAPH_URL='https://api.thegraph.com/subgraphs/name/tomasfrancizco/nof_polygon' MAIL_CLIENT= // sendgrid | ethereal @@ -17,16 +16,7 @@ WALLET_CONNECT_PROJECT_ID='your_project_id_api_key' CHAIN_NODE_PROVIDER_URL='https://polygon-mumbai.g.alchemy.com/YOUR_API_KEY' // client-side +NEXT_PUBLIC_APP_ENV='development' NEXT_PUBLIC_STORAGE_URL_ALPHA='https://storage.googleapis.com/nof-alpha' NEXT_PUBLIC_STORAGE_URL_GAMMA='https://storage.googleapis.com/nof-gamma' -NEXT_PUBLIC_CHAIN_NAME='localhost' -NEXT_PUBLIC_CHAIN_ID='0x539' // '0x539' = 1337 (hardhat node) | '0x89' = Polygon Mainnet | '0x13881' = Mumbai -NEXT_PUBLIC_CHAIN_CURRENCY='ETH' -NEXT_PUBLIC_CHAIN_RPC_URL='http://localhost:8545' -NEXT_PUBLIC_CHAIN_EXPLORER_URL='https://mumbai.polygonscan.com' NEXT_PUBLIC_ADMIN_ACCOUNTS='0x...,0X....,0xfa3....' // accounts separated by a comma -NEXT_PUBLIC_DAI_ADDRESS='0x59876b33dd6e725Da632B4DB50d90d33ab022dB6' -NEXT_PUBLIC_ALPHA_ADDRESS='0x1772F33b587B4ed32f59Dc6B09B9e994616C1eCB' -NEXT_PUBLIC_GAMMA_PACKS_ADDRESS='0xc0a2630f551106190d95C2348e02E400478e711c' -NEXT_PUBLIC_GAMMA_CARDS_ADDRESS='0xa888449f2CB7AB034D08051Bf1a9D7402DE959ab' -NEXT_PUBLIC_GAMMA_OFFERS_ADDRESS='' \ No newline at end of file diff --git a/package.json b/package.json index a647ee4c..a4954bd4 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ "dev": "next dev", "start": "next start", "build": "next build", + "create-env": "printenv > .env", "serve": "yarn build && npm i -g http-server && http-server ./.next", "export": "yarn build && next export -o _static", "clear-all": "rm -rf .next _static node_modules", diff --git a/public/locales/br/common.json b/public/locales/br/common.json index faa73b77..cd75d276 100644 --- a/public/locales/br/common.json +++ b/public/locales/br/common.json @@ -156,7 +156,7 @@ "account_connect": "Conectar", "account_disconnect": "Desconectar", - "account_invalid_network": "Você está conectado a uma rede inválida. Por favor, mude para a rede {NETWORK}.", + "account_invalid_network": "Você está conectado a uma rede inválida. Por favor, mude para uma dessas redes: {NETWORKS}.", "account_no_metamask": "Por favor instale o metamask para usar este site", "account_switch": "Mudar de rede", "account_text_copied": "Copiado", diff --git a/public/locales/en/common.json b/public/locales/en/common.json index 3ca7b35c..2b12054a 100644 --- a/public/locales/en/common.json +++ b/public/locales/en/common.json @@ -156,7 +156,7 @@ "account_connect": "Connect", "account_disconnect": "Disconnect", - "account_invalid_network": "You are connected to an invalid network. Please, switch to {NETWORK} network.", + "account_invalid_network": "You are connected to an invalid network. Please switch to one of these networks: {NETWORKS}.", "account_no_metamask": "Please install metamask to use this website", "account_switch": "Switch Network", "account_text_copied": "Copied", diff --git a/public/locales/es/common.json b/public/locales/es/common.json index c63b08b0..489cd753 100644 --- a/public/locales/es/common.json +++ b/public/locales/es/common.json @@ -157,7 +157,7 @@ "account_connect": "Conectar", "account_disconnect": "Desconectar", - "account_invalid_network": "Estás conectado a una red no válida. Por favor, cambia a la red {NETWORK}.", + "account_invalid_network": "Estás conectado a una red no válida. Por favor, cambia a alguna de estas redes: {NETWORKS}.", "account_no_metamask": "Por favor instale metamask para usar este sitio web", "account_switch": "Cambiar Red", "account_text_copied": "Copiado", diff --git a/src/components/Navbar/AccountInfo.jsx b/src/components/Navbar/AccountInfo.jsx index 0be1a57e..39d6b5ee 100644 --- a/src/components/Navbar/AccountInfo.jsx +++ b/src/components/Navbar/AccountInfo.jsx @@ -6,9 +6,8 @@ import Swal from 'sweetalert2' import { HiOutlineClipboardDocument } from 'react-icons/hi2' import { GoLinkExternal } from 'react-icons/go' import { AiOutlineSend } from 'react-icons/ai' -// import { MdOutlinePublishedWithChanges } from 'react-icons/md' + import { useWeb3Context, useLayoutContext } from '../../hooks' -import { NETWORK, CONTRACTS } from '../../config' import { getBalance, getTokenName, transfer } from '../../services/dai' import { emitError, emitInfo, emitSuccess } from '../../utils/alert' import { checkInputAddress, checkFloatValue1GTValue2 } from '../../utils/InputValidators' @@ -20,10 +19,11 @@ const AccountInfo = ({ showAccountInfo, setShowAccountInfo }) => { walletAddress, connectWallet, disconnectWallet, + getCurrentNetwork, isValidNetwork, + enabledNetworkNames, daiContract, - isConnected // , - // switchOrCreateNetwork + isConnected } = useWeb3Context() const { startLoading, stopLoading } = useLayoutContext() const [copiedTextVisible, setCopiedTextVisible] = useState(false) @@ -31,6 +31,8 @@ const AccountInfo = ({ showAccountInfo, setShowAccountInfo }) => { const [walletBalance, setWalletBalance] = useState(0) const [tokenName, setTokenName] = useState('') + const currentNwk = getCurrentNetwork() + const fetchTokenName = async () => { if (!walletAddress || !daiContract || !isValidNetwork) return try { @@ -172,8 +174,10 @@ const AccountInfo = ({ showAccountInfo, setShowAccountInfo }) => { }`} > {isValidNetwork - ? NETWORK.chainName - : t('account_invalid_network').replace('{NETWORK}', NETWORK.chainName)} + ? currentNwk + ? currentNwk.config.chainName + : '' + : t('account_invalid_network').replace('{NETWORKS}', enabledNetworkNames)}

{/*!isValidNetwork && ( @@ -204,7 +208,7 @@ const AccountInfo = ({ showAccountInfo, setShowAccountInfo }) => {
{ className='account__info__icon' /> {}, disconnectWallet: () => {}, - switchOrCreateNetwork: () => {} + getCurrentNetwork: () => {} } const Web3Context = createContext(initialState) @@ -37,14 +37,6 @@ function Web3ContextProvider({ children }) { const { walletProvider } = useWeb3ModalProvider() const { disconnect } = useDisconnect() - const mumbai = { - chainId: hexToDec(NETWORK.chainId), - name: NETWORK.chainName, - currency: NETWORK.chainCurrency, - explorerUrl: NETWORK.chainExplorerUrl, - rpcUrl: NETWORK.ChainRpcUrl - } - const metadata = { name: 'NoF', description: 'Number One Fan', @@ -52,16 +44,42 @@ function Web3ContextProvider({ children }) { icons: ['https://avatars.githubusercontent.com/u/37784886'] } + const enabledNetworks = Object.keys(NETWORKS) + .filter((networkKey) => { + const network = NETWORKS[networkKey] + return network.config.enabled === 'true' && network.config.environment === environment + }) + .map((networkKey) => { + const network = NETWORKS[networkKey] + return { + web3ModalConfig: { + chainId: hexToDec(network.config.chainId), + name: network.config.chainName, + currency: network.config.chainCurrency, + explorerUrl: network.config.chainExplorerUrl, + rpcUrl: network.config.ChainRpcUrl + }, + config: network.config, + contracts: network.contracts + } + }) + + const enabledNetworkNames = enabledNetworks + .map((network) => network.web3ModalConfig.name) + .join(', ') + const enabledNetworkChainIds = enabledNetworks.map((network) => network.web3ModalConfig.chainId) + const webModalConfigs = enabledNetworks.map((network) => network.web3ModalConfig) + createWeb3Modal({ ethersConfig: defaultConfig({ metadata, - defaultChainId: hexToDec(NETWORK.chainId), + defaultChainId: hexToDec(enabledNetworks[0].config.chainId), enableEIP6963: true, enableInjected: true, enableCoinbase: true, - rpcUrl: NETWORK.ChainRpcUrl + rpcUrl: enabledNetworks[0].config.ChainRpcUrl }), - chains: [mumbai], + chains: webModalConfigs, projectId: walletConnectProjectId || 'ND', enableAnalytics: true, themeMode: 'light', @@ -86,13 +104,22 @@ function Web3ContextProvider({ children }) { accountAddress = await web3Provider.getSigner().getAddress() const chainIdHex = decToHex(_chainId) - if (chainIdHex === NETWORK.chainId) { + const networkKeys = Object.keys(NETWORKS) + const isValidNetwork = networkKeys.some((networkKey) => { + const network = NETWORKS[networkKey] + return ( + network.config.enabled === 'true' && + network.config.environment === environment && + network.config.chainId === chainIdHex + ) + }) + + if (isValidNetwork) { connectContracts(web3Provider.getSigner()) setIsValidNetwork(true) } else { setIsValidNetwork(false) setWeb3Error('account_invalid_network') - // await switchOrCreateNetwork() } return [web3Provider, accountAddress] } catch (e) { @@ -113,32 +140,39 @@ function Web3ContextProvider({ children }) { } } + function getCurrentNetwork() { + const network = enabledNetworks.find((network) => network.web3ModalConfig.chainId === chainId) + return network ? network : null + } + function connectContracts(_signer) { try { - const daiContractInstance = new ethers.Contract(CONTRACTS.daiAddress, daiAbi.abi, _signer) + const _contracts = getCurrentNetwork().contracts + + const daiContractInstance = new ethers.Contract(_contracts.daiAddress, daiAbi.abi, _signer) const alphaContractInstance = new ethers.Contract( - CONTRACTS.alphaAddress, + _contracts.alphaAddress, alphaAbi.abi, _signer ) const gammaPacksContractInstance = new ethers.Contract( - CONTRACTS.gammaPackAddress, + _contracts.gammaPackAddress, gammaPacksAbi.abi, _signer ) const gammaCardsContractInstance = new ethers.Contract( - CONTRACTS.gammaCardsAddress, + _contracts.gammaCardsAddress, gammaCardsAbi.abi, _signer ) const gammaOffersContractInstance = new ethers.Contract( - CONTRACTS.gammaOffersAddress, + _contracts.gammaOffersAddress, gammaOffersAbi.abi, _signer ) const gammaTicketsContractInstance = new ethers.Contract( - CONTRACTS.gammaTicketsAddress, + _contracts.gammaTicketsAddress, gammaTicketsAbi.abi, _signer ) @@ -220,47 +254,6 @@ function Web3ContextProvider({ children }) { return parseInt(str, 16) } - async function switchOrCreateNetwork() { - // open({ view: 'Networks' }) - - if (window && window.ethereum) { - try { - await window.ethereum.request({ - method: 'wallet_switchEthereumChain', - params: [{ chainId: NETWORK.chainId }] - }) - setIsValidNetwork(true) - } catch (error) { - if (error.code === 4902) { - try { - await window.ethereum.request({ - method: 'wallet_addEthereumChain', - params: [ - { - chainId: NETWORK.chainId, - chainName: NETWORK.chainName, - rpcUrls: [NETWORK.ChainRpcUrl], - nativeCurrency: { - name: NETWORK.chainCurrency, - symbol: NETWORK.chainCurrency, - decimals: 18 - }, - blockExplorerUrls: [NETWORK.chainExplorerUrl] - } - ] - }) - } catch (e) { - console.error({ e }) - } - } else { - console.error('Error switching network', error) - } - } - } else { - console.error('Metamask or compatible wallet not installed') - } - } - useEffect(() => { if (window && typeof window.ethereum === 'undefined') { setWeb3Error('account_no_metamask') @@ -277,7 +270,7 @@ function Web3ContextProvider({ children }) { const _chanIdHex = decToHex(newChain) setIsValidNetwork(false) - if (_chanIdHex === NETWORK.chainId) { + if (enabledNetworkChainIds.includes(_chanIdHex)) { const provider = new ethers.providers.Web3Provider(window.ethereum, 'any') const signer = provider.getSigner() connectContracts(signer) @@ -300,9 +293,10 @@ function Web3ContextProvider({ children }) { web3Error, isConnected, isValidNetwork, + enabledNetworkNames, connectWallet, disconnectWallet, - switchOrCreateNetwork + getCurrentNetwork } return {children} diff --git a/src/pages/api/match.js b/src/pages/api/match.js index d48828da..ad5a2589 100644 --- a/src/pages/api/match.js +++ b/src/pages/api/match.js @@ -1,3 +1,4 @@ +/* import { ethers } from 'ethers' import { NETWORK, CONTRACTS } from '../../config' import gammaCardsAbi from '../../context/abis/GammaCards.v5.sol/NofGammaCardsV5.json' @@ -69,3 +70,4 @@ function getNotPresentCards(userCards1, userCards2) { }) return notPresentCards } +*/ diff --git a/src/pages/api/ping.js b/src/pages/api/ping.js index 06cc5c59..fa615caa 100644 --- a/src/pages/api/ping.js +++ b/src/pages/api/ping.js @@ -1,4 +1,4 @@ -import { combinedVariables } from '../../config' +// import { combinedVariables } from '../../config' export default async function handler(req, res) { try { @@ -10,7 +10,8 @@ export default async function handler(req, res) { } res.setHeader('Content-Type', 'application/json') - res.status(200).json(combinedVariables) + res.status(200).json('ok') + // res.status(200).json(combinedVariables) } catch (error) { console.error(error) res.status(500).json({ diff --git a/src/sections/Alpha/AlphaAlbums.jsx b/src/sections/Alpha/AlphaAlbums.jsx index da461fd2..fc4e5ffc 100644 --- a/src/sections/Alpha/AlphaAlbums.jsx +++ b/src/sections/Alpha/AlphaAlbums.jsx @@ -1,5 +1,5 @@ import PropTypes from 'prop-types' -import { useState } from 'react' +import { useState, useEffect } from 'react' import { Swiper, SwiperSlide } from 'swiper/react' import 'swiper/css' import 'swiper/css/effect-fade' @@ -15,9 +15,10 @@ import SwiperCore, { EffectCards } from 'swiper' import Swal from 'sweetalert2' -import { storageUrlAlpha, openSeaUrlAlpha } from '../../config' +import { storageUrlAlpha } from '../../config' import { useTranslation } from 'next-i18next' import CustomImage from '../../components/CustomImage' +import { useWeb3Context } from '../../hooks' SwiperCore.use([Parallax, Autoplay, Navigation, Pagination, Scrollbar, A11y]) @@ -25,11 +26,26 @@ const AlphaAlbums = ({ albums, clickFromAlbums, setSeasonName }) => { const { t } = useTranslation() const noAlbumMessage = t('juega_para_completar') const [seasonNameAlbum, setSeasonNameAlbums] = useState('') + const { getCurrentNetwork, alphaContract } = useWeb3Context() + const [openSeaUrl, setOpenSeaUrl] = useState('') + + useEffect(() => { + const ntwk = getCurrentNetwork() + if (ntwk && alphaContract) { + let openSeaUrlGamma = '' + if (ntwk.config.chainOpenSeaBaseUrl === '') { + openSeaUrlGamma = `${ntwk.config.chainNftUrl}` + } else { + openSeaUrlGamma = `${ntwk.config.chainOpenSeaBaseUrl}/${alphaContract.address}` + } + setOpenSeaUrl(openSeaUrlGamma) + } + }, [getCurrentNetwork, alphaContract]) function handleRedirectAlbum(album) { if (album[0].completion === 5) { // Open the album on OpenSea if the completion status is 5 - window.open(`${openSeaUrlAlpha}/${album[0].tokenId}`, '_blank') + window.open(`${openSeaUrl}/${album[0].tokenId}`, '_blank') } else { // Otherwise, display a message to the user and perform some actions setSeasonName(album[0].season) diff --git a/src/sections/Alpha/AlphaMain.jsx b/src/sections/Alpha/AlphaMain.jsx index 4dccff56..e3e96f5b 100644 --- a/src/sections/Alpha/AlphaMain.jsx +++ b/src/sections/Alpha/AlphaMain.jsx @@ -4,7 +4,7 @@ import 'swiper/css/bundle' import Swiper from 'swiper/bundle' import AlphaAlbums from './AlphaAlbums' import Rules from '../Common/Rules' -import { storageUrlAlpha, CONTRACTS } from '../../config' +import { storageUrlAlpha } from '../../config' import { fetchDataAlpha } from '../../services/alpha' import { checkApproved } from '../../services/dai' import CustomImage from '../../components/CustomImage' @@ -14,8 +14,6 @@ import { useTranslation } from 'next-i18next' import { useWeb3Context, useLayoutContext } from '../../hooks' import { checkInputAddress } from '../../utils/InputValidators' -import { NETWORK } from '../../config' - const vidas = [ '/images/alpha/vida0.png', '/images/alpha/vida1.png', @@ -50,8 +48,15 @@ const AlphaMain = () => { const [, setDisableTransfer] = useState(false) const [seasonFolder, setSeasonFolder] = useState(null) const { startLoading, stopLoading } = useLayoutContext() - const { walletAddress, daiContract, alphaContract, connectWallet, isConnected, isValidNetwork } = - useWeb3Context() + const { + walletAddress, + daiContract, + alphaContract, + connectWallet, + isConnected, + isValidNetwork, + enabledNetworkNames + } = useWeb3Context() const [showRules, setShowRules] = useState(false) const [albums, setAlbums] = useState(null) const [showMain, setShowMain] = useState(false) @@ -249,7 +254,7 @@ const AlphaMain = () => { const authorizeDaiContract = async () => { try { const authorization = await daiContract.approve( - CONTRACTS.alphaAddress, + alphaContract.address, ethers.constants.MaxUint256, { gasLimit: 2500000 } ) @@ -363,7 +368,7 @@ const AlphaMain = () => { setError(t('no_mas_packs')) } else { if (checkBalance(walletAddress)) { - checkApproved(daiContract, walletAddress, CONTRACTS.alphaAddress) + checkApproved(daiContract, walletAddress, alphaContract.address) .then((res) => { const comprarPack = async (price, name) => { const pack = await alphaContract.buyPack(price, name, { @@ -500,19 +505,10 @@ const AlphaMain = () => { {isConnected && !isValidNetwork && (
- {t('account_invalid_network').replace('{NETWORK}', NETWORK.chainName)} + {t('account_invalid_network').replace('{NETWORKS}', enabledNetworkNames)}
)} - {/*isConnected && !isValidNetwork && ( - - )*/} - )*/}