Skip to content

Commit

Permalink
fix: make async getAssetImageURL
Browse files Browse the repository at this point in the history
  • Loading branch information
sahar-fehri committed Sep 9, 2024
1 parent 8605106 commit e1b952e
Show file tree
Hide file tree
Showing 11 changed files with 267 additions and 60 deletions.
6 changes: 6 additions & 0 deletions app/scripts/metamask-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,12 @@ export default class MetamaskController extends EventEmitter {
`${this.networkController.name}:getNetworkClientById`,
'AccountsController:getSelectedAccount',
'AccountsController:getAccount',
'AssetsContractController:getERC721AssetName',
'AssetsContractController:getERC721AssetSymbol',
'AssetsContractController:getERC721TokenURI',
'AssetsContractController:getERC721OwnerOf',
'AssetsContractController:getERC1155BalanceOf',
'AssetsContractController:getERC1155TokenURI',
],
});
this.nftController = new NftController({
Expand Down
17 changes: 15 additions & 2 deletions ui/components/app/assets/nfts/nft-details/nft-details.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useContext } from 'react';
import React, { useEffect, useContext, useState } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory } from 'react-router-dom';
Expand Down Expand Up @@ -105,12 +105,12 @@ export default function NftDetails({ nft }: { nft: Nft }) {
const trackEvent = useContext(MetaMetricsContext);
const currency = useSelector(getCurrentCurrency);
const selectedNativeConversionRate = useSelector(getConversionRate);
const [nftImageURL, setAssetImageUrl] = useState<string>('');

const [addressCopied, handleAddressCopy] = useCopyToClipboard();

const nftImageAlt = getNftImageAlt(nft);
const nftSrcUrl = imageOriginal ?? image;
const nftImageURL = getAssetImageURL(imageOriginal ?? image, ipfsGateway);
const isIpfsURL = nftSrcUrl?.startsWith('ipfs:');
const isImageHosted = image?.startsWith('https:');

Expand Down Expand Up @@ -165,6 +165,19 @@ export default function NftDetails({ nft }: { nft: Nft }) {
};

const { chainId } = currentChain;

useEffect(() => {
const getAssetImageUrl = async () => {
const assetImageUrl = await getAssetImageURL(
imageOriginal ?? image,
ipfsGateway,
);
setAssetImageUrl(assetImageUrl);
};

getAssetImageUrl();
}, []);

useEffect(() => {
trackEvent({
event: MetaMetricsEventName.NftDetailsOpened,
Expand Down
14 changes: 13 additions & 1 deletion ui/components/app/assets/nfts/nft-details/nft-full-image.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,28 @@ export default function NftFullImage() {

const ipfsGateway = useSelector(getIpfsGateway);
const currentChain = useSelector(getCurrentNetwork);
const [nftImageURL, setAssetImageUrl] = useState<string>('');

const nftImageAlt = getNftImageAlt(nft);
const nftSrcUrl = imageOriginal ?? image;
const nftImageURL = getAssetImageURL(imageOriginal ?? image, ipfsGateway);
const isIpfsURL = nftSrcUrl?.startsWith('ipfs:');
const isImageHosted = image?.startsWith('https:');
const history = useHistory();

const [visible, setVisible] = useState(false);

useEffect(() => {
const getAssetImageUrl = async () => {
const assetImageUrl = await getAssetImageURL(
imageOriginal ?? image,
ipfsGateway,
);
setAssetImageUrl(assetImageUrl);
};

getAssetImageUrl();
}, []);

useEffect(() => {
setVisible(true);
}, []);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import React, { useEffect, useState } from 'react';

import { useSelector } from 'react-redux';

import Box from '../../../../ui/box';

import { getIpfsGateway, getOpenSeaEnabled } from '../../../../../selectors';
import { getAssetImageURL } from '../../../../../helpers/utils/util';

export const CollectionImageComponent = ({
collectionImage,
collectionName,
}: {
collectionImage: string;
collectionName: string;
}) => {
const ipfsGateway = useSelector(getIpfsGateway);
const openSeaEnabled = useSelector(getOpenSeaEnabled);
const [nftImageURL, setAssetImageUrl] = useState<string>('');

useEffect(() => {
const getAssetImageUrl = async () => {
const assetImageUrl = await getAssetImageURL(
collectionImage,
ipfsGateway,
);
setAssetImageUrl(assetImageUrl);
};

getAssetImageUrl();
}, []);

const renderCollectionImage = () => {
if (collectionImage?.startsWith('ipfs') && !ipfsGateway) {
return (
<div className="nfts-items__collection-image-alt">
{collectionName?.[0]?.toUpperCase() ?? null}
</div>
);
}
if (!openSeaEnabled && !collectionImage?.startsWith('ipfs')) {
return (
<div className="nfts-items__collection-image-alt">
{collectionName?.[0]?.toUpperCase() ?? null}
</div>
);
}

if (collectionImage) {
return (
<img
alt={collectionName}
src={nftImageURL}
className="nfts-items__collection-image"
/>
);
}
return (
<div className="nfts-items__collection-image-alt">
{collectionName?.[0]?.toUpperCase() ?? null}
</div>
);
};

return <Box>{renderCollectionImage()}</Box>;
};
100 changes: 56 additions & 44 deletions ui/components/app/assets/nfts/nfts-items/nfts-items.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useContext, useEffect } from 'react';
import React, { useContext, useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory } from 'react-router-dom';
Expand All @@ -22,7 +22,6 @@ import {
getIpfsGateway,
getSelectedInternalAccount,
getCurrentNetwork,
getOpenSeaEnabled,
} from '../../../../../selectors';
import {
ASSET_ROUTE,
Expand All @@ -46,6 +45,8 @@ import {
MetaMetricsEventCategory,
MetaMetricsEventName,
} from '../../../../../../shared/constants/metametrics';
import { isEqualCaseInsensitive } from '../../../../../../shared/modules/string-utils';
import { CollectionImageComponent } from './collection-image.component';

const width = (isModal) => {
const env = getEnvironmentType() === ENVIRONMENT_TYPE_POPUP;
Expand Down Expand Up @@ -78,7 +79,8 @@ export default function NftsItems({
const currentChain = useSelector(getCurrentNetwork);
const t = useI18nContext();
const ipfsGateway = useSelector(getIpfsGateway);
const openSeaEnabled = useSelector(getOpenSeaEnabled);

const [updatedNfts, setUpdatedNfts] = useState([]);

const trackEvent = useContext(MetaMetricsContext);
const sendAnalytics = useSelector(getSendAnalyticProperties);
Expand Down Expand Up @@ -116,39 +118,39 @@ export default function NftsItems({
dispatch,
]);

const history = useHistory();
const getAssetImageUrlAndUpdate = async (image, nft) => {
const nftImage = await getAssetImageURL(image, ipfsGateway);
const updatedNFt = {
...nft,
ipfsImageUpdated: nftImage,
};
return updatedNFt;
};

const renderCollectionImage = (collectionImage, collectionName) => {
if (collectionImage?.startsWith('ipfs') && !ipfsGateway) {
return (
<div className="nfts-items__collection-image-alt">
{collectionName?.[0]?.toUpperCase() ?? null}
</div>
);
}
if (!openSeaEnabled && !collectionImage?.startsWith('ipfs')) {
return (
<div className="nfts-items__collection-image-alt">
{collectionName?.[0]?.toUpperCase() ?? null}
</div>
);
}
useEffect(() => {
const promisesArr = [];
const modifyItems = async () => {
for (const key of collectionsKeys) {
const { nfts } = collections[key];
for (const singleNft of nfts) {
const { image, imageOriginal } = singleNft;

if (collectionImage) {
return (
<img
alt={collectionName}
src={getAssetImageURL(collectionImage, ipfsGateway)}
className="nfts-items__collection-image"
/>
);
}
return (
<div className="nfts-items__collection-image-alt">
{collectionName?.[0]?.toUpperCase() ?? null}
</div>
);
};
const isImageHosted = image?.startsWith('https:');
if (!isImageHosted) {
promisesArr.push(
getAssetImageUrlAndUpdate(imageOriginal ?? image, singleNft),
);
}
}
}
const settled = await Promise.all(promisesArr);
setUpdatedNfts(settled);
};

modifyItems();
}, []);

const history = useHistory();

const updateNftDropDownStateKey = (key, isExpanded) => {
const newCurrentAccountState = {
Expand Down Expand Up @@ -220,7 +222,10 @@ export default function NftsItems({
alignItems={AlignItems.center}
className="nfts-items__collection-header"
>
{renderCollectionImage(collectionImage, collectionName)}
<CollectionImageComponent
collectionImage={collectionImage}
collectionName={collectionName}
/>
<Typography
color={Color.textDefault}
variant={TypographyVariant.H5}
Expand All @@ -243,15 +248,23 @@ export default function NftsItems({
{nfts.map((nft, i) => {
const { image, address, tokenId, name, imageOriginal, tokenURI } =
nft;
const nftImage = getAssetImageURL(
imageOriginal ?? image,
ipfsGateway,
);
const nftImageAlt = getNftImageAlt(nft);
const isImageHosted = image?.startsWith('https:');
const nftImageURL = imageOriginal?.startsWith('ipfs')
? nftImage
: image;

const getSource = () => {
if (!isImageHosted) {
const found = updatedNfts.find(
(elm) =>
elm.tokenId === nft.tokenId &&
isEqualCaseInsensitive(elm.address, nft.address),
);
if (found) {
return found.ipfsImageUpdated;
}
}
return image;
};

const isIpfsURL = (
imageOriginal ??
image ??
Expand All @@ -271,9 +284,8 @@ export default function NftsItems({
className="nfts-items__item-wrapper"
>
<NftItem
nftImageURL={nftImageURL}
alt={nftImageAlt}
src={isImageHosted ? image : nftImage}
src={getSource()}
name={name}
tokenId={tokenId}
networkName={currentChain.nickname}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ export const AssetPickerAmount = ({

const [isFocused, setIsFocused] = useState(false);
const [isNFTInputChanged, setIsTokenInputChanged] = useState(false);
const [nftImageURL, setAssetImageUrl] = useState<string>('');

const handleChange = useCallback(
(newAmountRaw, newAmountFormatted) => {
Expand Down Expand Up @@ -140,6 +141,18 @@ export const AssetPickerAmount = ({
}
}, [selectedAccount]);

useEffect(() => {
const getAssetImageUrl = async () => {
const assetImageUrl = await getAssetImageURL(
asset?.details?.image,
ipfsGateway,
);
setAssetImageUrl(assetImageUrl);
};

getAssetImageUrl();
}, []);

let borderColor = BorderColor.borderMuted;

if (isDisabled) {
Expand Down Expand Up @@ -168,7 +181,7 @@ export const AssetPickerAmount = ({
standardizedAsset = {
type: asset.type,
image:
getAssetImageURL(asset.details.image, ipfsGateway) ||
nftImageURL ||
(tokenList &&
asset.details?.address &&
tokenList[asset.details.address.toLowerCase()]?.iconUrl),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import React, {
useCallback,
useEffect,
///: BEGIN:ONLY_INCLUDE_IF(build-main,build-beta,build-flask)
useMemo,
///: END:ONLY_INCLUDE_IF
useRef,
useState,
} from 'react';
import { useDispatch, useSelector } from 'react-redux';
///: BEGIN:ONLY_INCLUDE_IF(build-main,build-beta,build-flask)
Expand Down Expand Up @@ -103,6 +105,7 @@ export const SendPageRecipientContent = ({
///: END:ONLY_INCLUDE_IF

const bestQuote: Quote = useSelector(getBestQuote);
const [nftImageURL, setAssetImageUrl] = useState<string>('');

const isLoadingInitialQuotes = !bestQuote && isSwapQuoteLoading;

Expand Down Expand Up @@ -130,6 +133,18 @@ export const SendPageRecipientContent = ({
// Gas data
const dispatch = useDispatch();

useEffect(() => {
const getAssetImageUrl = async () => {
const assetImageUrl = await getAssetImageURL(
sendAsset.details?.image,
ipfsGateway,
);
setAssetImageUrl(assetImageUrl);
};

getAssetImageUrl();
}, []);

return (
<Box>
{requireContractAddressAcknowledgement ? (
Expand Down Expand Up @@ -169,7 +184,7 @@ export const SendPageRecipientContent = ({
? nativeCurrencyImageUrl
: tokenList &&
sendAsset.details &&
(getAssetImageURL(sendAsset.details?.image, ipfsGateway) ||
(nftImageURL ||
tokenList[sendAsset.details.address?.toLowerCase()]
?.iconUrl),
symbol: sendAsset?.details?.symbol || nativeCurrencySymbol,
Expand Down
Loading

0 comments on commit e1b952e

Please sign in to comment.