Use SWR for Sourcify metadata fetching

This commit is contained in:
Willian Mitsuda 2022-08-09 19:23:38 -03:00
parent 50ac6f7a3e
commit 0b210fd446
No known key found for this signature in database
3 changed files with 22 additions and 30 deletions

View File

@ -11,7 +11,10 @@ import { SelectionContext, useSelection } from "./useSelection";
import { SelectedTransactionContext } from "./useSelectedTransaction";
import { BlockNumberContext } from "./useBlockTagContext";
import { useAppConfigContext } from "./useAppConfig";
import { useSourcify, useTransactionDescription } from "./sourcify/useSourcify";
import {
useSourcifyMetadata,
useTransactionDescription,
} from "./sourcify/useSourcify";
const Details = React.lazy(() => import("./transaction/Details"));
const Logs = React.lazy(() => import("./transaction/Logs"));
@ -44,7 +47,7 @@ const TransactionPageContent: React.FC<TransactionPageContentProps> = ({
const selectionCtx = useSelection();
const { sourcifySource } = useAppConfigContext();
const metadata = useSourcify(
const metadata = useSourcifyMetadata(
txData?.to,
provider?.network.chainId,
sourcifySource

View File

@ -1,6 +1,7 @@
import { useState, useEffect, useMemo } from "react";
import { Interface } from "@ethersproject/abi";
import { ErrorDescription } from "@ethersproject/abi/lib/interface";
import useSWRImmutable from "swr/immutable";
import { ChecksummedAddress, TransactionData } from "../types";
import { sourcifyMetadata, SourcifySource, sourcifySourceFile } from "../url";
@ -102,38 +103,22 @@ const fetchSourcifyMetadata = async (
}
};
// TODO: replace every occurrence with the multiple version one
export const useSourcify = (
export const useSourcifyMetadata = (
address: ChecksummedAddress | undefined,
chainId: number | undefined,
source: SourcifySource
): Metadata | null | undefined => {
const [rawMetadata, setRawMetadata] = useState<Metadata | null | undefined>();
useEffect(() => {
if (!address || chainId === undefined) {
return;
}
setRawMetadata(undefined);
const abortController = new AbortController();
const fetchMetadata = async () => {
const _metadata = await fetchSourcifyMetadata(
address,
chainId,
source,
abortController
);
setRawMetadata(_metadata);
};
fetchMetadata();
return () => {
abortController.abort();
};
}, [address, chainId, source]);
return rawMetadata;
const metadataURL = () =>
address === undefined || chainId === undefined
? null
: sourcifyMetadata(address, chainId, source);
const { data, error } = useSWRImmutable<Metadata>(metadataURL, (url) =>
fetch(url).then((res) => res.json())
);
if (error) {
return null;
}
return data;
};
export const useMultipleMetadata = (

View File

@ -53,6 +53,10 @@ const resolveSourcifySource = (source: SourcifySource) => {
throw new Error(`Unknown Sourcify integration source code: ${source}`);
};
/**
* Builds a complete Sourcify metadata.json URL given the contract address
* and chain.
*/
export const sourcifyMetadata = (
address: ChecksummedAddress,
chainId: number,