Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions web-marketplace/src/clients/regen/Regen.Routes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ import { Router } from '@remix-run/router';
import * as Sentry from '@sentry/react';
import { QueryClient } from '@tanstack/react-query';

import { Maybe } from 'generated/graphql';
import { ApolloClientFactory } from 'lib/clients/apolloClientFactory';
import { useWallet } from 'lib/wallet/wallet';

import { buyCreditsLoader } from 'pages/BuyCredits/BuyCredits.loader';
import { CertificatePage } from 'pages/Certificate/Certificate';
import MyBridge from 'pages/Dashboard/MyBridge';
import { MyBridgableEcocreditsTable } from 'pages/Dashboard/MyBridge/MyBridge.BridgableEcocreditsTable';
Expand Down Expand Up @@ -100,13 +102,13 @@ export const RegenRoutes = ({
reactQueryClient,
apolloClientFactory,
}: RouterProps) => {
const { wallet } = useWallet();
const { activeWalletAddr } = useWallet();
return (
<RouterProvider
router={getRegenRouter({
reactQueryClient,
apolloClientFactory,
address: wallet?.address,
address: activeWalletAddr,
})}
fallbackElement={<PageLoader />}
/>
Expand All @@ -116,7 +118,7 @@ export const RegenRoutes = ({
type RouterParams = {
reactQueryClient: QueryClient;
apolloClientFactory: ApolloClientFactory;
address?: string;
address?: Maybe<string>;
};

export const getRegenRoutes = ({
Expand Down Expand Up @@ -171,7 +173,15 @@ export const getRegenRoutes = ({
})}
></Route>
</Route>
<Route path="project/:projectId/buy" element={<BuyCredits />} />
<Route
path="project/:projectId/buy"
element={<BuyCredits />}
loader={buyCreditsLoader({
queryClient: reactQueryClient,
apolloClientFactory,
address,
})}
/>
<Route
path="post/:iri"
element={<Post />}
Expand Down Expand Up @@ -352,11 +362,12 @@ export const getRegenRoutes = ({
export const getRegenRouter = ({
reactQueryClient,
apolloClientFactory,
address,
}: RouterParams): Router => {
const sentryCreateBrowserRouter =
Sentry.wrapCreateBrowserRouter(createBrowserRouter);
return sentryCreateBrowserRouter(
getRegenRoutes({ reactQueryClient, apolloClientFactory }),
getRegenRoutes({ reactQueryClient, apolloClientFactory, address }),
{
basename: import.meta.env.PUBLIC_URL,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export type PrivateAccount = {
google_email: string | null;
};

type Accounts = {
export type Accounts = {
activeAccountId: string;
authenticatedAccounts?: Array<PrivateAccount>;
};
Expand Down
73 changes: 73 additions & 0 deletions web-marketplace/src/pages/BuyCredits/BuyCredits.loader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { ApolloClient, NormalizedCacheObject } from '@apollo/client';
import { SellOrderInfo } from '@regen-network/api/lib/generated/regen/ecocredit/marketplace/v1/query';
import { QueryClient } from '@tanstack/react-query';
import { getDefaultStore } from 'jotai';

import { Maybe } from 'generated/graphql';
import { selectedLanguageAtom } from 'lib/atoms/languageSwitcher.atoms';
import { ApolloClientFactory } from 'lib/clients/apolloClientFactory';
import { getMarketplaceQueryClient } from 'lib/clients/regen/ecocredit/marketplace/marketplaceQueryClient';
import { getSellOrdersExtendedQuery } from 'lib/queries/react-query/ecocredit/marketplace/getSellOrdersExtendedQuery/getSellOrdersExtendedQuery';
import { getProjectBySlugQuery } from 'lib/queries/react-query/registry-server/graphql/getProjectBySlugQuery/getProjectBySlugQuery';
import { getFromCacheOrFetch } from 'lib/queries/react-query/utils/getFromCacheOrFetch';

import { getIsOnChainId } from 'components/templates/ProjectDetails/ProjectDetails.utils';

type LoaderType = {
queryClient: QueryClient;
apolloClientFactory: ApolloClientFactory;
address?: Maybe<string>;
};
/**
* Loader function for the Buy Credits page that checks if there are available
* sell orders in a given project where the current account address is not the seller.
* Returns true if at least one sell order exists from a different seller.
*/
export const buyCreditsLoader =
({ queryClient, apolloClientFactory, address }: LoaderType) =>
async ({
params: { projectId: projectIdParam },
}: {
params: { projectId?: string };
}) => {
const isOnChainId = getIsOnChainId(projectIdParam);
const apolloClient =
apolloClientFactory.getClient() as ApolloClient<NormalizedCacheObject>;
const marketplaceClient = await getMarketplaceQueryClient();
const atomStore = getDefaultStore();
const selectedLanguage = atomStore.get(selectedLanguageAtom);

const sellOrdersQuery = getSellOrdersExtendedQuery({
client: marketplaceClient,
reactQueryClient: queryClient,
request: {},
});

const allSellOrders = await getFromCacheOrFetch({
query: sellOrdersQuery,
reactQueryClient: queryClient,
});

const projectBySlugQuery = getProjectBySlugQuery({
client: apolloClient,
enabled: !!projectIdParam && !isOnChainId,
slug: projectIdParam as string,
languageCode: selectedLanguage,
});

const projectBySlug = await getFromCacheOrFetch({
query: projectBySlugQuery,
reactQueryClient: queryClient,
});
const projectBySlugId = projectBySlug?.data?.projectBySlug?.onChainId;
const projectId = isOnChainId ? projectIdParam : projectBySlugId;

const availableSellOrders = allSellOrders?.filter(
(sellOrder: SellOrderInfo) =>
sellOrder.seller !== address &&
projectId &&
sellOrder.batchDenom?.startsWith(projectId),
);

return !!availableSellOrders?.length;
};
14 changes: 13 additions & 1 deletion web-marketplace/src/pages/BuyCredits/BuyCredits.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useLoaderData, useNavigate, useParams } from 'react-router-dom';
import { useAtom, useAtomValue } from 'jotai';

import { Loading } from 'web-components/src/components/loading';

import NotFoundPage from 'pages/NotFound';
import WithLoader from 'components/atoms/WithLoader';
import { MultiStepTemplate } from 'components/templates/MultiStepTemplate';
Expand All @@ -17,6 +19,14 @@ import { useSummarizePayment } from './hooks/useSummarizePayment';

export const BuyCredits = () => {
const { projectId } = useParams();
const navigate = useNavigate();
const accountCanBuy = useLoaderData();

useEffect(() => {
if (!accountCanBuy) {
navigate(`/project/${projectId}`, { replace: true });
}
}, [navigate, projectId, accountCanBuy]);

const {
loadingSanityProject,
Expand Down Expand Up @@ -78,6 +88,8 @@ export const BuyCredits = () => {
}
}, [paymentOption, retiring, setRetiring]);

if (!accountCanBuy) return <Loading />;

if (noProjectFound) return <NotFoundPage />;

return (
Expand Down