From 94a6cc23964fc0d8328b1170447c3e00e0a60adc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcus=20Vin=C3=ADcius?= Date: Fri, 10 Feb 2023 09:24:59 -0300 Subject: [PATCH 01/13] fix: adding condition to disabled button (#864) --- components/bounty/tabs-sections/item-sections.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/components/bounty/tabs-sections/item-sections.tsx b/components/bounty/tabs-sections/item-sections.tsx index 903afaf1f7..f608f2c4d6 100644 --- a/components/bounty/tabs-sections/item-sections.tsx +++ b/components/bounty/tabs-sections/item-sections.tsx @@ -125,6 +125,7 @@ function ItemSections({ data, isProposal }: ItemProps) { review: true })) }} + disabled={item?.status === "draft" ? true : false} > From 35ac31f34946ece0bd1446df31947fb835ad4ee0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcus=20Vin=C3=ADcius?= Date: Fri, 10 Feb 2023 16:46:19 -0300 Subject: [PATCH 02/13] adjusting to render explorePage on index app (#865) --- pages/index.tsx | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/pages/index.tsx b/pages/index.tsx index 9586ecaaf2..ccb77fc30d 100644 --- a/pages/index.tsx +++ b/pages/index.tsx @@ -1,20 +1,11 @@ -import { useEffect } from "react"; - import { serverSideTranslations } from "next-i18next/serverSideTranslations"; -import { useRouter } from "next/router"; import { GetServerSideProps } from "next/types"; -import LoadingGlobal from "components/loading-global"; +import ExplorePage from "./explore"; export default function Index() { - const { replace } = useRouter(); - - useEffect(() => { - replace(`/explore`); - }, []); - return( - + ); } From 2864b29cc763503d1c58997204d2d07fcebc9ed2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcus=20Vin=C3=ADcius?= Date: Mon, 13 Feb 2023 11:33:20 -0300 Subject: [PATCH 03/13] Bepro 1352 on my network registry i should be able to change the network creation amount and fee (#861) * adding handleAmountcreate and handleFeeCreate * adding updates registry values on dao-service * adding translatings * adding setup translations * adding new types to transactions * fix warning strokeWidth * adding new inputs to registry-settings component * adjusting warningSpan --- assets/icons/transactions/settings.tsx | 18 ++-- .../my-network-settings/registry-settings.tsx | 95 ++++++++++++++++--- components/transaction-type.tsx | 2 + components/transactions-icon.tsx | 4 +- interfaces/enums/transaction-types.ts | 4 +- pages/[network]/profile/my-network.tsx | 1 + public/locales/en/common.json | 4 +- public/locales/en/custom-network.json | 4 +- services/dao-service.ts | 23 +++++ x-hooks/use-bepro.tsx | 44 ++++++++- 10 files changed, 173 insertions(+), 26 deletions(-) diff --git a/assets/icons/transactions/settings.tsx b/assets/icons/transactions/settings.tsx index 7fddc527a3..f3aefd975a 100644 --- a/assets/icons/transactions/settings.tsx +++ b/assets/icons/transactions/settings.tsx @@ -3,15 +3,15 @@ import { SVGProps } from "react"; export default function SettingsIcon(props: SVGProps) { return ( - - - - - - - - - + + + + + + + + + ); } diff --git a/components/profile/my-network-settings/registry-settings.tsx b/components/profile/my-network-settings/registry-settings.tsx index e9d8b4771a..c723740bf3 100644 --- a/components/profile/my-network-settings/registry-settings.tsx +++ b/components/profile/my-network-settings/registry-settings.tsx @@ -1,3 +1,4 @@ +import { useEffect, useState } from "react"; import { Col, Row } from "react-bootstrap"; import { useTranslation } from "next-i18next"; @@ -5,26 +6,53 @@ import { useTranslation } from "next-i18next"; import Button from "components/button"; import NetworkParameterInput from "components/custom-network/network-parameter-input"; import TreasuryAddressField from "components/custom-network/treasury-address-field"; +import { FormGroup } from "components/form-group"; import TokensSettings from "components/profile/my-network-settings/tokens-settings"; import { WarningSpan } from "components/warning-span"; +import { useAppState } from "contexts/app-state"; import { useNetworkSettings } from "contexts/network-settings"; import useBepro from "x-hooks/use-bepro"; import { useNetwork } from "x-hooks/use-network"; export default function RegistrySettings({ isGovernorRegistry = false }) { - const { t } = useTranslation(["common", "custom-network"]); + const { t } = useTranslation(["common", "custom-network", "setup"]); + const [networkCreationFeePercentage, setNetworkCreationFeePercentage] = useState() + const [lockAmountForNetworkCreation, setLockAmountForNetworkCreation] = useState() const { fields, settings } = useNetworkSettings(); - + const {state} = useAppState(); const { updateActiveNetwork } = useNetwork(); - const { handleFeeSettings } = useBepro(); + const { handleFeeSettings, handleAmountNetworkCreation, handleFeeNetworkCreation } = useBepro(); async function saveFeeSettings() { await handleFeeSettings(settings?.treasury?.closeFee?.value, settings?.treasury?.cancelFee?.value).then(() => updateActiveNetwork(true)); } + async function saveCreateNetworkFee() { + await handleFeeNetworkCreation(Number(networkCreationFeePercentage)/100) + } + + async function saveCreateNetworkAmount() { + await handleAmountNetworkCreation(lockAmountForNetworkCreation) + } + + useEffect(() => { + if(!state.Service?.active) return; + + state.Service.active.getRegistryCreatorAmount().then(v => setLockAmountForNetworkCreation(v.toFixed())) + state.Service.active.getRegistryCreatorFee().then(v => v.toString()).then(setNetworkCreationFeePercentage) + + },[state.Service.active]) + + function exceedsFeesLimitsError(fee) { + if (+fee < 0 || +fee > 100) + return t("setup:registry.errors.exceeds-limit"); + + return undefined; + } + return ( <> {isGovernorRegistry && ( @@ -62,7 +90,7 @@ export default function RegistrySettings({ isGovernorRegistry = false }) { onChange={fields.cancelFee.setter} /> - + - - {!isGovernorRegistry && ( - - - - )} {isGovernorRegistry && ( + + )} + + + + {isGovernorRegistry && ( + + + + )} + + {!isGovernorRegistry && ( + + + + )} {isGovernorRegistry && } diff --git a/components/transaction-type.tsx b/components/transaction-type.tsx index 1b533f06d1..f2d5d4eda2 100644 --- a/components/transaction-type.tsx +++ b/components/transaction-type.tsx @@ -41,6 +41,8 @@ export default function TransactionType({ type }) { [TransactionTypes.deployNetworkRegistry]: t("transactions.types.deploy-registry"), [TransactionTypes.changeAllowedTokens]: t("transactions.types.change-allowed-tokens"), [TransactionTypes.closeNetwork]: t("transactions.types.close-network"), + [TransactionTypes.amountForNetworkCreation]: t("transactions.types.amount-for-network-creation"), + [TransactionTypes.feeForNetworkCreation]: t("transactions.types.fee-for-network-creation"), }; return ( diff --git a/components/transactions-icon.tsx b/components/transactions-icon.tsx index 67aa014a5d..8f9195a716 100644 --- a/components/transactions-icon.tsx +++ b/components/transactions-icon.tsx @@ -56,7 +56,9 @@ export function TransactionIcon({ type } : TransactionIconProps) { [TransactionTypes.configFees]: , [TransactionTypes.deployNetworkRegistry]: , [TransactionTypes.changeAllowedTokens]: , - [TransactionTypes.closeNetwork]: + [TransactionTypes.closeNetwork]: , + [TransactionTypes.amountForNetworkCreation]: , + [TransactionTypes.feeForNetworkCreation]: }; if (icons[type]) return icons[type]; diff --git a/interfaces/enums/transaction-types.ts b/interfaces/enums/transaction-types.ts index 519defd4bf..929a8622af 100644 --- a/interfaces/enums/transaction-types.ts +++ b/interfaces/enums/transaction-types.ts @@ -32,5 +32,7 @@ export enum TransactionTypes { configFees, deployNetworkRegistry, changeAllowedTokens, - closeNetwork + closeNetwork, + amountForNetworkCreation, + feeForNetworkCreation } diff --git a/pages/[network]/profile/my-network.tsx b/pages/[network]/profile/my-network.tsx index 05ac3c1c81..a6f0aeaa76 100644 --- a/pages/[network]/profile/my-network.tsx +++ b/pages/[network]/profile/my-network.tsx @@ -95,6 +95,7 @@ export const getServerSideProps: GetServerSideProps = async ({ locale }) => { "pull-request", "custom-network", "profile", + "setup", "change-token-modal" ])) } diff --git a/public/locales/en/common.json b/public/locales/en/common.json index 4743bec70d..4f3b81b83e 100644 --- a/public/locales/en/common.json +++ b/public/locales/en/common.json @@ -389,7 +389,9 @@ "config-fees": "Config Fees", "deploy-registry": "Deploy Network Registry", "change-allowed-tokens": "Change Allowed Tokens", - "close-network": "Close Network" + "close-network": "Close Network", + "amount-for-network-creation": "Amount For Network Creation", + "fee-for-network-creation": "Fee For Network Creation" } }, "sort": { diff --git a/public/locales/en/custom-network.json b/public/locales/en/custom-network.json index c92dcd7208..a8d05d09f4 100644 --- a/public/locales/en/custom-network.json +++ b/public/locales/en/custom-network.json @@ -23,7 +23,9 @@ "registry": { "title-governor": "Registry Governor", "config-fees": "Config Fees", - "save-fees-config": "Save fees config" + "save-fees-config": "Save fees config", + "save-create-network-fee": "Save Create Network Fee", + "save-create-network-amount": "Save Create Network Amount" }, "network-info": "Network info", "network-address": "Network Address", diff --git a/services/dao-service.ts b/services/dao-service.ts index fad309ba28..571fd4c1e5 100644 --- a/services/dao-service.ts +++ b/services/dao-service.ts @@ -399,6 +399,20 @@ export default class DAO { return this.registry.changeGlobalFees(closeFee, cancelFee) } + async updateAmountNetworkCreation(amount: string | number) { + if (!this.registry) await this.loadRegistry(); + + return this.registry.changeAmountForNetworkCreation(amount) + } + + async updateFeeNetworkCreation(amount: number) { + if (!this.registry) await this.loadRegistry(); + + return this.registry.changeNetworkCreationFee(amount) + } + + + async getTreasuryRegistry(): Promise { if (!this.registry) await this.loadRegistry(); @@ -453,6 +467,15 @@ export default class DAO { return new BigNumber(creatorAmount); } + async getRegistryCreatorFee(): Promise { + if (!this.registry) await this.loadRegistry(); + + const creatorFee = await this.registry.networkCreationFeePercentage(); + + // networkCreationFeePercentage is aready dived per divisor on sdk + return (creatorFee * 100) + } + async isRegistryGovernor(address: string): Promise { if (!this.registry) await this.loadRegistry(); diff --git a/x-hooks/use-bepro.tsx b/x-hooks/use-bepro.tsx index 6efb137236..5318b3155f 100644 --- a/x-hooks/use-bepro.tsx +++ b/x-hooks/use-bepro.tsx @@ -77,6 +77,46 @@ export default function useBepro() { }); } + async function handleAmountNetworkCreation(amount: string | number): Promise { + return new Promise(async (resolve, reject) => { + const transaction = addTx([{ + type: TransactionTypes.amountForNetworkCreation, + network: state.Service?.network?.active + } as any]); + + dispatch(transaction); + + await state.Service?.active.updateAmountNetworkCreation(amount) + .then((txInfo: TransactionReceipt) => { + dispatch(updateTx([parseTransaction(txInfo, transaction.payload[0] as SimpleBlockTransactionPayload)])) + resolve(txInfo); + }) + .catch((err: { message: string; }) => { + failTx(err, transaction, reject); + }); + }); + } + + async function handleFeeNetworkCreation(amount: number): Promise { + return new Promise(async (resolve, reject) => { + const transaction = addTx([{ + type: TransactionTypes.feeForNetworkCreation, + network: state.Service?.network?.active + } as any]); + + dispatch(transaction); + + await state.Service?.active.updateFeeNetworkCreation(amount) + .then((txInfo: TransactionReceipt) => { + dispatch(updateTx([parseTransaction(txInfo, transaction.payload[0] as SimpleBlockTransactionPayload)])) + resolve(txInfo); + }) + .catch((err: { message: string; }) => { + failTx(err, transaction, reject); + }); + }); + } + async function handleCloseIssue(bountyId: number, proposalContractId: number, tokenUri: string): Promise { @@ -624,6 +664,8 @@ export default function useBepro() { handleFeeSettings, handleDeployRegistry, handleAddAllowedTokens, - handleCloseNetwork + handleCloseNetwork, + handleFeeNetworkCreation, + handleAmountNetworkCreation }; } From 8e5b7176e72e52b271615c86662a5771b29b6732 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcus=20Vin=C3=ADcius?= Date: Mon, 13 Feb 2023 12:35:43 -0300 Subject: [PATCH 04/13] Bepro 1342 after connecting GitHub in setup page user is redirected to networks page (#863) * fix: redirect to setup if network is undefined * rm console * adjusting spaces --- pages/connect-account.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pages/connect-account.tsx b/pages/connect-account.tsx index 1e01c0e912..641bf8b082 100644 --- a/pages/connect-account.tsx +++ b/pages/connect-account.tsx @@ -56,8 +56,10 @@ export default function ConnectAccount() { function redirectToProfile() { const lastNetworkVisited = new WinStorage(`lastNetworkVisited`, 0, 'localStorage'); + const toNetworks = state.Service?.active?.network ? "/networks" : "/setup" + const redirectTo = - lastNetworkVisited.value ? `${lastNetworkVisited.value}/profile` : "/networks"; + lastNetworkVisited.value ? `${lastNetworkVisited.value}/profile` : toNetworks; router.push(redirectTo); } @@ -128,8 +130,6 @@ export default function ConnectAccount() { isLoading={state.spinners?.connectingGH} isDisabled={!state.currentUser?.walletAddress || state.spinners?.connectingGH} /> - -
Date: Mon, 13 Feb 2023 12:35:56 -0300 Subject: [PATCH 05/13] Bepro 1353 change network list items to get data from database instead of blockchain (#859) * adding countOpenIssues to interface network * adjusting endpoint to get new values * adjusting searchNetworks to convert totalValue * refactoring networks-list * adjusting network list item * adjusting search network api logic * adding isNeedCountsAndTotalLock * adding initial structure endpoint search networks * adding new association on network.model * adjusting names on network-list-item * adjusting interface searchNetworkParams * adjusting searchNetworks on networks-list * chaging name interface Network * refactoring logic in search networks endpoint * adjusting new logic searchNetworks in use-api * adding new if to resolve return problem: "0.00" * adjusting type interface total issues * fix build --- components/bounties/list-active-networks.tsx | 2 +- components/network-list-item.tsx | 12 ++- components/networks-list.tsx | 53 ++---------- db/models/network.model.js | 5 ++ helpers/formatNumber.ts | 3 +- interfaces/api.ts | 1 + interfaces/network.ts | 3 +- pages/api/search/networks/active.ts | 2 +- pages/api/search/networks/index.ts | 87 ++++++++++++++++---- x-hooks/use-api.tsx | 9 +- 10 files changed, 101 insertions(+), 76 deletions(-) diff --git a/components/bounties/list-active-networks.tsx b/components/bounties/list-active-networks.tsx index 88ea2d21d3..974a222046 100644 --- a/components/bounties/list-active-networks.tsx +++ b/components/bounties/list-active-networks.tsx @@ -84,7 +84,7 @@ export default function ListActiveNetworks() { - {network?.countIssues || 0}{" "} + {network?.totalIssues || 0}{" "} {t("label_other")} diff --git a/components/network-list-item.tsx b/components/network-list-item.tsx index 905af098a8..3fdcfefe1b 100644 --- a/components/network-list-item.tsx +++ b/components/network-list-item.tsx @@ -1,3 +1,5 @@ +import BigNumber from "bignumber.js"; + import NetworkLogo from "components/network-logo"; import PullRequestLabels from "components/pull-request-labels"; @@ -45,19 +47,23 @@ export default function NetworkListItem({
- {isNotUndefined(network?.totalBounties) ? formatNumberToNScale(network?.totalBounties, 0) : } + {isNotUndefined(network?.totalIssues) ? formatNumberToNScale(network?.totalIssues, 0) : }
- {isNotUndefined(network?.openBounties) ? formatNumberToNScale(network?.openBounties, 0) : } + {isNotUndefined(network?.totalOpenIssues) ? formatNumberToNScale(network?.totalOpenIssues, 0) : }
- {isNotUndefined(network?.tokensLocked) ? formatNumberToNScale(+network?.tokensLocked) : } + {isNotUndefined(network?.tokensLocked) ? ( + formatNumberToNScale(BigNumber(network?.tokensLocked || 0).toFixed()) + ) : ( + + )} { if (count > 0) { @@ -83,7 +83,7 @@ export default function NetworksList() { useEffect(() => { if (!networks.length) return; - if (!state.Service?.active || networks?.every(network => network?.openBounties !== undefined)) return; + if (!state.Service?.active) return; const web3Host = state.Settings?.urls?.web3Provider; const dao = new DAO({web3Host, skipWindowAssignment: true}); @@ -93,59 +93,16 @@ export default function NetworksList() { const networkAddress = network?.networkAddress; await dao.loadNetwork(networkAddress); - const [settlerTokenData, totalSettlerLocked, openBounties, totalBounties] = await Promise.all([ + const [settlerTokenData] = await Promise.all([ dao.getSettlerTokenData().catch(() => undefined), - dao.getTotalNetworkToken().catch(() => 0), - dao.getOpenBounties().catch(() => 0), - dao.getTotalBounties().catch(() => 0) ]); - const mainCurrency = state.Settings?.currency?.defaultFiat || "eur"; - - const coinInfo = await getCoinInfoByContract(settlerTokenData?.symbol).catch(() => ({ prices: {} })); - - const totalSettlerConverted = (coinInfo.prices[mainCurrency] || 0) * +totalSettlerLocked; - return { ...network, - openBounties, - totalBounties, - networkToken: settlerTokenData, - tokensLocked: totalSettlerLocked.toFixed(), - totalSettlerConverted: totalSettlerConverted.toFixed() + networkToken: settlerTokenData } }))) .then(setNetworks) .catch(error => console.log("Failed to load network data", error, state.Service?.network?.active)); - - // Promise.all(networks.map(async (network: Network) => { - // const networkAddress = network?.networkAddress; - // - // - // await dao.loadNetwork(networkAddress); - // - // const [settlerTokenData, totalSettlerLocked, openBounties, totalBounties] = await Promise.all([ - // dao.getSettlerTokenData().catch(() => undefined), - // dao.getTotalNetworkToken().catch(() => 0), - // dao.getOpenBounties().catch(() => 0), - // dao.getTotalBounties().catch(() => 0) - // ]); - // - // const mainCurrency = state.Settings?.currency?.defaultFiat || "eur"; - // - // const coinInfo = await getCoinInfoByContract(settlerTokenData?.address).catch(() => ({ prices: {} })); - // - // const totalSettlerConverted = (coinInfo.prices[mainCurrency] || 0) * +totalSettlerLocked; - // - // return { ...network, - // openBounties, - // totalBounties, - // networkToken: settlerTokenData, - // tokensLocked: totalSettlerLocked.toFixed(), - // totalSettlerConverted: totalSettlerConverted.toFixed() - // } - // })) - // .then(setNetworks) - // .catch(error => console.log("Failed to load network data", error, state.Service?.network?.active)); }, [networks, state.Service?.active]); return ( diff --git a/db/models/network.model.js b/db/models/network.model.js index a45feab97e..3209c0ea7d 100644 --- a/db/models/network.model.js +++ b/db/models/network.model.js @@ -48,6 +48,11 @@ class Network extends Model { foreignKey: "network_id", sourceKey: "id" }); + this.hasMany(models.issue, { + foreignKey: "network_id", + sourceKey: "id", + as: "openIssues" + }); this.hasMany(models.repositories, { foreignKey: "network_id", sourceKey: "id" diff --git a/helpers/formatNumber.ts b/helpers/formatNumber.ts index cdd24f2153..e5d1d86b25 100644 --- a/helpers/formatNumber.ts +++ b/helpers/formatNumber.ts @@ -7,8 +7,7 @@ export const formatNumberToString = (number: number | string, decimals = 4) => { }; export const formatNumberToNScale = (number: number | string, fixed = 2, spacer = ` `) => { - if (!number) - return '0'; + if((typeof number === 'string' && number === "0") || !number) return '0' const bigNumber = new BigNumber(number); diff --git a/interfaces/api.ts b/interfaces/api.ts index 8286bbc8a1..70ac8d0b0d 100644 --- a/interfaces/api.ts +++ b/interfaces/api.ts @@ -30,6 +30,7 @@ export interface SearchNetworkParams { isClosed?: boolean; isRegistered?: boolean; isDefault?: boolean; + isNeedCountsAndTokensLocked?: boolean; } export interface SearchActiveNetworkParams { diff --git a/interfaces/network.ts b/interfaces/network.ts index 0e60be4a0f..f98a7ad67c 100644 --- a/interfaces/network.ts +++ b/interfaces/network.ts @@ -42,7 +42,8 @@ export interface Network { isDefault?: boolean; curators?: Curator[]; totalValueLock?: BigNumber; - countIssues?: number; + totalIssues?: string; + totalOpenIssues?: string; } export interface ThemeColors { diff --git a/pages/api/search/networks/active.ts b/pages/api/search/networks/active.ts index 273ee1ce69..77bf1ebb66 100644 --- a/pages/api/search/networks/active.ts +++ b/pages/api/search/networks/active.ts @@ -48,7 +48,7 @@ async function get(req: NextApiRequest, res: NextApiResponse) { logoIcon: network?.logoIcon, totalValueLock: network?.curators?.reduce((ac, cv) => BigNumber(ac).plus(cv?.tokensLocked || 0), BigNumber(0)), - countIssues: network?.issues?.length || 0 + totalIssues: network?.issues?.length || 0 }; }) diff --git a/pages/api/search/networks/index.ts b/pages/api/search/networks/index.ts index b63b87c634..3081381913 100644 --- a/pages/api/search/networks/index.ts +++ b/pages/api/search/networks/index.ts @@ -1,15 +1,36 @@ import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; -import {Op, WhereOptions} from "sequelize"; +import { Op, Sequelize, WhereOptions } from "sequelize"; +import { Fn, Literal } from "sequelize/types/utils"; import models from "db/models"; -import paginate, {calculateTotalPages} from "helpers/paginate"; +import {paginateArray} from "helpers/paginate"; + +interface includeProps { + association: string; + required?: boolean; + attributes?: string[]; + where?: { + state?: { + [Op.ne]?: string; + } | string; + } +} async function get(req: NextApiRequest, res: NextApiResponse) { const whereCondition: WhereOptions = {}; - const {name, creatorAddress, networkAddress, isClosed, isRegistered, isDefault, page} = req.query || {}; + const { + name, + creatorAddress, + networkAddress, + isClosed, + isRegistered, + isDefault, + isNeedCountsAndTokensLocked, + page, + } = req.query || {}; if (name) whereCondition.name = name; @@ -28,26 +49,56 @@ async function get(req: NextApiRequest, res: NextApiResponse) { if (isDefault) whereCondition.isDefault = isDefault; - const include = [ - { association: "tokens" } + const include: includeProps[] = [ + { association: "tokens" } ]; - const networks = await models.network.findAndCountAll(paginate({ - attributes: { - exclude: ["id", "creatorAddress"] - }, - where: whereCondition, - include, - nest: true - }, - req.query, - [[req.query.sortBy || "createdAt", req.query.order || "DESC"]])); + let group: string[] = [] + + const attributes: { include?: (string | [Fn,string] | [Literal,string])[]; exclude: string[] } = { + exclude: ["creatorAddress", "id"] + } + + if (isNeedCountsAndTokensLocked) { + include.push({ association: "curators", required: false, attributes: [] }) + include.push({ association: "issues", required: false, attributes: [], + where: { + state: {[Op.ne]: "pending" } + } + }) + include.push({ association: 'openIssues', required: false, attributes: [], where: {state: 'open'}},) + attributes.include = [ + "network.id", + "network.name", + [ + Sequelize.literal('sum(cast("curators"."tokensLocked" as INT)) / COUNT(distinct("issues".id)) / case when count(distinct "openIssues".id) = 0 then 1 else count(distinct "openIssues".id) end'), // eslint-disable-line + "tokensLocked", + ], + [Sequelize.literal('COUNT(DISTINCT("issues".id))'), 'totalIssues'], + [Sequelize.literal('COUNT(DISTINCT("openIssues".id))'), 'totalOpenIssues'] + ] + group = ['network.id', "network.name", "tokens.id", "tokens->network_tokens.id"] + } + + const networks = await models.network.findAll({ + include, + attributes, + group, + order: [[String(req.query.sortBy) ||["createdAt"], String(req.query.order) || "DESC"]], + where: whereCondition, + nest: true, + }) + + + const paginatedData = paginateArray(networks, 10, +page || 1) return res.status(200).json({ - ...networks, - currentPage: +page || 1, - pages: calculateTotalPages(networks.count) + count: networks.length, + rows: paginatedData.data, + pages: paginatedData.pages, + currentPage: +paginatedData.page }); + } async function SearchNetworks(req: NextApiRequest, diff --git a/x-hooks/use-api.tsx b/x-hooks/use-api.tsx index 86db3b1fcd..61fddbce6c 100644 --- a/x-hooks/use-api.tsx +++ b/x-hooks/use-api.tsx @@ -530,7 +530,8 @@ export default function useApi() { search = "", isClosed = undefined, isRegistered = undefined, - isDefault = undefined + isDefault = undefined, + isNeedCountsAndTokensLocked = undefined }: SearchNetworkParams) { const params = new URLSearchParams({ page, @@ -542,7 +543,11 @@ export default function useApi() { search, ... (isClosed !== undefined && { isClosed: isClosed.toString() } || {}), ... (isRegistered !== undefined && { isRegistered: isRegistered.toString() } || {}), - ... (isDefault !== undefined && { isDefault: isDefault.toString() } || {}) + ... (isDefault !== undefined && { isDefault: isDefault.toString() } || {}), + ...((isNeedCountsAndTokensLocked !== undefined && { + isNeedCountsAndTokensLocked: isNeedCountsAndTokensLocked.toString(), + }) || + {}), }).toString(); return api From 9a833cb4309f99c1f052042c73d1bac64936853c Mon Sep 17 00:00:00 2001 From: MoshMage Date: Tue, 14 Feb 2023 14:49:28 +0000 Subject: [PATCH 06/13] reduce withJWT eagerness --- middleware/log-access.ts | 10 +++++----- pages/api/graphql/index.ts | 7 +++++-- pages/api/seo/[...ids].ts | 4 ++-- pages/api/settings/index.ts | 5 ++--- pages/api/user/connect/index.ts | 9 ++++----- pages/api/user/reset/index.ts | 4 ++-- scripts/logging.js | 13 ++----------- services/logging.ts | 20 +++++++++++--------- x-hooks/use-analytic-events.ts | 6 ++++-- 9 files changed, 37 insertions(+), 41 deletions(-) diff --git a/middleware/log-access.ts b/middleware/log-access.ts index 006f82b4cb..bbbd0e900e 100644 --- a/middleware/log-access.ts +++ b/middleware/log-access.ts @@ -11,11 +11,11 @@ export const LogAccess = (handler: NextApiHandler) => { const pathname = url.split('/api')[1].replace(/\?.+/g, ''); - const rest = (query || body) ? ({ ... query ? {query} : {}, ... body ? {body} : {}}) : ''; + const payload = (query || body) ? ({ ... query ? {query} : {}, ... body ? {body} : {}}) : ''; - log(`${method} access`, pathname); - if (rest) - debug(`${method} access-payload`, pathname, rest); + log(`access`, {pathname, method}); + if (payload) + debug(`access-payload`, {pathname, payload, method}); try { await handler(req, res); @@ -25,7 +25,7 @@ export const LogAccess = (handler: NextApiHandler) => { debug(`${method} access-end`, pathname) } catch (e) { - Logger.error(e, `${method}`, pathname, e?.toString(), rest); + Logger.error(e, `access-error`, {method, pathname, payload}); } Logger.changeActionName(``); // clean action just in case; } diff --git a/pages/api/graphql/index.ts b/pages/api/graphql/index.ts index c082afda5e..fe6816ccb2 100644 --- a/pages/api/graphql/index.ts +++ b/pages/api/graphql/index.ts @@ -1,11 +1,12 @@ // import { error as LogError } from "services/logging"; -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; import {getToken} from "next-auth/jwt"; import getConfig from "next/config"; import {Octokit} from "octokit"; import {Logger} from "services/logging"; +import {LogAccess} from "../../../middleware/log-access"; +import WithCors from "../../../middleware/withCors"; const {serverRuntimeConfig: {authSecret, github: {token: botToken}}} = getConfig(); @@ -37,7 +38,9 @@ async function handler(req: NextApiRequest, res: NextApiResponse) { default: return res.status(405).json({ statusCode: 405, message: "Method Not Allowed" }); } + + res.end(); } Logger.changeActionName(`GraphQL`); -export default RouteMiddleware(handler); \ No newline at end of file +export default LogAccess(WithCors(handler)); \ No newline at end of file diff --git a/pages/api/seo/[...ids].ts b/pages/api/seo/[...ids].ts index dd8fc7afc6..57f3044909 100644 --- a/pages/api/seo/[...ids].ts +++ b/pages/api/seo/[...ids].ts @@ -1,11 +1,11 @@ import axios from "axios"; -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; import {Op} from "sequelize"; import models from "db/models"; import {Settings} from "helpers/settings"; +import {LogAccess} from "../../../middleware/log-access"; async function get(req: NextApiRequest, res: NextApiResponse) { const { @@ -59,4 +59,4 @@ async function Seo(req: NextApiRequest, res: NextApiResponse) { res.end(); } -export default RouteMiddleware(Seo) \ No newline at end of file +export default LogAccess(Seo) \ No newline at end of file diff --git a/pages/api/settings/index.ts b/pages/api/settings/index.ts index e13725e1c8..669f2f7634 100644 --- a/pages/api/settings/index.ts +++ b/pages/api/settings/index.ts @@ -3,9 +3,8 @@ import {NextApiRequest, NextApiResponse} from "next"; import models from "db/models"; import {Settings} from "helpers/settings"; - -import {RouteMiddleware} from "../../../middleware"; import {Logger} from "../../../services/logging"; +import {LogAccess} from "../../../middleware/log-access"; async function get(_req: NextApiRequest, res: NextApiResponse) { const settings = await models.settings.findAll({ @@ -20,7 +19,7 @@ async function get(_req: NextApiRequest, res: NextApiResponse) { Logger.changeActionName(`Settings`); -export default RouteMiddleware(async function handler(req: NextApiRequest, res: NextApiResponse) { +export default LogAccess(async function handler(req: NextApiRequest, res: NextApiResponse) { switch (req.method) { case "GET": await get(req, res); diff --git a/pages/api/user/connect/index.ts b/pages/api/user/connect/index.ts index aa0795e56c..a7b919c893 100644 --- a/pages/api/user/connect/index.ts +++ b/pages/api/user/connect/index.ts @@ -5,8 +5,7 @@ import {Op} from "sequelize"; import models from "db/models"; import {error as LogError} from "services/logging"; - -import {RouteMiddleware} from "../../../../middleware"; +import {LogAccess} from "../../../../middleware/log-access"; enum Actions { REGISTER = "register", @@ -53,12 +52,12 @@ async function patch(req: NextApiRequest, res: NextApiResponse) { return res.status(200).json("Success"); } catch (error) { - LogError(`Failed to ${action || "no action"} user`, { req, error }); - return res.status(500).json(error); + LogError(`Failed to ${action || "no action"} user`, { req, error: error?.toString() }); + return res.status(500).json(error?.toString()); } } -export default RouteMiddleware(async function ConnectUser(req: NextApiRequest, res: NextApiResponse) { +export default LogAccess(async function ConnectUser(req: NextApiRequest, res: NextApiResponse) { switch (req.method.toLowerCase()) { case "patch": await patch(req, res); diff --git a/pages/api/user/reset/index.ts b/pages/api/user/reset/index.ts index 35a512ed5b..353ebaf26b 100644 --- a/pages/api/user/reset/index.ts +++ b/pages/api/user/reset/index.ts @@ -7,7 +7,7 @@ import models from "db/models"; import {error as LogError} from "services/logging"; import {UNAUTHORIZED} from "../../../../helpers/error-messages"; -import {RouteMiddleware} from "../../../../middleware"; +import {LogAccess} from "../../../../middleware/log-access"; async function post(req: NextApiRequest, res: NextApiResponse) { const {address, githubLogin} = req.body; @@ -61,7 +61,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) { } } -export default RouteMiddleware(async function ResetUser(req: NextApiRequest, res: NextApiResponse) { +export default LogAccess(async function ResetUser(req: NextApiRequest, res: NextApiResponse) { switch (req.method.toLowerCase()) { case "post": await post(req, res); diff --git a/scripts/logging.js b/scripts/logging.js index 3f6f56ec33..fea1de496d 100644 --- a/scripts/logging.js +++ b/scripts/logging.js @@ -1,4 +1,5 @@ const {Client} = require("@elastic/elasticsearch"); +const {format} = require("date-fns"); require('dotenv').config(); const Levels = {none: '', log: 'log', info: 'info', error: 'error', DEBUG: 'debug'}; @@ -12,10 +13,6 @@ let DebugLevel; DebugLevel[DebugLevel["log"] = 4] = "log"; })(DebugLevel || (DebugLevel = {})) -const node = process.env.NEXT_ELASTIC_SEARCH_URL; -const username = process.env.NEXT_ELASTIC_SEARCH_USERNAME; -const password = process.env.NEXT_ELASTIC_SEARCH_PASSWORD; - const LOG_LEVEL = process.env.LOG_LEVEL ? parseInt(process.env.LOG_LEVEL, 10) : DebugLevel.log; const output = (level, message, ...rest) => { // eslint-disable-line @@ -24,17 +21,11 @@ const output = (level, message, ...rest) => { // eslint-disable-line if (rest.some(v => v !== undefined)) _rest = rest; - const string = `(${level.toUpperCase()}) (${new Date().toISOString()}) ${message}\n`; + const string = `(${level.toUpperCase()}) (${format(new Date(), `dd/MM HH:mm:ss`)}) ${message}`; if (LOG_LEVEL && LOG_LEVEL >= +DebugLevel[level]) console[level](string, _rest ? _rest : ""); - if (node && username && password) { - const client = new Client({node, auth: {username, password} }) - - client?.index({ index: "web-network", document: {level, timestamp: new Date(), message, rest: _rest}}) - .catch(e => console.log(e)) - } } /* eslint-disable */ const info = (message, rest) => output(Levels.info, message, rest); diff --git a/services/logging.ts b/services/logging.ts index fcbebb5448..4fece5f8ce 100644 --- a/services/logging.ts +++ b/services/logging.ts @@ -41,7 +41,9 @@ export const output = (_level: LogLevel, message, ...rest) => { // eslint-disabl const client = new Client({node, auth: {username, password} }) - client?.index({ index: "web-network-app", document: {level, timestamp: new Date(), message, rest}}) + const info = Array.isArray(rest) || rest !== null && typeof rest === "object" ? rest : {info: {rest: rest || ''}}; + + client?.index({ index: "web-network-ui", document: {level, timestamp: new Date(), message, rest}}) .catch(e => console.log(e)) } } @@ -65,13 +67,13 @@ export class Logger { ] } - static info(..._args) { info(...this._args(..._args)) } - static log(..._args) { log(...this._args(..._args)) } - static warn(..._args) { warn(...this._args(..._args)) } - static debug(..._args) { debug(...this._args(..._args)) } - static trace(..._args) { trace(...this._args(..._args)) } - static error(e: Error, ..._args) { - error(...this._args(...[e?.toString(), ..._args])) - trace(...this._args(...[`Code: ${(e as any).code || `NO_OPCODE`}\n`, e.stack || `NO_STACK_TRACE`, ..._args])); + static info(message,..._args) { info(...this._args(message,..._args)) } + static log(message,..._args) { log(...this._args(message,..._args)) } + static warn(message,..._args) { warn(...this._args(message,..._args)) } + static debug(message,..._args) { debug(...this._args(message,..._args)) } + static trace(message,..._args) { trace(...this._args(message,..._args)) } + static error(e: Error, message, ..._args) { + error(message, ...this._args(...[e?.toString(), ..._args])) + trace(`Code: ${(e as any).code || `NO_OPCODE`}\n`, e.stack || `NO_STACK_TRACE`); } } \ No newline at end of file diff --git a/x-hooks/use-analytic-events.ts b/x-hooks/use-analytic-events.ts index 1213e5f742..3ec2dd4380 100644 --- a/x-hooks/use-analytic-events.ts +++ b/x-hooks/use-analytic-events.ts @@ -38,10 +38,12 @@ export default function useAnalyticEvents() { } if (state?.currentUser) { - const {walletAddress, connected, handle, login} = state.currentUser; details = { ...details, - walletAddress: walletAddress.toString(), connected: connected.toString(), handle, login + walletAddress: state.currentUser?.walletAddress?.toString(), + connected: state.currentUser?.connected?.toString(), + handle: state.currentUser?.handle, + login: state.currentUser?.login }; } From fab6c7843919802b77a5f37797c12ff8644247b6 Mon Sep 17 00:00:00 2001 From: Vitor Hugo Date: Tue, 14 Feb 2023 15:02:19 -0300 Subject: [PATCH 07/13] removing withJWT from endpoints that doesn't require a token (#871) --- pages/api/files/index.ts | 5 +++-- pages/api/issue/index.ts | 8 ++++---- pages/api/nft/index.ts | 5 +++-- pages/api/search/users/[...action].ts | 5 +++-- 4 files changed, 13 insertions(+), 10 deletions(-) diff --git a/pages/api/files/index.ts b/pages/api/files/index.ts index 92c1dbcca7..5e1761f525 100644 --- a/pages/api/files/index.ts +++ b/pages/api/files/index.ts @@ -1,6 +1,7 @@ import formidable from "formidable"; import fs from "fs"; -import {RouteMiddleware} from "middleware"; +import { LogAccess } from "middleware/log-access"; +import WithCors from "middleware/withCors"; import {NextApiRequest, NextApiResponse} from "next"; import IpfsStorage from "services/ipfs-service"; @@ -52,4 +53,4 @@ async function FilesMethods (req: NextApiRequest, res: NextApiResponse) { } Logger.changeActionName(`Files`); -export default RouteMiddleware(FilesMethods) \ No newline at end of file +export default LogAccess(WithCors(FilesMethods)); \ No newline at end of file diff --git a/pages/api/issue/index.ts b/pages/api/issue/index.ts index cb7b11286d..35ed9adabf 100644 --- a/pages/api/issue/index.ts +++ b/pages/api/issue/index.ts @@ -1,3 +1,5 @@ +import { LogAccess } from "middleware/log-access"; +import WithCors from "middleware/withCors"; import {NextApiRequest, NextApiResponse} from "next"; import getConfig from "next/config"; import {Octokit} from "octokit"; @@ -10,8 +12,6 @@ import * as RepositoryQueries from "graphql/repository"; import {GraphQlResponse} from "types/octokit"; -import {RouteMiddleware} from "../../../middleware"; - const {serverRuntimeConfig} = getConfig(); async function post(req: NextApiRequest, res: NextApiResponse) { @@ -95,7 +95,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) { return res.status(200).json(`${repository.id}/${githubId}`); } -export default RouteMiddleware(async function Issue(req: NextApiRequest, res: NextApiResponse) { +export default LogAccess(WithCors(async function Issue(req: NextApiRequest, res: NextApiResponse) { switch (req.method.toLowerCase()) { case "post": await post(req, res); @@ -106,4 +106,4 @@ export default RouteMiddleware(async function Issue(req: NextApiRequest, res: Ne } res.end(); -}) +})) diff --git a/pages/api/nft/index.ts b/pages/api/nft/index.ts index 41ab8ebb8b..6e9f47fa83 100644 --- a/pages/api/nft/index.ts +++ b/pages/api/nft/index.ts @@ -1,6 +1,7 @@ import {Bounty, ProposalDetail,} from "@taikai/dappkit"; import BigNumber from "bignumber.js"; -import {RouteMiddleware} from "middleware"; +import { LogAccess } from "middleware/log-access"; +import WithCors from "middleware/withCors"; import {NextApiRequest, NextApiResponse} from "next"; import {Op} from "sequelize"; @@ -178,4 +179,4 @@ async function NftMethods(req: NextApiRequest, res: NextApiResponse) { res.end(); } -export default RouteMiddleware(NftMethods); \ No newline at end of file +export default LogAccess(WithCors(NftMethods)); \ No newline at end of file diff --git a/pages/api/search/users/[...action].ts b/pages/api/search/users/[...action].ts index accda188e8..3735160845 100644 --- a/pages/api/search/users/[...action].ts +++ b/pages/api/search/users/[...action].ts @@ -1,4 +1,5 @@ -import {RouteMiddleware} from "middleware"; +import { LogAccess } from "middleware/log-access"; +import WithCors from "middleware/withCors"; import {NextApiRequest, NextApiResponse} from "next"; import {Op} from "sequelize"; @@ -51,4 +52,4 @@ async function SearchUsers(req: NextApiRequest, res.end(); } -export default RouteMiddleware(SearchUsers) \ No newline at end of file +export default LogAccess(WithCors(SearchUsers)); \ No newline at end of file From 6bcec8bcca20d014948a1732eb99c90e43ecf33e Mon Sep 17 00:00:00 2001 From: MoshMage Date: Wed, 15 Feb 2023 09:52:44 +0000 Subject: [PATCH 08/13] try and make peace with elastic-search --- services/logging.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/services/logging.ts b/services/logging.ts index 4fece5f8ce..e2ab886a13 100644 --- a/services/logging.ts +++ b/services/logging.ts @@ -41,9 +41,14 @@ export const output = (_level: LogLevel, message, ...rest) => { // eslint-disabl const client = new Client({node, auth: {username, password} }) - const info = Array.isArray(rest) || rest !== null && typeof rest === "object" ? rest : {info: {rest: rest || ''}}; - - client?.index({ index: "web-network-ui", document: {level, timestamp: new Date(), message, rest}}) + const info = {restArray: [], restObject: {}, restSimple: ''}; + if (Array.isArray(rest)) + info.restArray = rest; + else if (rest !== null && typeof rest === "object") + info.restObject = rest; + else info.restSimple = rest; + + client?.index({ index: "web-network-ui", document: {level, timestamp: new Date(), message, info}}) .catch(e => console.log(e)) } } From d81a976b65dce1c83938242cfe7f3783cb328a76 Mon Sep 17 00:00:00 2001 From: MoshMage Date: Wed, 15 Feb 2023 10:09:59 +0000 Subject: [PATCH 09/13] remove logging.js because its not needed. --- db/config/index.js | 3 +-- scripts/logging.js | 35 ----------------------------------- 2 files changed, 1 insertion(+), 37 deletions(-) delete mode 100644 scripts/logging.js diff --git a/db/config/index.js b/db/config/index.js index e764b58d68..9eb670d86e 100644 --- a/db/config/index.js +++ b/db/config/index.js @@ -1,4 +1,3 @@ -const {info} = require("../../scripts/logging.js"); require("dotenv").config(); module.exports = { @@ -10,7 +9,7 @@ module.exports = { host: process.env.NEXT_DB_HOST || "localhost", port: +process.env.NEXT_DB_PORT || 54320, ... (process.env.NEXT_DB_LOG ? { - logging: (sql) => { info(sql) }, + logging: (sql) => { console.log(sql) }, } : { logging: false }), diff --git a/scripts/logging.js b/scripts/logging.js deleted file mode 100644 index fea1de496d..0000000000 --- a/scripts/logging.js +++ /dev/null @@ -1,35 +0,0 @@ -const {Client} = require("@elastic/elasticsearch"); -const {format} = require("date-fns"); -require('dotenv').config(); - -const Levels = {none: '', log: 'log', info: 'info', error: 'error', DEBUG: 'debug'}; - -let DebugLevel; -(function (DebugLevel) { - DebugLevel[DebugLevel["none"] = 0] = "none"; - DebugLevel[DebugLevel["error"] = 1] = "error"; - DebugLevel[DebugLevel["warn"] = 2] = "warn"; - DebugLevel[DebugLevel["info"] = 3] = "info"; - DebugLevel[DebugLevel["log"] = 4] = "log"; -})(DebugLevel || (DebugLevel = {})) - -const LOG_LEVEL = process.env.LOG_LEVEL ? parseInt(process.env.LOG_LEVEL, 10) : DebugLevel.log; - -const output = (level, message, ...rest) => { // eslint-disable-line - let _rest; - - if (rest.some(v => v !== undefined)) - _rest = rest; - - const string = `(${level.toUpperCase()}) (${format(new Date(), `dd/MM HH:mm:ss`)}) ${message}`; - - if (LOG_LEVEL && LOG_LEVEL >= +DebugLevel[level]) - console[level](string, _rest ? _rest : ""); - -} -/* eslint-disable */ -const info = (message, rest) => output(Levels.info, message, rest); -const error = (message, rest) => output(Levels.error, message, rest); -const log = (message, rest) => output(Levels.log, message, rest); -/* eslint-disable */ -module.exports = {info, error, log}; From 51f443bef00a1751ca3d994b61b62bcfd12e8e76 Mon Sep 17 00:00:00 2001 From: MoshMage Date: Wed, 15 Feb 2023 10:22:57 +0000 Subject: [PATCH 10/13] revert eagerness on withJwt to its default state --- pages/api/header/networks/index.ts | 5 +++-- pages/api/issue/[...ids].ts | 8 ++++---- pages/api/issue/working/index.ts | 5 +++-- pages/api/merge-proposal/poll/[...info].ts | 5 +++-- pages/api/payments/index.ts | 5 +++-- pages/api/pull-request/index.ts | 5 +++-- pages/api/pull-request/merge/index.ts | 5 +++-- pages/api/pull-request/review/index.ts | 5 +++-- pages/api/repos/index.ts | 5 +++-- pages/api/search/curators/index.ts | 5 +++-- pages/api/search/issues/index.ts | 5 +++-- pages/api/search/issues/recent.ts | 5 +++-- pages/api/search/issues/total.ts | 6 +++--- pages/api/search/leaderboard/index.ts | 5 +++-- pages/api/search/leaderboard/points/index.ts | 5 +++-- pages/api/search/networks/active.ts | 5 +++-- pages/api/search/networks/index.ts | 9 +++++---- pages/api/search/networks/total.ts | 5 +++-- pages/api/search/repositories/index.ts | 5 +++-- pages/api/search/users/total.ts | 5 +++-- pages/api/tokens/index.ts | 5 +++-- 21 files changed, 66 insertions(+), 47 deletions(-) diff --git a/pages/api/header/networks/index.ts b/pages/api/header/networks/index.ts index e3dcd2b352..9077daa5ea 100644 --- a/pages/api/header/networks/index.ts +++ b/pages/api/header/networks/index.ts @@ -1,7 +1,8 @@ -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; import models from "db/models"; +import {LogAccess} from "../../../../middleware/log-access"; +import WithCors from "../../../../middleware/withCors"; async function get(req: NextApiRequest, res: NextApiResponse) { @@ -27,4 +28,4 @@ async function SearchNetworks(req: NextApiRequest, res.end(); } -export default RouteMiddleware(SearchNetworks) \ No newline at end of file +export default LogAccess(WithCors(SearchNetworks)) \ No newline at end of file diff --git a/pages/api/issue/[...ids].ts b/pages/api/issue/[...ids].ts index 37fad9f4b0..9fea44eee0 100644 --- a/pages/api/issue/[...ids].ts +++ b/pages/api/issue/[...ids].ts @@ -2,8 +2,8 @@ import {NextApiRequest, NextApiResponse} from "next"; import {Op} from "sequelize"; import models from "db/models"; - -import {RouteMiddleware} from "../../../middleware"; +import {LogAccess} from "../../../middleware/log-access"; +import WithCors from "../../../middleware/withCors"; async function get(req: NextApiRequest, res: NextApiResponse) { const { @@ -44,7 +44,7 @@ async function get(req: NextApiRequest, res: NextApiResponse) { return res.status(200).json(issue); } -export default RouteMiddleware(async function GetIssues(req: NextApiRequest, +export default LogAccess(WithCors(async function GetIssues(req: NextApiRequest, res: NextApiResponse) { switch (req.method.toLowerCase()) { case "get": @@ -56,4 +56,4 @@ export default RouteMiddleware(async function GetIssues(req: NextApiRequest, } res.end(); -}) +})) diff --git a/pages/api/issue/working/index.ts b/pages/api/issue/working/index.ts index c406ab70c2..1df0618487 100644 --- a/pages/api/issue/working/index.ts +++ b/pages/api/issue/working/index.ts @@ -1,4 +1,3 @@ -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; import getConfig from "next/config"; import {Octokit} from "octokit"; @@ -14,6 +13,8 @@ import {getPropertyRecursively} from "helpers/object"; import {GraphQlQueryResponseData, GraphQlResponse} from "types/octokit"; import {Logger} from "../../../../services/logging"; +import {LogAccess} from "../../../../middleware/log-access"; +import WithCors from "../../../../middleware/withCors"; const { serverRuntimeConfig } = getConfig(); @@ -96,4 +97,4 @@ async function Working(req: NextApiRequest, } Logger.changeActionName(`Issue/Working`); -export default RouteMiddleware(Working) \ No newline at end of file +export default LogAccess(WithCors(Working)) \ No newline at end of file diff --git a/pages/api/merge-proposal/poll/[...info].ts b/pages/api/merge-proposal/poll/[...info].ts index b0595ccca7..0018906e52 100644 --- a/pages/api/merge-proposal/poll/[...info].ts +++ b/pages/api/merge-proposal/poll/[...info].ts @@ -1,7 +1,8 @@ -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; import {Bus} from "helpers/bus"; +import {LogAccess} from "../../../../middleware/log-access"; +import WithCors from "../../../../middleware/withCors"; async function get(req: NextApiRequest, res: NextApiResponse) { const { @@ -27,4 +28,4 @@ async function PollMergeProposal(req: NextApiRequest, } } -export default RouteMiddleware(PollMergeProposal) \ No newline at end of file +export default LogAccess(WithCors(PollMergeProposal)); \ No newline at end of file diff --git a/pages/api/payments/index.ts b/pages/api/payments/index.ts index 27da1702fd..8f188d0b84 100644 --- a/pages/api/payments/index.ts +++ b/pages/api/payments/index.ts @@ -1,9 +1,10 @@ import {endOfDay, isAfter, parseISO, startOfDay} from "date-fns"; -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; import {Op} from "sequelize"; import models from "db/models"; +import {LogAccess} from "../../../middleware/log-access"; +import WithCors from "../../../middleware/withCors"; async function get(req: NextApiRequest, res: NextApiResponse) { const {wallet, networkName, startDate, endDate} = req.query; @@ -74,4 +75,4 @@ async function Payments(req: NextApiRequest, res: NextApiResponse) { res.end(); } -export default RouteMiddleware(Payments) \ No newline at end of file +export default LogAccess(WithCors(Payments)); \ No newline at end of file diff --git a/pages/api/pull-request/index.ts b/pages/api/pull-request/index.ts index 1c28b49994..e48c99a536 100644 --- a/pages/api/pull-request/index.ts +++ b/pages/api/pull-request/index.ts @@ -1,4 +1,3 @@ -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; import getConfig from "next/config"; import {Octokit} from "octokit"; @@ -15,6 +14,8 @@ import {Settings} from "helpers/settings"; import DAO from "services/dao-service"; import {GraphQlResponse} from "types/octokit"; +import {LogAccess} from "../../../middleware/log-access"; +import WithCors from "../../../middleware/withCors"; const { serverRuntimeConfig } = getConfig(); @@ -289,4 +290,4 @@ async function PullRequest(req: NextApiRequest, res: NextApiResponse) { res.end(); } -export default RouteMiddleware(PullRequest); +export default LogAccess(WithCors(PullRequest)); diff --git a/pages/api/pull-request/merge/index.ts b/pages/api/pull-request/merge/index.ts index 0a96e60a32..a4314e5631 100644 --- a/pages/api/pull-request/merge/index.ts +++ b/pages/api/pull-request/merge/index.ts @@ -1,4 +1,3 @@ -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; import getConfig from "next/config"; import {Octokit} from "octokit"; @@ -13,6 +12,8 @@ import {Settings} from "helpers/settings"; import DAO from "services/dao-service"; import {GraphQlResponse} from "types/octokit"; +import {LogAccess} from "../../../../middleware/log-access"; +import WithCors from "../../../../middleware/withCors"; const { serverRuntimeConfig } = getConfig(); @@ -130,4 +131,4 @@ async function PullRequest(req: NextApiRequest, res.end(); } -export default RouteMiddleware(PullRequest) \ No newline at end of file +export default LogAccess(WithCors(PullRequest)); \ No newline at end of file diff --git a/pages/api/pull-request/review/index.ts b/pages/api/pull-request/review/index.ts index 316dcefada..717e438f92 100644 --- a/pages/api/pull-request/review/index.ts +++ b/pages/api/pull-request/review/index.ts @@ -1,4 +1,3 @@ -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; import getConfig from "next/config"; import {Octokit} from "octokit"; @@ -9,6 +8,8 @@ import models from "db/models"; import * as PullRequestQueries from "graphql/pull-request"; import {GraphQlResponse} from "types/octokit"; +import {LogAccess} from "../../../../middleware/log-access"; +import WithCors from "../../../../middleware/withCors"; const { serverRuntimeConfig } = getConfig(); @@ -100,4 +101,4 @@ async function PullRequestReview(req: NextApiRequest, res.end(); } -export default RouteMiddleware(PullRequestReview) \ No newline at end of file +export default LogAccess(WithCors(PullRequestReview)); \ No newline at end of file diff --git a/pages/api/repos/index.ts b/pages/api/repos/index.ts index c4148a63a7..39254baa7b 100644 --- a/pages/api/repos/index.ts +++ b/pages/api/repos/index.ts @@ -1,8 +1,9 @@ -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; import {Op} from "sequelize"; import models from "db/models"; +import {LogAccess} from "../../../middleware/log-access"; +import WithCors from "../../../middleware/withCors"; async function getAllRepos(req, res) { const {networkName} = req.query; @@ -103,4 +104,4 @@ async function RepoRoute(req: NextApiRequest, res.end(); } -export default RouteMiddleware(RepoRoute) \ No newline at end of file +export default LogAccess(WithCors(RepoRoute)) \ No newline at end of file diff --git a/pages/api/search/curators/index.ts b/pages/api/search/curators/index.ts index 3467fafb99..d9a7160371 100644 --- a/pages/api/search/curators/index.ts +++ b/pages/api/search/curators/index.ts @@ -1,10 +1,11 @@ -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; import {Op, WhereOptions} from "sequelize"; import models from "db/models"; import paginate, {calculateTotalPages} from "helpers/paginate"; +import {LogAccess} from "../../../../middleware/log-access"; +import WithCors from "../../../../middleware/withCors"; async function get(req: NextApiRequest, res: NextApiResponse) { try { @@ -76,4 +77,4 @@ async function SearchCurators(req: NextApiRequest, res: NextApiResponse) { res.end(); } -export default RouteMiddleware(SearchCurators); +export default LogAccess(WithCors(SearchCurators)); diff --git a/pages/api/search/issues/index.ts b/pages/api/search/issues/index.ts index 245d7afc62..e6dfd1ae95 100644 --- a/pages/api/search/issues/index.ts +++ b/pages/api/search/issues/index.ts @@ -1,5 +1,4 @@ import {subHours, subMonths, subWeeks, subYears} from "date-fns"; -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; import {Op, Sequelize, WhereOptions} from "sequelize"; @@ -8,6 +7,8 @@ import models from "db/models"; import handleNetworkValues from "helpers/handleNetworksValuesApi"; import paginate, {calculateTotalPages, paginateArray} from "helpers/paginate"; import {searchPatternInText} from "helpers/string"; +import {LogAccess} from "../../../../middleware/log-access"; +import WithCors from "../../../../middleware/withCors"; const COLS_TO_CAST = ["amount", "fundingAmount"]; const castToDecimal = columnName => Sequelize.cast(Sequelize.col(columnName), 'DECIMAL'); @@ -227,4 +228,4 @@ async function SearchIssues(req: NextApiRequest, res.end(); } -export default RouteMiddleware(SearchIssues) \ No newline at end of file +export default LogAccess(WithCors(SearchIssues)) \ No newline at end of file diff --git a/pages/api/search/issues/recent.ts b/pages/api/search/issues/recent.ts index 09e6aa5cc0..1dbb2c9549 100644 --- a/pages/api/search/issues/recent.ts +++ b/pages/api/search/issues/recent.ts @@ -1,10 +1,11 @@ -import {RouteMiddleware} from 'middleware'; import {NextApiRequest, NextApiResponse} from "next"; import {Op, WhereOptions} from "sequelize"; import models from "db/models"; import handleNetworkValues from 'helpers/handleNetworksValuesApi'; +import {LogAccess} from "../../../../middleware/log-access"; +import WithCors from "../../../../middleware/withCors"; const getLastIssuesByStatus = async (state, whereCondition, sortBy, order, limit = 3) => (models.issue.findAll({ where: { @@ -84,4 +85,4 @@ async function getAll(req: NextApiRequest, res.end(); } -export default RouteMiddleware(getAll) \ No newline at end of file +export default LogAccess(WithCors(getAll)) \ No newline at end of file diff --git a/pages/api/search/issues/total.ts b/pages/api/search/issues/total.ts index 158a2aa154..550ae3590d 100644 --- a/pages/api/search/issues/total.ts +++ b/pages/api/search/issues/total.ts @@ -1,9 +1,9 @@ -import {RouteMiddleware} from 'middleware'; -import withJwt from "middleware/withJwt"; import {NextApiRequest, NextApiResponse} from "next"; import {Op, WhereOptions} from "sequelize"; import models from "db/models"; +import {LogAccess} from "../../../../middleware/log-access"; +import WithCors from "../../../../middleware/withCors"; async function getTotal(req: NextApiRequest, res: NextApiResponse) { const whereCondition: WhereOptions = {state: {[Op.not]: "pending"}}; @@ -72,4 +72,4 @@ async function getAll(req: NextApiRequest, res.end(); } -export default RouteMiddleware(withJwt(getAll)) \ No newline at end of file +export default LogAccess(WithCors(getAll)); \ No newline at end of file diff --git a/pages/api/search/leaderboard/index.ts b/pages/api/search/leaderboard/index.ts index b9fb6231d3..13e5587f66 100644 --- a/pages/api/search/leaderboard/index.ts +++ b/pages/api/search/leaderboard/index.ts @@ -1,5 +1,4 @@ import {subHours, subMonths, subWeeks, subYears} from "date-fns"; -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; import {Op, WhereOptions} from "sequelize"; @@ -7,6 +6,8 @@ import models from "db/models"; import paginate, {calculateTotalPages, paginateArray} from "helpers/paginate"; import {searchPatternInText} from "helpers/string"; +import {LogAccess} from "../../../../middleware/log-access"; +import WithCors from "../../../../middleware/withCors"; async function get(req: NextApiRequest, res: NextApiResponse) { try { @@ -110,4 +111,4 @@ async function SearchLeaderBoard(req: NextApiRequest, res: NextApiResponse) { res.end(); } -export default RouteMiddleware(SearchLeaderBoard); +export default LogAccess(WithCors(SearchLeaderBoard)); diff --git a/pages/api/search/leaderboard/points/index.ts b/pages/api/search/leaderboard/points/index.ts index 46653ddc54..d1243bd7ff 100644 --- a/pages/api/search/leaderboard/points/index.ts +++ b/pages/api/search/leaderboard/points/index.ts @@ -1,4 +1,3 @@ -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; import {Op, WhereOptions} from "sequelize"; @@ -6,6 +5,8 @@ import models from "db/models"; import {calculateLeaderboardScore} from "helpers/leaderboard-score"; import paginate, {calculateTotalPages} from "helpers/paginate"; +import {LogAccess} from "../../../../../middleware/log-access"; +import WithCors from "../../../../../middleware/withCors"; async function get(req: NextApiRequest, res: NextApiResponse) { try { @@ -64,4 +65,4 @@ async function SearchLeaderBoardPoints(req: NextApiRequest, res: NextApiResponse res.end(); } -export default RouteMiddleware(SearchLeaderBoardPoints); +export default LogAccess(WithCors(SearchLeaderBoardPoints)); diff --git a/pages/api/search/networks/active.ts b/pages/api/search/networks/active.ts index 77bf1ebb66..465a7ae445 100644 --- a/pages/api/search/networks/active.ts +++ b/pages/api/search/networks/active.ts @@ -1,11 +1,12 @@ import BigNumber from "bignumber.js"; -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; import {Op, WhereOptions} from "sequelize"; import models from "db/models"; import {paginateArray} from "helpers/paginate"; +import {LogAccess} from "../../../../middleware/log-access"; +import WithCors from "../../../../middleware/withCors"; async function get(req: NextApiRequest, res: NextApiResponse) { const whereCondition: WhereOptions = {}; @@ -83,4 +84,4 @@ async function SearchNetworks(req: NextApiRequest, res.end(); } -export default RouteMiddleware(SearchNetworks) \ No newline at end of file +export default LogAccess(WithCors(SearchNetworks)); \ No newline at end of file diff --git a/pages/api/search/networks/index.ts b/pages/api/search/networks/index.ts index 3081381913..75202cd65b 100644 --- a/pages/api/search/networks/index.ts +++ b/pages/api/search/networks/index.ts @@ -1,11 +1,12 @@ -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; -import { Op, Sequelize, WhereOptions } from "sequelize"; -import { Fn, Literal } from "sequelize/types/utils"; +import {Op, Sequelize, WhereOptions} from "sequelize"; +import {Fn, Literal} from "sequelize/types/utils"; import models from "db/models"; import {paginateArray} from "helpers/paginate"; +import {LogAccess} from "../../../../middleware/log-access"; +import WithCors from "../../../../middleware/withCors"; interface includeProps { association: string; @@ -114,4 +115,4 @@ async function SearchNetworks(req: NextApiRequest, res.end(); } -export default RouteMiddleware(SearchNetworks) \ No newline at end of file +export default LogAccess(WithCors(SearchNetworks)); \ No newline at end of file diff --git a/pages/api/search/networks/total.ts b/pages/api/search/networks/total.ts index 4e9f076ebd..8bc547b933 100644 --- a/pages/api/search/networks/total.ts +++ b/pages/api/search/networks/total.ts @@ -1,8 +1,9 @@ -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; import {Op, WhereOptions} from "sequelize"; import models from "db/models"; +import {LogAccess} from "../../../../middleware/log-access"; +import WithCors from "../../../../middleware/withCors"; async function get(req: NextApiRequest, res: NextApiResponse) { const whereCondition: WhereOptions = {}; @@ -39,4 +40,4 @@ async function GetAll(req: NextApiRequest, res.end(); } -export default RouteMiddleware(GetAll) \ No newline at end of file +export default LogAccess(WithCors(GetAll)); \ No newline at end of file diff --git a/pages/api/search/repositories/index.ts b/pages/api/search/repositories/index.ts index f0f74653bf..2d2474eb0f 100644 --- a/pages/api/search/repositories/index.ts +++ b/pages/api/search/repositories/index.ts @@ -1,10 +1,11 @@ -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; import {Op, WhereOptions} from "sequelize"; import models from "db/models"; import paginate, {calculateTotalPages} from "helpers/paginate"; +import {LogAccess} from "../../../../middleware/log-access"; +import WithCors from "../../../../middleware/withCors"; async function get(req: NextApiRequest, res: NextApiResponse) { const whereCondition: WhereOptions = {}; @@ -56,4 +57,4 @@ async function SearchRepositories(req: NextApiRequest, res.end(); } -export default RouteMiddleware(SearchRepositories) \ No newline at end of file +export default LogAccess(WithCors(SearchRepositories)); \ No newline at end of file diff --git a/pages/api/search/users/total.ts b/pages/api/search/users/total.ts index 359a7e533b..5e592c3d52 100644 --- a/pages/api/search/users/total.ts +++ b/pages/api/search/users/total.ts @@ -1,7 +1,8 @@ -import {RouteMiddleware} from 'middleware'; import {NextApiRequest, NextApiResponse} from "next"; import models from "db/models"; +import {LogAccess} from "../../../../middleware/log-access"; +import WithCors from "../../../../middleware/withCors"; async function getTotal(req: NextApiRequest, res: NextApiResponse) { const userCount = await models.user.count(); @@ -23,4 +24,4 @@ async function getAll(req: NextApiRequest, res.end(); } -export default RouteMiddleware(getAll) \ No newline at end of file +export default LogAccess(WithCors(getAll)); \ No newline at end of file diff --git a/pages/api/tokens/index.ts b/pages/api/tokens/index.ts index d4d0a477f7..dd6467f13e 100644 --- a/pages/api/tokens/index.ts +++ b/pages/api/tokens/index.ts @@ -1,10 +1,11 @@ -import {RouteMiddleware} from "middleware"; import {NextApiRequest, NextApiResponse} from "next"; import {Op, Sequelize} from "sequelize"; import Database from "db/models"; import {error as logError, Logger} from 'services/logging'; +import {LogAccess} from "../../../middleware/log-access"; +import WithCors from "../../../middleware/withCors"; const colToLower = (colName: string) => Sequelize.fn("LOWER", Sequelize.col(colName)); @@ -56,4 +57,4 @@ async function tokensEndPoint(req: NextApiRequest, res: NextApiResponse) { } Logger.changeActionName(`Tokens`); -export default RouteMiddleware(tokensEndPoint); +export default LogAccess(WithCors(tokensEndPoint)); From e3da8057fc4704f6e27297139a4db21c0d19e21e Mon Sep 17 00:00:00 2001 From: Vitor Hugo Date: Wed, 15 Feb 2023 16:01:23 -0300 Subject: [PATCH 11/13] fix invalid date --- helpers/formatDate.ts | 23 ++++++++++++++--------- x-hooks/use-bounty.tsx | 1 + 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/helpers/formatDate.ts b/helpers/formatDate.ts index 967ff7daa2..2381d18a5a 100644 --- a/helpers/formatDate.ts +++ b/helpers/formatDate.ts @@ -1,21 +1,26 @@ import { formatDistanceStrict } from "date-fns"; export const formatDate = (date: number | string | Date, joiner = "/") => { - const d = ["string", "number"].includes(typeof date) - ? new Date(date) - : (date as Date); - return [ - `0${d.getDate()}`.slice(-2), - `0${d.getMonth() + 1}`.slice(-2), - d.getFullYear() - ].join(joiner); + try { + const d = ["string", "number"].includes(typeof date) + ? new Date(date) + : (date as Date); + return [ + `0${d.getDate()}`.slice(-2), + `0${d.getMonth() + 1}`.slice(-2), + d.getFullYear() + ].join(joiner); + } catch (e) { + console.debug(e); + return `0`; + } }; export const getTimeDifferenceInWords = (date: Date, dateToCompare: Date) => { try { return formatDistanceStrict(date, dateToCompare); } catch (e) { - console.error(e); + console.debug(e); return `0`; } }; diff --git a/x-hooks/use-bounty.tsx b/x-hooks/use-bounty.tsx index 05f97cd62d..0cfe3beace 100644 --- a/x-hooks/use-bounty.tsx +++ b/x-hooks/use-bounty.tsx @@ -153,6 +153,7 @@ export function useBounty() { getExtendedProposalsForCurrentBounty(bounty) .then(proposals => dispatch(changeCurrentBountyDataProposals(proposals))) + .catch(error => console.debug("Failed to getExtendedProposalsForCurrentBounty", error)); bountyReadyPRsHasNoInvalidProposals(bounty, state.Service.active.network) .catch(() => -1) From a73cb870f31a0d57229a59f19839f7c2f600561e Mon Sep 17 00:00:00 2001 From: Vitor Hugo Date: Wed, 15 Feb 2023 19:25:20 -0300 Subject: [PATCH 12/13] fix translation --- pages/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pages/index.tsx b/pages/index.tsx index ccb77fc30d..00c02ad4ff 100644 --- a/pages/index.tsx +++ b/pages/index.tsx @@ -12,7 +12,7 @@ export default function Index() { export const getServerSideProps: GetServerSideProps = async ({ locale }) => { return { props: { - ...(await serverSideTranslations(locale, ["common", "bounty", "connect-wallet-button"])) + ...(await serverSideTranslations(locale, ["common", "custom-network", "bounty", "connect-wallet-button"])) } }; }; From 45bea40e462430902811eacb531e7f7bc992d747 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcus=20Vin=C3=ADcius?= Date: Thu, 16 Feb 2023 11:58:53 -0300 Subject: [PATCH 13/13] adding "/" to noNeedNetworkInstance (#873) --- components/main-nav.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/main-nav.tsx b/components/main-nav.tsx index a5087a4441..f14b307451 100644 --- a/components/main-nav.tsx +++ b/components/main-nav.tsx @@ -46,7 +46,7 @@ export default function MainNav() { const { searchNetworks } = useApi(); const { getURLWithNetwork } = useNetworkTheme(); - const noNeedNetworkInstance = ["/networks", "/new-network", "/explore", "/leaderboard"].includes(pathname); + const noNeedNetworkInstance = ["/","/networks", "/new-network", "/explore", "/leaderboard"].includes(pathname); const fullLogoUrl = state.Service?.network?.active?.fullLogo; useEffect(() => {