Skip to content

Commit

Permalink
Merge branch 'master' of github.com:GoodDollar/GoodCollective into fi…
Browse files Browse the repository at this point in the history
…x-swapandflow
  • Loading branch information
L03TJ3 committed Feb 5, 2024
2 parents a2ea0f5 + 0937e35 commit dc553d5
Show file tree
Hide file tree
Showing 12 changed files with 141 additions and 60 deletions.
3 changes: 2 additions & 1 deletion packages/app/src/components/DonorsList/DonorsList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,13 @@ function DonorsList({ donors, listStyle }: DonorsListProps) {
const userAddresses = useMemo(() => {
return sortedDonors.map((donor) => donor.donor as `0x${string}`);
}, [sortedDonors]);

const userFullNames = useFetchFullNames(userAddresses);

return (
<View style={[styles.list, { ...(listStyle ?? {}) }]}>
{sortedDonors.map((donor, index) => (
<DonorsListItem key={donor.donor} donor={donor} rank={index + 1} userFullName={userFullNames[index]} />
<DonorsListItem key={donor.donor} donor={donor} rank={index + 1} userFullName={userFullNames[donor.donor]} />
))}
</View>
);
Expand Down
12 changes: 7 additions & 5 deletions packages/app/src/components/DonorsList/DonorsListItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,22 @@ import Decimal from 'decimal.js';
import { formatAddress } from '../../lib/formatAddress';
import { ethers } from 'ethers';
import { useEnsName } from 'wagmi';
import { useFlowingBalance } from '../../hooks/useFlowingBalance';

interface DonorsListItemProps {
donor: DonorCollective;
rank: number;
userFullName?: string;
}

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

const formattedDonations: string = new Decimal(ethers.utils.formatEther(donor.contribution) ?? 0).toFixed(
2,
Decimal.ROUND_DOWN
const { formatted: formattedDonations } = useFlowingBalance(
donor.contribution,
donor.timestamp,
donor.flowRate,
undefined
);

const { data: ensName } = useEnsName({ address: donor.donor as `0x${string}`, chainId: 1 });
Expand Down
8 changes: 7 additions & 1 deletion packages/app/src/components/FlowingCurrentPoolRowItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { useDonorCollectivesFlowingBalancesWithAltStaticBalance } from '../hooks
import { DonorCollective } from '../models/models';
import { useGetTokenBalance } from '../hooks/useGetTokenBalance';
import { SupportedNetwork } from '../models/constants';
import Decimal from 'decimal.js';

interface FlowingDonationsRowItemProps {
rowInfo: string;
Expand All @@ -14,6 +15,7 @@ interface FlowingDonationsRowItemProps {
tokenPrice: number | undefined;
currency?: string;
imageUrl: string;
additionalBalance?: string;
}

function FlowingDonationsRowItem({
Expand All @@ -23,14 +25,18 @@ function FlowingDonationsRowItem({
tokenPrice,
currency,
imageUrl,
additionalBalance,
}: FlowingDonationsRowItemProps) {
const [isDesktopResolution] = useMediaQuery({
minWidth: 920,
});

const currentBalance = useGetTokenBalance('G$', collective, SupportedNetwork.CELO);
const balanceUsed = additionalBalance
? new Decimal(currentBalance).add(additionalBalance).toFixed(0, Decimal.ROUND_DOWN)
: currentBalance;
const { formatted: formattedCurrentPool, usdValue: usdValueCurrentPool } =
useDonorCollectivesFlowingBalancesWithAltStaticBalance(currentBalance, donorCollectives, tokenPrice);
useDonorCollectivesFlowingBalancesWithAltStaticBalance(balanceUsed, donorCollectives, tokenPrice);

return (
<View style={styles.row}>
Expand Down
11 changes: 7 additions & 4 deletions packages/app/src/components/Header/ConnectedAccountDisplay.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { Image, StyleSheet, Text, View } from 'react-native';
import { useEnsName, useNetwork } from 'wagmi';

import { InterRegular } from '../../utils/webFonts';
import { formatAddress } from '../../lib/formatAddress';
import { useEnsName, useNetwork } from 'wagmi';
import { Colors } from '../../utils/colors';
import { PlaceholderAvatar } from '../../assets';
import { useGetTokenBalance } from '../../hooks/useGetTokenBalance';
import { formatNumberWithCommas } from '../../lib/formatFiatCurrency';
import { SupportedNetwork } from '../../models/constants';

interface ConnectedAccountDisplayProps {
isDesktopResolution: boolean;
Expand All @@ -17,8 +19,9 @@ export const ConnectedAccountDisplay = (props: ConnectedAccountDisplayProps) =>

const { chain } = useNetwork();
let chainName = chain?.name.replace(/\d+|\s/g, '');
if (chainName !== 'Celo') {
chainName = 'None';
console.log('chainName', { chainName, chain: chain });
if (!(chainName && chainName.toUpperCase() in SupportedNetwork)) {
chainName = 'Unsupported Network';
}

const tokenBalance = useGetTokenBalance('G$', address, chain?.id, true);
Expand All @@ -33,7 +36,7 @@ export const ConnectedAccountDisplay = (props: ConnectedAccountDisplayProps) =>
<View
style={{
...styles.walletWhiteContainer,
width: 48,
minWidth: 48,
...InterRegular,
}}>
<Text style={{ ...InterRegular }}>{chainName}</Text>
Expand Down
8 changes: 4 additions & 4 deletions packages/app/src/components/RowItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,15 @@ function RowItem({ rowInfo, rowData, balance, currency, imageUrl }: RowItemProps
<Image source={{ uri: imageUrl }} style={styles.rowIcon} />
<Text style={styles.rowInfo}>{rowInfo}</Text>
</View>
<Text style={styles.rowData}>
<View style={{ gap: 2 }}>
<View style={styles.rowData}>
<Text style={{ gap: 2 }}>
<Text>
<Text>{currency}</Text> <Text style={{ ...InterRegular }}>{rowData}</Text>
{isDesktopResolution && currency && <Text style={styles.rowBalance}> = {usdBalance} USD</Text>}
</Text>
{!isDesktopResolution && currency && <Text style={styles.rowBalance}>= {usdBalance} USD</Text>}
</View>
</Text>
</Text>
</View>
</View>
);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/components/StewardsList/StewardsList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ function StewardList({ listType, stewards, titleStyle, listStyle }: StewardListP
showActions={listType === 'viewStewards'}
key={steward.steward}
profileImage={profileImages[index % profileImages.length]}
userFullName={userFullNames[index]}
userFullName={userFullNames[steward.steward]}
/>
))}
</View>
Expand Down
9 changes: 6 additions & 3 deletions packages/app/src/components/ViewCollective.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import {
WebIcon,
} from '../assets/';
import { calculateGoodDollarAmounts } from '../lib/calculateGoodDollarAmounts';
import FlowingDonationsRowItem from './FlowingDonationsRowItem';
import { useDeleteFlow } from '../hooks/useContractCalls/useDeleteFlow';
import ErrorModal from './modals/ErrorModal';
import FlowingCurrentPoolRowItem from './FlowingCurrentPoolRowItem';
Expand Down Expand Up @@ -189,12 +188,14 @@ function ViewCollective({ collective }: ViewCollectiveProps) {
<RowItem imageUrl={ListGreenIcon} rowInfo="# of Payments Made" rowData={paymentsMade ?? 0} currency="" />
</View>
<View style={{ flex: 1, gap: 16 }}>
<FlowingDonationsRowItem
<FlowingCurrentPoolRowItem
imageUrl={ReceiveLightIcon}
rowInfo="Total Donations Received"
collective={collective.address as `0x${string}`}
donorCollectives={donorCollectives}
tokenPrice={tokenPrice}
currency="G$"
additionalBalance={totalRewards}
/>
<RowItem
imageUrl={SendIcon}
Expand Down Expand Up @@ -282,12 +283,14 @@ function ViewCollective({ collective }: ViewCollectiveProps) {
<RowItem imageUrl={CalendarIcon} rowInfo="Creation Date" rowData={formatTime(timestamp)} />
<RowItem imageUrl={StewardGreen} rowInfo="Stewards Paid" rowData={stewardsPaid ?? 0} />
<RowItem imageUrl={ListGreenIcon} rowInfo="# of Payments Made" rowData={paymentsMade ?? 0} currency="" />
<FlowingDonationsRowItem
<FlowingCurrentPoolRowItem
imageUrl={ReceiveLightIcon}
rowInfo="Total Donations Received"
collective={collective.address as `0x${string}`}
donorCollectives={donorCollectives}
tokenPrice={tokenPrice}
currency="G$"
additionalBalance={totalRewards}
/>
<RowItem
imageUrl={SendIcon}
Expand Down
60 changes: 35 additions & 25 deletions packages/app/src/hooks/apollo/useCreateMongoDbApolloClient.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
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 { ApolloClient, from, HttpLink, NormalizedCacheObject } from '@apollo/client';
import { AsyncStorageWrapper, persistCache } from 'apollo3-cache-persist';
import AsyncStorage from '@react-native-async-storage/async-storage';

import { errorLink, retryLink } from '../../utils/apolloLinkUtils';

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

Expand Down Expand Up @@ -42,32 +44,40 @@ export const useCreateMongoDbApolloClient = (): ApolloClient<any> | undefined =>
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',
},
const httpLink = 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);
},
});
setApolloClient(client);

try {
const client = new ApolloClient({
cache,
link: from([errorLink, retryLink, httpLink]),
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network',
},
query: {
fetchPolicy: 'cache-first',
},
},
});
setApolloClient(client);
} catch (error) {
console.error(error);
} finally {
return;
}
}

initApollo().catch(console.error);
Expand Down
10 changes: 8 additions & 2 deletions packages/app/src/hooks/apollo/useCreateSubgraphApolloClient.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,28 @@
import { useEffect, useState } from 'react';
import { ApolloClient, InMemoryCache, NormalizedCacheObject } from '@apollo/client';
import { ApolloClient, from, HttpLink, InMemoryCache, NormalizedCacheObject } from '@apollo/client';
import { AsyncStorageWrapper, persistCache } from 'apollo3-cache-persist';
import AsyncStorage from '@react-native-async-storage/async-storage';

import { errorLink, retryLink } from '../../utils/apolloLinkUtils';

const subgraphUri = 'https://api.thegraph.com/subgraphs/name/gooddollar/goodcollective';

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

useEffect(() => {
const httpLink = new HttpLink({
uri: subgraphUri,
});
async function initApollo() {
const cache = new InMemoryCache();
await persistCache({
cache,
storage: new AsyncStorageWrapper(AsyncStorage),
});

const client = new ApolloClient({
uri: subgraphUri,
link: from([errorLink, retryLink, httpLink]),
cache,
defaultOptions: {
watchQuery: {
Expand Down
45 changes: 34 additions & 11 deletions packages/app/src/hooks/useFetchFullName.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ import { useMongoDbQuery } from './apollo/useMongoDbQuery';

interface UserProfile {
fullName?: { display?: string };
index: {
walletAddress: {
hash: string;
display?: string;
};
};
}

interface UserProfilesResponse {
Expand All @@ -17,6 +23,11 @@ const findProfiles = gql`
fullName {
display
}
index {
walletAddress {
hash
}
}
}
}
`;
Expand All @@ -27,22 +38,34 @@ export function useFetchFullName(address?: string): string | undefined {
return names[0];
}

export function useFetchFullNames(addresses: string[]): (string | undefined)[] {
const hashedAddresses = useMemo(() => {
return addresses.map((address: string) => ethers.utils.keccak256(address));
}, [addresses]);
export function useFetchFullNames(addresses: string[]): any {
const addressToHashMapping = addresses.reduce((acc: any, address) => {
const hash = ethers.utils.keccak256(address);
acc[hash] = address;
return acc;
}, {});

const hashedAddresses = Object.keys(addressToHashMapping);

const { data, error } = useMongoDbQuery<UserProfilesResponse>(findProfiles, {
variables: { query: { index: { walletAddress: { hash_in: hashedAddresses } } } },
variables: {
query: {
index: { walletAddress: { hash_in: hashedAddresses } },
},
},
});

return useMemo(() => {
if (error) {
console.error(error);
}
if (!data || data.user_profiles.length === 0) {
return [];
return {};
}
return data.user_profiles.map((profile) => profile?.fullName?.display);
}, [data, error]);
return data.user_profiles.reduce((acc: Record<string, string>, profile) => {
if (!profile) return {};
const { hash } = profile.index.walletAddress;
const { display } = profile.fullName ?? {};
const address = addressToHashMapping[hash];
acc[address] = display ?? '';
return acc;
}, {});
}, [data, addressToHashMapping]);
}
6 changes: 3 additions & 3 deletions packages/app/src/hooks/useSwapRoute.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { AlphaRouter, SwapRoute, SwapType, V3Route } from '@uniswap/smart-order-router';
import { CurrencyAmount, Percent, TradeType } from '@uniswap/sdk-core';
import { useAccount, useNetwork } from 'wagmi';
import { GDToken } from '../models/constants';
import { GDToken, SupportedNetwork } from '../models/constants';
import { useEthersSigner } from './useEthersSigner';
import { calculateRawTotalDonation } from '../lib/calculateRawTotalDonation';
import Decimal from 'decimal.js';
Expand Down Expand Up @@ -39,13 +39,13 @@ export function useSwapRoute(
const [route, setRoute] = useState<SwapRoute | undefined>(undefined);

useEffect(() => {
if (!address || !chain?.id || !signer?.provider || tokenIn.symbol === 'G$') {
if (!address || !chain?.id || chain.id !== SupportedNetwork.CELO || !signer?.provider || tokenIn.symbol === 'G$') {
setRoute(undefined);
return;
}

const router = new AlphaRouter({
chainId: chain.id,
chainId: chain.id as number,
provider: signer.provider,
});

Expand Down
Loading

0 comments on commit dc553d5

Please sign in to comment.