From 0406ccc96011ec0f71ddf0d0a86d83248958bde4 Mon Sep 17 00:00:00 2001
From: Peiman <25097709+Rickk137@users.noreply.github.com>
Date: Tue, 18 Jun 2024 15:34:13 +0330
Subject: [PATCH] Fix/pools loading (#309)

* fix: pool loading issue

* fix: type issue

* fix: pool collateral prices

* fix: duplicated rewards
---
 .../useCollateralPriceUpdates/package.json    |  1 +
 .../useCollateralPriceUpdates.ts              | 19 ++++++++++++-------
 liquidity/lib/useCoreProxy/useCoreProxy.ts    |  2 +-
 .../useLiquidityPositions.ts                  |  4 +---
 liquidity/lib/usePools/usePools.ts            |  9 +++++----
 .../components/Pools/CollateralSection.tsx    | 19 ++++++++++---------
 .../components/Pools/PoolCards/PoolCard.tsx   | 17 +----------------
 liquidity/ui/src/pages/Pool.tsx               |  7 +++++--
 yarn.lock                                     |  1 +
 9 files changed, 37 insertions(+), 42 deletions(-)

diff --git a/liquidity/lib/useCollateralPriceUpdates/package.json b/liquidity/lib/useCollateralPriceUpdates/package.json
index a8b4151a1..08a269049 100644
--- a/liquidity/lib/useCollateralPriceUpdates/package.json
+++ b/liquidity/lib/useCollateralPriceUpdates/package.json
@@ -7,6 +7,7 @@
     "@pythnetwork/pyth-evm-js": "^1.42.0",
     "@snx-v3/constants": "workspace:*",
     "@snx-v3/contracts": "workspace:*",
+    "@snx-v3/format": "workspace:*",
     "@snx-v3/isBaseAndromeda": "workspace:*",
     "@snx-v3/useBlockchain": "workspace:*",
     "@snx-v3/usePoolsList": "workspace:*",
diff --git a/liquidity/lib/useCollateralPriceUpdates/useCollateralPriceUpdates.ts b/liquidity/lib/useCollateralPriceUpdates/useCollateralPriceUpdates.ts
index 566a85202..a64ab8cdc 100644
--- a/liquidity/lib/useCollateralPriceUpdates/useCollateralPriceUpdates.ts
+++ b/liquidity/lib/useCollateralPriceUpdates/useCollateralPriceUpdates.ts
@@ -1,5 +1,5 @@
 import { useQuery } from '@tanstack/react-query';
-import { ethers } from 'ethers';
+import { BigNumberish, ethers } from 'ethers';
 import { Network, useDefaultProvider, useNetwork, useWallet } from '@snx-v3/useBlockchain';
 import { EvmPriceServiceConnection } from '@pythnetwork/pyth-evm-js';
 import { offchainMainnetEndpoint } from '@snx-v3/constants';
@@ -7,8 +7,9 @@ import { ERC7412_ABI } from '@snx-v3/withERC7412';
 import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda';
 import { importMulticall3, importExtras } from '@snx-v3/contracts';
 import { networksOffline } from '@snx-v3/usePoolsList';
-import { wei, Wei } from '@synthetixio/wei';
+import { wei } from '@synthetixio/wei';
 import { importPythERC7412Wrapper } from '@snx-v3/contracts';
+import { parseUnits } from '@snx-v3/format';
 
 const priceService = new EvmPriceServiceConnection(offchainMainnetEndpoint);
 
@@ -123,10 +124,14 @@ export const useOfflinePrices = (collaterals?: Collaterals[]) => {
         throw 'useOfflinePrices is missing required data';
       }
 
-      const returnData: { symbol: string; price: Wei }[] = [
+      const returnData: { symbol: string; price: BigNumberish }[] = [
         {
           symbol: 'sUSDC',
-          price: wei(1),
+          price: wei(1).toBN(),
+        },
+        {
+          symbol: 'USDC',
+          price: wei(1).toBN(),
         },
       ];
 
@@ -149,9 +154,9 @@ export const useOfflinePrices = (collaterals?: Collaterals[]) => {
       prices?.forEach((item, index) => {
         const price = item.getPriceUnchecked();
 
-        returnData.unshift({
-          symbol: filteredCollaterals[index].symbol,
-          price: wei(price.price, price.expo),
+        returnData.push({
+          symbol: collaterals[index].symbol,
+          price: parseUnits(price.price, 18 + price.expo),
         });
       });
 
diff --git a/liquidity/lib/useCoreProxy/useCoreProxy.ts b/liquidity/lib/useCoreProxy/useCoreProxy.ts
index 8ee141214..3e11e8c7b 100644
--- a/liquidity/lib/useCoreProxy/useCoreProxy.ts
+++ b/liquidity/lib/useCoreProxy/useCoreProxy.ts
@@ -9,7 +9,7 @@ import {
 } from '@snx-v3/useBlockchain';
 import { importCoreProxy } from '@snx-v3/contracts';
 
-export function useCoreProxy(customNetwork?: Network) {
+export function useCoreProxy(customNetwork?: Network | null) {
   const providerForChain = useProviderForChain(customNetwork);
   const { network } = useNetwork();
   const provider = useProvider();
diff --git a/liquidity/lib/useLiquidityPositions/useLiquidityPositions.ts b/liquidity/lib/useLiquidityPositions/useLiquidityPositions.ts
index bfc65ee93..bfc16de4e 100644
--- a/liquidity/lib/useLiquidityPositions/useLiquidityPositions.ts
+++ b/liquidity/lib/useLiquidityPositions/useLiquidityPositions.ts
@@ -161,9 +161,7 @@ export const useLiquidityPositions = ({ accountId }: { accountId?: string }) =>
         'useLiquidityPositions'
       );
     },
-    enabled: Boolean(
-      collateralPriceUpdates && CoreProxy && collateralTypes?.length && accountId && pools?.length
-    ),
+    enabled: Boolean(CoreProxy && collateralTypes?.length && accountId && pools?.length),
   });
 
   return {
diff --git a/liquidity/lib/usePools/usePools.ts b/liquidity/lib/usePools/usePools.ts
index b532a5275..820c4d827 100644
--- a/liquidity/lib/usePools/usePools.ts
+++ b/liquidity/lib/usePools/usePools.ts
@@ -21,15 +21,16 @@ export type PoolsType = z.infer<typeof PoolsSchema>;
 
 export function usePools(customNetwork?: Network) {
   const { network } = useNetwork();
-  const { data: CoreProxy } = useCoreProxy(customNetwork);
-
   const targetNetwork = customNetwork || network;
+  const { data: CoreProxy } = useCoreProxy(targetNetwork);
 
   return useQuery({
     enabled: Boolean(targetNetwork),
-    queryKey: [`${targetNetwork?.id}-${targetNetwork?.preset}`, 'Pools'],
+    queryKey: [`${targetNetwork?.id}-${targetNetwork?.preset}`, CoreProxy?.address, 'Pools'],
     queryFn: async () => {
-      if (!CoreProxy) throw 'usePools is missing required data';
+      if (!CoreProxy) {
+        throw 'usePools is missing required data';
+      }
 
       const [prefferedPoolId, approvedPoolIds] = await Promise.all([
         CoreProxy.callStatic.getPreferredPool(),
diff --git a/liquidity/ui/src/components/Pools/CollateralSection.tsx b/liquidity/ui/src/components/Pools/CollateralSection.tsx
index 1cc7d65ea..ed76ba64e 100644
--- a/liquidity/ui/src/components/Pools/CollateralSection.tsx
+++ b/liquidity/ui/src/components/Pools/CollateralSection.tsx
@@ -1,7 +1,7 @@
 import { Box, Divider, Flex, Skeleton, Text } from '@chakra-ui/react';
 import { useVaultsData, VaultsDataType } from '@snx-v3/useVaultsData';
 import React, { FC } from 'react';
-import Wei, { wei } from '@synthetixio/wei';
+import { wei } from '@synthetixio/wei';
 import { formatNumber, formatNumberToUsd, formatPercent } from '@snx-v3/formatters';
 import { useParams } from '@snx-v3/useParams';
 import { BorderBox } from '@snx-v3/BorderBox';
@@ -11,6 +11,8 @@ import { Tooltip } from '@snx-v3/Tooltip';
 import { NETWORKS } from '@snx-v3/useBlockchain';
 import { useOfflinePrices } from '@snx-v3/useCollateralPriceUpdates';
 import { usePool } from '@snx-v3/usePoolsList';
+import { formatEther } from 'ethers/lib/utils';
+import { BigNumberish } from 'ethers';
 
 export const calculateVaultTotals = (vaultsData: VaultsDataType) => {
   const zeroValues = { collateral: { value: wei(0), amount: wei(0) }, debt: wei(0) };
@@ -27,7 +29,7 @@ export const calculateVaultTotals = (vaultsData: VaultsDataType) => {
 
 export const CollateralSectionUi: FC<{
   vaultsData: VaultsDataType;
-  collateralPrices?: { symbol: string; price: Wei }[];
+  collateralPrices?: { symbol: string; price: BigNumberish }[];
   apr?: number;
   isAprLoading?: boolean;
 }> = ({ vaultsData, collateralPrices, apr, isAprLoading }) => {
@@ -108,7 +110,7 @@ export const CollateralSectionUi: FC<{
           )}
         </Flex>
       </BorderBox>
-      <Flex flexDirection="column" justifyContent="space-between">
+      <Flex py={3} flexDirection="column" justifyContent="space-between">
         {!vaultsData || !collateralPrices ? (
           <Box>
             <Skeleton mt={4} w="full" height={24} />
@@ -116,19 +118,18 @@ export const CollateralSectionUi: FC<{
           </Box>
         ) : (
           <>
-            <Divider mt={6} mb={4} />
             {vaultsData.map((vaultCollateral) => {
               const price = collateralPrices?.find(
                 (item) => item.symbol === vaultCollateral.collateralType.symbol
               )?.price;
+
               return (
                 <React.Fragment key={vaultCollateral.collateralType.tokenAddress}>
+                  <Divider my={4} />
                   <Box
                     display="flex"
                     px={4}
-                    mb={2}
                     flexDirection="column"
-                    borderBottom="1px"
                     borderColor="gray.900"
                     _last={{ borderBottom: 'none' }}
                     data-testid="pool collateral"
@@ -151,11 +152,11 @@ export const CollateralSectionUi: FC<{
                         fontWeight="400"
                         data-testid="collateral price"
                       >
-                        {price ? formatNumberToUsd(price.toNumber()) : '-'}
+                        {price ? formatNumberToUsd(formatEther(price.toString())) : '-'}
                       </Text>
                     </Flex>
                     <Flex gap={2} justifyContent="space-between">
-                      <Flex flexBasis="50%" flexDirection="column">
+                      <Flex gap={1} flexBasis="50%" flexDirection="column">
                         <Text
                           mt={2}
                           fontSize="sm"
@@ -183,7 +184,7 @@ export const CollateralSectionUi: FC<{
                           {vaultCollateral.collateralType.displaySymbol}
                         </Text>
                       </Flex>
-                      <Flex flexBasis="50%" flexDirection="column">
+                      <Flex gap={1} flexBasis="50%" flexDirection="column">
                         <Text
                           mt={2}
                           fontSize="sm"
diff --git a/liquidity/ui/src/components/Pools/PoolCards/PoolCard.tsx b/liquidity/ui/src/components/Pools/PoolCards/PoolCard.tsx
index d29351115..68b437269 100644
--- a/liquidity/ui/src/components/Pools/PoolCards/PoolCard.tsx
+++ b/liquidity/ui/src/components/Pools/PoolCards/PoolCard.tsx
@@ -89,22 +89,7 @@ export const PoolCard = ({ pool, network, collaterals, apr, collateralTypes }: P
         bg="navy.700"
         p="6"
         _hover={{ cursor: 'pointer', bg: 'whiteAlpha.50' }}
-        onClick={async () => {
-          try {
-            if (!currentNetwork) {
-              connect();
-              return;
-            }
-
-            if (currentNetwork.id !== network.id) {
-              if (!(await setNetwork(network.id))) {
-                return;
-              }
-            }
-
-            navigate(`/pools/${network.id}/${pool.id}`);
-          } catch (error) {}
-        }}
+        onClick={() => navigate(`/pools/${network.id}/${pool.id}`)}
       >
         <Flex flexWrap="wrap" justifyContent="space-between" alignItems="center" gap={4}>
           <Flex>
diff --git a/liquidity/ui/src/pages/Pool.tsx b/liquidity/ui/src/pages/Pool.tsx
index 2f76cb665..028225416 100644
--- a/liquidity/ui/src/pages/Pool.tsx
+++ b/liquidity/ui/src/pages/Pool.tsx
@@ -14,7 +14,10 @@ export const Pool = () => {
 
   const { poolInfo } = pool || {};
 
-  const registeredDistributors = poolInfo?.map((info) => info.pool.registered_distributors).flat();
+  const registeredDistributors = poolInfo
+    ?.map((info) => info.pool.registered_distributors)
+    .flat()
+    ?.filter((item, pos, self) => self.findIndex((d) => d.id === item.id) === pos);
   const collateralTypes = poolInfo?.map((info) => info.collateral_type);
 
   const network = NETWORKS.find((n) => n.id === Number(networkId));
@@ -42,7 +45,7 @@ export const Pool = () => {
         <PoolHeader name={poolInfo && poolInfo[0].pool.name} />
         <Divider my={8} bg="gray.900" />
         <Flex gap={4} flexDirection={{ base: 'column', lg: 'row' }} mb={8}>
-          <Box width="55%">
+          <Box w={['100%', '100%', '55%']}>
             <CollateralSection />
           </Box>
           <Box flexGrow={1}>
diff --git a/yarn.lock b/yarn.lock
index 0bcb1bc4e..d05277cbb 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -6221,6 +6221,7 @@ __metadata:
     "@pythnetwork/pyth-evm-js": "npm:^1.42.0"
     "@snx-v3/constants": "workspace:*"
     "@snx-v3/contracts": "workspace:*"
+    "@snx-v3/format": "workspace:*"
     "@snx-v3/isBaseAndromeda": "workspace:*"
     "@snx-v3/useBlockchain": "workspace:*"
     "@snx-v3/usePoolsList": "workspace:*"