Skip to content

Commit

Permalink
fetch full names of users (#113)
Browse files Browse the repository at this point in the history
* Working through SuperToken Initialization Error: There was an error initializing the SuperToken, last part needed it to get the contract fucntion to pass

* Done

* .

* fix: hardhat lint

* add: override reward

* add: deployed upgraded pool with override

* fix: contracts types build

* fix: ethers typescript errors

* fix: types

* update

* updated subgraph

* Put back functions lost

* fix: deploy preview on udpates to PR

* wip: test preview yml

* fix: lock file

* Update donor

* add: tsc lint-staged

* fix: lock issue

* fix: typescript jsx transform

* Update donor

* .

* fix: unit tests

* .

* update

* Fix: build

* fix: unit tests

* fix: build correctly

* wip: fix PR test

* Update readme to clarify that packages must be built locally

* Attempt to port existing desktop wallet connection handling to mobile

* fix: event quantity

* refactor: package.json

* Point to working subgraph

* refactored header and changed wallet connect buttons layout to menu

* added todo item

* fixed wallet connector dropdown offset

* animated wallet connector menu button arrow

* Collective Home Card description is now limited to 3 lines and expands on click

* reduced width of desktop home collective card containers so they more closely resemble the mobile card containers

* fixed padding on ViewCollective page and did some touchups on stewards list

* fixed CTA button size on DonationPage

* fixed Breadcrumb on DonationPage

* fixed icon alignment on ViewCollective page

* added random profile pics for stewards

* fixes for layout of ViewStewards page on mobile

* small refactors while trying to figure out why "see all stewards" button isn't working on desktop

* set gap between stewards and transactions to 32 on desktop ViewCollective page

* refactored subgraph data fetching

* fix: empty arrays, relations

* wip: subgraph fixes

* additional refactoring of models

* small progress made in adding dynamic data

* reworked subgraph; added entities for StewardCollective, Reward, DonorCollective, and Donation

* updated pool creation in subgraph

* adjusted Collective schema

* made all fields non-nullable since they all have values when instantiated

* removed 'contributions' summary value from Collective

* added summary statistics to Collective

* updated contribution calculations for donors in subgraph

* added dev comments in schema for clarity

* reworked subgraph queries and model transforms (build broken)

* added dynamic data to ViewCollective and ViewStewards (build broken)

* updated wallet profile page

* removed unused pages and fixed build

* added ipfs data parsing and removed unused reward/donation code

* fixed ipfs collective id

* Add: Design system (#54)

* add: design system, svg support

* add: svg default exports, apply svg icons to ViewCollective

* - add withTheme hook for the AboutCard
- add theme also to native provider

* fix: apply styles for aboutcard better, add readme

* fix: forgot to comment out web3modal

* chore: bump good-design

* Update README.md

* front end now obtains ipfs data from subgraph instead of fetching directly from ipfs

* minor refactoring

* made event-claim relationship m:1

* fix: exluded deps from bundle

* fix for desktop padding on view collective page

* added tsconfig for assemblyscript in subgraph package

* updated ViewDonorsPage and its components

* added correct Collective metadata to donate page

* added ipfs collective metadata update to handlePoolDetailsChanged

* changed variable name 'nftAddress' to 'nftId' in subgraph pool.ts; changed derivedFrom relationships in collective

* removed deriveFrom relationship from eventdata claim

* reconfigured subgraph to recognize factory-template relationship between poolfactory and pool

* fix: subgraph null, ipfs, mappings file

* ensured required values in subgraph entities are populated

* update yarn.lock

* fixed assemblyscript config extension path

* updated DonateComponent to determine if balance is sufficient; removed @Constants dir

* added donation timestamp to DonorCollective (needed for superfluid real-time updates)

* added donation timestamp to DonorCollective (needed for superfluid real-time updates)

* removed missed usages of @Constants folder

* fix: yarn lock

* displaying realtime superfluid donations (untested)

* fixed null values in handleRewardClaim NFT

* updated yarn lock

* updated yarn lock

* using hex string for pool project id due to invalid utf-8 data

* removed ipfs retries since they don't seem to help

* fixed Claim totalRewards initialization

* reworked ipfs usage in subgraph to use new data source feature

* updated data flow to accomodate subgraph updates

* add required fields to ipfs entity in subgraph

* adjusted ipfs fetching in front end

* renamed IpfsCollective.address to IpfsCollective.collective

* removed IpfsCollective.collective

* fixes to subgraph ipfs fetching in front end

* removed several hard-coded SVG strings

* several minor fixes

* various minor fixes

* reworked wallet profile UI

* removed use of `window`

* refactored useGetBalance

* post-merge fixes

* removed unused constants

* removed redundant view from ViewStewardsPage.tsx

* removed unused styles from ViewStewardsPage.tsx

* removed unused styles from ViewDonorsPage.tsx

* ui fixes ViewStewardsPage and ViewDonorsPage

* removed unused import and console log

* updated useContractCalls and much of DonateComponent

* fixed double usage of insufficientLiquidity

* simplified DonorListItem ranks

* ProfileView refactor

* added useApproveSwapTokenCallback and useSwapRoute

* removed mock data

* draft swap integration

* added index to hooks/useContractCalls

* prevented swap from G$ to G$

* fixed formatting and some swap bugs

* removed unused function from lib

* added flowing balances for total donation amounts for collectives and donors

* added useTokenList hook

* now using celo token list

* removed unused import

* made dropdown menu scrollable

* added storage cache to apollo client

* swap works!

* adjustments to reflect uniswap default slippage tolerance

* fixed jsbi via vite configuration

* changed priceImpact to number

* updated default apollo client fetch policy to 'cache-and-network'

* removed unused `WalletConnectionProvider` context

* by request, handleApproveToken is no longer memoized

* fixed GD formatting in Donor List

* changed acceptable price impact percent to 5% and moved it to constants.ts

* add swap and fix donate (#72)

* updated useContractCalls and much of DonateComponent

* added useApproveSwapTokenCallback and useSwapRoute

* draft swap integration

* added index to hooks/useContractCalls

* prevented swap from G$ to G$

* fixed formatting and some swap bugs

* removed unused function from lib

* now using celo token list

* removed unused import

* made dropdown menu scrollable

* swap works!

* adjustments to reflect uniswap default slippage tolerance

* fixed jsbi via vite configuration

* changed priceImpact to number

* removed unused `WalletConnectionProvider` context

* by request, handleApproveToken is no longer memoized

* fixed GD formatting in Donor List

* changed acceptable price impact percent to 5% and moved it to constants.ts

* added steward verification check

* added currentPool value fetching

* added "people supported" counts

* fixed for useIsStewardVerified and added FlowingDonationsRowItem to reduce re-renders

* fixes for currentPool, donor list

* fix for ens name support

* fix social links and show only if available

* changed DonorListItem amount display from toFixed to toString

* sort connectors with WalletConnect before MetaMask

* added token symbol next to wallet balance and adjusted balance formatting

* update copy for on-time donation, added chain check to useEthersSigner and useGetTokenBalance

* one-time transfer now assumes token is already approved for transfer

* G$ donation now assumes token is already approved for transfer

* added infoButton property to ipfs meta data in subgraph

* increased slippage tolerance from 0.5% to 1%

* made it so only G$ shows in token list for one-time donations

* made it so selecting one-time donation changes currency to G$ and amount to 0

* fixed total donation usd value

* swap errors will only show if donation amount is not zero

* added infoLabel to front end

* updated breadcrumb to show collective name and only go back to previous page if back arrow is clicked

* updated breadcrumb to fix links and text

* incremented subgraph starting block because prior block was failing

* donation is now disabled if swap required and token approval not yet ready; token approval should not fail on retry

* breadcrumb formatting for '/'

* adjusted G$ formatting in profile

* modal and donation error formatting

* added steward profile link to steward list item

* added polling to donor in wallet; improved error message in donation functions

* fix for error message in donation functions

* switched from supportSingleTransferAndCall to supportSingleBatch since it includes token approval

* removed warnings for missing subgraph items

* set margin between collective cards on home page to 24

* fixed transaction list UI

* added useRecentTransactions hook

* fixed ViewCollective tablet portrait resolution

* removed G$ fractional amount from connected wallet display, and added currency symbol to mobile version

* made sure G$ displayed amount is rounded down to nearest int

* fixed stop donation

* changed default gas price to 5 in @gooddollar/goodcollective-sdk

* renamed enum value from celo to CELO

* currentPool is now a flowing balance

* refactor: dry up donate button styles, no inline arrow functions

* fix: getDonateStyles, does not stop loop after hitting first true

* fix: simplify getDonateStyles

* inline lambdas to const

* memoized onChangeFrequency

* added support for fetching full user names from mongodb

* added caching to useFetchFullName and fixed realm logout callback

* Bug fixes (#111)

* fix social links and show only if available

* changed DonorListItem amount display from toFixed to toString

* sort connectors with WalletConnect before MetaMask

* added token symbol next to wallet balance and adjusted balance formatting

* update copy for on-time donation, added chain check to useEthersSigner and useGetTokenBalance

* one-time transfer now assumes token is already approved for transfer

* G$ donation now assumes token is already approved for transfer

* added infoButton property to ipfs meta data in subgraph

* increased slippage tolerance from 0.5% to 1%

* made it so only G$ shows in token list for one-time donations

* made it so selecting one-time donation changes currency to G$ and amount to 0

* fixed total donation usd value

* swap errors will only show if donation amount is not zero

* added infoLabel to front end

* updated breadcrumb to show collective name and only go back to previous page if back arrow is clicked

* updated breadcrumb to fix links and text

* incremented subgraph starting block because prior block was failing

* donation is now disabled if swap required and token approval not yet ready; token approval should not fail on retry

* breadcrumb formatting for '/'

* adjusted G$ formatting in profile

* modal and donation error formatting

* added steward profile link to steward list item

* added polling to donor in wallet; improved error message in donation functions

* fix for error message in donation functions

* switched from supportSingleTransferAndCall to supportSingleBatch since it includes token approval

* removed warnings for missing subgraph items

* set margin between collective cards on home page to 24

* fixed transaction list UI

* added useRecentTransactions hook

* fixed ViewCollective tablet portrait resolution

* removed G$ fractional amount from connected wallet display, and added currency symbol to mobile version

* made sure G$ displayed amount is rounded down to nearest int

* fixed stop donation

* changed default gas price to 5 in @gooddollar/goodcollective-sdk

* renamed enum value from celo to CELO

* currentPool is now a flowing balance

* refactor: dry up donate button styles, no inline arrow functions

* fix: getDonateStyles, does not stop loop after hitting first true

* fix: simplify getDonateStyles

* inline lambdas to const

* memoized onChangeFrequency

* fixed link to smart contract in ViewCollective

* version bump

* version bump

* version bump

* version bump

* version bump

* version bump

* version bump

* version bump

* version bump

* chore: release sdk, bump in app

---------

Co-authored-by: LewisB <lewis@gooddollar.org>

* added apollo client for mongo db fetches

* changed apollo client cache policies

* added full name fetching to transactions list items

---------

Co-authored-by: Joshua-Jack <joshuajack256@gmail.com>
Co-authored-by: sirpy <hadarr@gmail.com>
Co-authored-by: LewisB <lewis@gooddollar.org>
Co-authored-by: Ben Walker <ben.walker18@gmail.com>
Co-authored-by: sirpy <hadar@gooddollar.org>
Co-authored-by: Lewis B <lewis@ikigaistudios.eu>
  • Loading branch information
7 people authored Jan 21, 2024
1 parent c9c34af commit 2ee9dbe
Show file tree
Hide file tree
Showing 19 changed files with 331 additions and 79 deletions.
2 changes: 2 additions & 0 deletions packages/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"@gooddollar/good-design": "^0.1.31",
"@gooddollar/goodcollective-sdk": "^1.0.15",
"@gooddollar/web3sdk-v2": "^0.2.2",
"@nerdwallet/apollo-cache-policies": "^3.2.0",
"@react-native-aria/interactions": "0.2.3",
"@react-native-async-storage/async-storage": "^1.18.2",
"@react-native-firebase/analytics": "16.7.0",
Expand Down Expand Up @@ -67,6 +68,7 @@
"react-native-web": "0.18.*",
"react-router-dom": "^6.14.1",
"react-router-native": "^6.14.1",
"realm-web": "^2.0.0",
"viem": "^1.10.8",
"wagmi": "^1.4.5"
},
Expand Down
102 changes: 41 additions & 61 deletions packages/app/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,11 @@ import { publicProvider } from 'wagmi/providers/public';
import { infuraProvider } from 'wagmi/providers/infura';
import { MetaMaskConnector } from 'wagmi/connectors/metaMask';
import { WalletConnectConnector } from 'wagmi/connectors/walletConnect';
import { ApolloClient, ApolloProvider, InMemoryCache, NormalizedCacheObject } from '@apollo/client';
import { ApolloProvider } from '@apollo/client';

import { Colors } from './utils/colors';
import { AsyncStorageWrapper, persistCache } from 'apollo3-cache-persist';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useEffect, useState } from 'react';
import { useCreateSubgraphApolloClient, useCreateMongoDbApolloClient } from './hooks/apollo';
import { MongoDbApolloProvider } from './components/providers/MongoDbApolloProvider';

function App(): JSX.Element {
const { publicClient, webSocketPublicClient } = configureChains(
Expand All @@ -44,77 +43,58 @@ function App(): JSX.Element {
}),
];

const [apolloClient, setApolloClient] = useState<ApolloClient<NormalizedCacheObject> | undefined>();

useEffect(() => {
async function initApollo() {
const cache = new InMemoryCache();
await persistCache({
cache,
storage: new AsyncStorageWrapper(AsyncStorage),
});
const client = new ApolloClient({
uri: 'https://api.thegraph.com/subgraphs/name/gooddollar/goodcollective',
cache,
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network',
},
},
});
setApolloClient(client);
}

initApollo().catch(console.error);
}, []);

const wagmiConfig = createConfig({
autoConnect: true,
connectors,
publicClient,
webSocketPublicClient,
});

if (!apolloClient) {
const subgraphApolloClient = useCreateSubgraphApolloClient();
const mongoDbApolloClient = useCreateMongoDbApolloClient();

if (!subgraphApolloClient || !mongoDbApolloClient) {
return <Text>Loading...</Text>;
}

return (
<Providers>
<WagmiConfig config={wagmiConfig}>
<ApolloProvider client={apolloClient}>
<SafeAreaView style={styles.body}>
{Platform.OS !== 'web' && (
<MobileRoute.Router>
<MobileRoute.Routes>
<MobileRoute.Route path="/" element={<HomePage />} />
<MobileRoute.Route path="/about" element={<AboutPage />} />
<MobileRoute.Route path="/collective/:id" element={<ViewCollectivePage />} />
<MobileRoute.Route path="/collective/:id/stewards" element={<ViewStewardsPage />} />
<MobileRoute.Route path="/collective/:id/donors" element={<ViewDonorsPage />} />
<MobileRoute.Route path="/profile/:id" element={<WalletProfilePage />} />
<MobileRoute.Route path="/profile/:id/activity" element={<ActivityLogPage />} />
<MobileRoute.Route path="/donate" element={<DonatePage />} />
</MobileRoute.Routes>
</MobileRoute.Router>
)}
<ApolloProvider client={subgraphApolloClient}>
<MongoDbApolloProvider client={mongoDbApolloClient}>
<SafeAreaView style={styles.body}>
{Platform.OS !== 'web' && (
<MobileRoute.Router>
<MobileRoute.Routes>
<MobileRoute.Route path="/" element={<HomePage />} />
<MobileRoute.Route path="/about" element={<AboutPage />} />
<MobileRoute.Route path="/collective/:id" element={<ViewCollectivePage />} />
<MobileRoute.Route path="/collective/:id/stewards" element={<ViewStewardsPage />} />
<MobileRoute.Route path="/collective/:id/donors" element={<ViewDonorsPage />} />
<MobileRoute.Route path="/profile/:id" element={<WalletProfilePage />} />
<MobileRoute.Route path="/profile/:id/activity" element={<ActivityLogPage />} />
<MobileRoute.Route path="/donate" element={<DonatePage />} />
</MobileRoute.Routes>
</MobileRoute.Router>
)}

{Platform.OS === 'web' && (
<WebRoute.Router>
<WebRoute.Routes>
<WebRoute.Route path="/" element={<HomePage />} />
<WebRoute.Route path="/about" element={<AboutPage />} />
<WebRoute.Route path="/collective/:id" element={<ViewCollectivePage />} />
<WebRoute.Route path="/collective/:id/stewards" element={<ViewStewardsPage />} />
<WebRoute.Route path="/collective/:id/donors" element={<ViewDonorsPage />} />
<WebRoute.Route path="/profile/:id" element={<WalletProfilePage />} />
<WebRoute.Route path="/profile/:id/activity" element={<ActivityLogPage />} />
<WebRoute.Route path="/profile/" element={<WalletProfilePage />} />
<WebRoute.Route path="/donate/:id" element={<DonatePage />} />
</WebRoute.Routes>
</WebRoute.Router>
)}
</SafeAreaView>
{Platform.OS === 'web' && (
<WebRoute.Router>
<WebRoute.Routes>
<WebRoute.Route path="/" element={<HomePage />} />
<WebRoute.Route path="/about" element={<AboutPage />} />
<WebRoute.Route path="/collective/:id" element={<ViewCollectivePage />} />
<WebRoute.Route path="/collective/:id/stewards" element={<ViewStewardsPage />} />
<WebRoute.Route path="/collective/:id/donors" element={<ViewDonorsPage />} />
<WebRoute.Route path="/profile/:id" element={<WalletProfilePage />} />
<WebRoute.Route path="/profile/:id/activity" element={<ActivityLogPage />} />
<WebRoute.Route path="/profile/" element={<WalletProfilePage />} />
<WebRoute.Route path="/donate/:id" element={<DonatePage />} />
</WebRoute.Routes>
</WebRoute.Router>
)}
</SafeAreaView>
</MongoDbApolloProvider>
</ApolloProvider>
</WagmiConfig>
</Providers>
Expand Down
8 changes: 7 additions & 1 deletion packages/app/src/components/DonorsList/DonorsList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { DonorCollective } from '../../models/models';
import { DonorsListItem } from './DonorsListItem';
import { useMemo } from 'react';
import Decimal from 'decimal.js';
import { useFetchFullNames } from '../../hooks/useFetchFullName';

interface DonorsListProps {
donors: DonorCollective[];
Expand All @@ -20,10 +21,15 @@ function DonorsList({ donors, listStyle }: DonorsListProps) {
});
}, [donors]);

const userAddresses = useMemo(() => {
return donors.map((donor) => donor.donor as `0x${string}`);
}, [donors]);
const userFullNames = useFetchFullNames(userAddresses);

return (
<View style={[styles.list, { ...(listStyle ?? {}) }]}>
{sortedDonors.map((donor, index) => (
<DonorsListItem donor={donor} rank={index + 1} key={donor.donor} />
<DonorsListItem key={donor.donor} donor={donor} rank={index + 1} userFullName={userFullNames[index]} />
))}
</View>
);
Expand Down
5 changes: 3 additions & 2 deletions packages/app/src/components/DonorsList/DonorsListItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,17 @@ import { useEnsName } from 'wagmi';
interface DonorsListItemProps {
donor: DonorCollective;
rank: number;
userFullName?: string;
}

export const DonorsListItem = (props: DonorsListItemProps) => {
const { donor, rank } = props;
const { donor, rank, userFullName } = props;
const { navigate } = useCrossNavigate();

const formattedDonations: string = new Decimal(ethers.utils.formatEther(donor.contribution) ?? 0).toString();

const { data: ensName } = useEnsName({ address: donor.donor as `0x${string}`, chainId: 1 });
const userIdentifier = ensName ? ensName : formatAddress(donor.donor, 5);
const userIdentifier = userFullName ?? ensName ?? formatAddress(donor.donor);

const circleBackgroundColor = rank === 1 ? Colors.yellow[100] : rank === 2 ? Colors.gray[700] : Colors.orange[400];
const circleTextColor = rank === 1 ? Colors.yellow[200] : rank === 2 ? Colors.blue[200] : Colors.brown[100];
Expand Down
7 changes: 7 additions & 0 deletions packages/app/src/components/StewardsList/StewardsList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { StewardCollective } from '../../models/models';
import { useMemo } from 'react';
import { profilePictures } from '../../utils/profilePictures';
import { StewardBlue, StewardGreen } from '../../assets';
import { useFetchFullNames } from '../../hooks/useFetchFullName';

interface StewardListProps {
listType: 'viewCollective' | 'viewStewards';
Expand All @@ -22,6 +23,11 @@ function StewardList({ listType, stewards, titleStyle, listStyle }: StewardListP
return profilePictures.sort(() => Math.random());
}, []);

const userAddresses = useMemo(() => {
return stewards.map((steward) => steward.steward as `0x${string}`);
}, [stewards]);
const userFullNames = useFetchFullNames(userAddresses);

return (
<View style={styles.stewardsListContainer}>
<View style={[styles.row, { marginBottom: 24, ...(titleStyle ?? {}) }]}>
Expand All @@ -35,6 +41,7 @@ function StewardList({ listType, stewards, titleStyle, listStyle }: StewardListP
showActions={listType === 'viewStewards'}
key={steward.steward}
profileImage={profileImages[index % profileImages.length]}
userFullName={userFullNames[index]}
/>
))}
</View>
Expand Down
5 changes: 3 additions & 2 deletions packages/app/src/components/StewardsList/StewardsListItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,17 @@ interface StewardListItemProps {
steward: StewardCollective;
showActions: boolean;
profileImage: string;
userFullName?: string;
}

export const StewardsListItem = (props: StewardListItemProps) => {
const { showActions, steward, profileImage } = props;
const { showActions, steward, profileImage, userFullName } = props;
const { navigate } = useCrossNavigate();

const isVerified = useIsStewardVerified(steward.steward);

const { data: ensName } = useEnsName({ address: steward.steward as `0x${string}`, chainId: 1 });
const userIdentifier = ensName ? ensName : formatAddress(steward.steward, 5);
const userIdentifier = userFullName ?? ensName ?? formatAddress(steward.steward);

const onClickSteward = () => navigate(`/profile/${steward.steward}`);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ClaimTx } from '../../models/models';
import { formatAddress } from '../../lib/formatAddress';
import { useEnsName } from 'wagmi';
import TransactionListItem from './TransactionListItem';
import { useFetchFullName } from '../../hooks/useFetchFullName';

interface ClaimTransactionListItemProps {
transaction: ClaimTx;
Expand All @@ -20,8 +21,9 @@ export function ClaimTransactionListItem({ transaction }: ClaimTransactionListIt
}

const { data: ensName } = useEnsName({ address: userAddress, chainId: 1 });
// TODO: how to get first name and last name of users?
const userIdentifier = multipleStewardsText ?? ensName ?? (userAddress ? formatAddress(userAddress) : 'Unknown');
const userFullName = useFetchFullName(userAddress);
const userIdentifier =
multipleStewardsText ?? userFullName ?? ensName ?? (userAddress ? formatAddress(userAddress) : 'Unknown');

return (
<TransactionListItem
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useEnsName } from 'wagmi';
import Decimal from 'decimal.js';
import TransactionListItem from './TransactionListItem';
import { useFlowingBalance } from '../../hooks/useFlowingBalance';
import { useFetchFullName } from '../../hooks/useFetchFullName';

interface SupportTransactionListItemProps {
transaction: SupportTx;
Expand All @@ -12,10 +13,9 @@ interface SupportTransactionListItemProps {
export function SupportTransactionListItem({ transaction }: SupportTransactionListItemProps) {
const { hash, networkFee, timestamp, donor } = transaction;

// TODO: how to get first name and last name of users?
const userFullName: string | undefined = undefined;
const userAddress = donor as `0x${string}`;
const { data: ensName } = useEnsName({ address: userAddress, chainId: 1 });
const userFullName = useFetchFullName(userAddress);
const userIdentifier = userFullName ?? ensName ?? formatAddress(userAddress);

const { formatted: formattedAmount } = useFlowingBalance(
Expand Down
2 changes: 0 additions & 2 deletions packages/app/src/components/ViewCollective.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,6 @@ interface ViewCollectiveProps {
collective: Collective;
}

// TODO: "See all Stewards" button doesn't work for me and I can't figure out why

function ViewCollective({ collective }: ViewCollectiveProps) {
const { navigate } = useCrossNavigate();
const [isDesktopResolution] = useMediaQuery({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Text, View } from 'react-native';
import { Steward } from '../../models/models';
import { ethers } from 'ethers';
import { styles } from './styles';
import { calculateGoodDollarAmounts } from '../../lib/calculateGoodDollarAmounts';

Expand Down
20 changes: 20 additions & 0 deletions packages/app/src/components/providers/MongoDbApolloProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import React, { createContext, PropsWithChildren, useContext } from 'react';
import { ApolloClient } from '@apollo/client';

type MongoDbApolloProviderProps = {
client: ApolloClient<any>;
};

const MongoDbApolloContext = createContext<ApolloClient<any> | undefined>(undefined);

export const MongoDbApolloProvider = ({ children, client }: PropsWithChildren<MongoDbApolloProviderProps>) => {
return <MongoDbApolloContext.Provider value={client}>{children}</MongoDbApolloContext.Provider>;
};

export const useMongoDbApolloClient = (): ApolloClient<any> => {
const context = useContext(MongoDbApolloContext);
if (!context) {
throw new Error('useMongoDbApollo must be used within a MongoDbApolloProvider');
}
return context;
};
2 changes: 2 additions & 0 deletions packages/app/src/hooks/apollo/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './useCreateMongoDbApolloClient';
export * from './useCreateSubgraphApolloClient';
76 changes: 76 additions & 0 deletions packages/app/src/hooks/apollo/useCreateMongoDbApolloClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { ApolloClient, HttpLink, NormalizedCacheObject } from '@apollo/client';
import { useEffect, useState } from 'react';
import * as Realm from 'realm-web';
import { InvalidationPolicyCache, RenewalPolicy } from '@nerdwallet/apollo-cache-policies';
import { AsyncStorageWrapper, persistCache } from 'apollo3-cache-persist';
import AsyncStorage from '@react-native-async-storage/async-storage';

const APP_ID = 'wallet_prod-obclo';
const mongoDbUri = `https://realm.mongodb.com/api/client/v2.0/app/${APP_ID}/graphql`;

export const useCreateMongoDbApolloClient = (): ApolloClient<any> | undefined => {
const [apolloClient, setApolloClient] = useState<ApolloClient<NormalizedCacheObject> | undefined>();

useEffect(() => {
async function initApollo() {
const app = new Realm.App(APP_ID);

async function getValidAccessToken() {
if (!app.currentUser) {
await app.logIn(Realm.Credentials.anonymous());
} else {
await app.currentUser.refreshCustomData();
}
return app.currentUser?.accessToken;
}

const cache = new InvalidationPolicyCache({
invalidationPolicies: {
timeToLive: 3600 * 1000, // 24hr TTL on all types in the cache
renewalPolicy: RenewalPolicy.AccessAndWrite,
types: {
User_profile: {
timeToLive: 3600 * 1000 * 24, // 1 day
},
},
},
});

await persistCache({
cache,
storage: new AsyncStorageWrapper(AsyncStorage),
});

const client = new ApolloClient({
cache,
link: new HttpLink({
uri: mongoDbUri,
fetch: async (uri, options) => {
const accessToken = await getValidAccessToken();
if (!options) {
options = {};
}
if (!options.headers) {
options.headers = {};
}
(options.headers as Record<string, any>).Authorization = `Bearer ${accessToken}`;
return fetch(uri, options);
},
}),
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network',
},
query: {
fetchPolicy: 'cache-first',
},
},
});
setApolloClient(client);
}

initApollo().catch(console.error);
}, []);

return apolloClient;
};
Loading

0 comments on commit 2ee9dbe

Please sign in to comment.