Skip to content

Commit

Permalink
[Update] Refactor setOverrides() call and IPFS URL resolution (#4587)
Browse files Browse the repository at this point in the history
<!-- start pr-codex -->

## PR-Codex overview
The focus of this PR is to refactor the codebase to run `setOverrides()` function on app load efficiently.

### Detailed summary
- Moved `setOverrides()` function calls to run on app load in various files
- Added `useEffect` hooks to ensure `setOverrides()` runs once on app load
- Updated `replaceIpfsUrl` function to use `resolveScheme` with `thirdwebClient`
- Imported `setOverrides` function in multiple files for app initialization

> ✨ Ask PR-Codex anything about this PR by commenting with `/codex {your question}`

<!-- end pr-codex -->
  • Loading branch information
jnsdls committed Sep 14, 2024
1 parent 5abc652 commit b2a2c97
Show file tree
Hide file tree
Showing 6 changed files with 38 additions and 72 deletions.
4 changes: 4 additions & 0 deletions apps/dashboard/src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,13 @@ import PlausibleProvider from "next-plausible";
import dynamic from "next/dynamic";
import { Inter } from "next/font/google";
import NextTopLoader from "nextjs-toploader";
import { setOverrides } from "../lib/vercel-utils";
import { PostHogProvider } from "./components/root-providers";
import { AppRouterProviders } from "./providers";

// run this on app load
setOverrides();

const fontSans = Inter({
subsets: ["latin"],
variable: "--font-sans",
Expand Down
7 changes: 7 additions & 0 deletions apps/dashboard/src/app/providers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,18 @@ import { DashboardThirdwebProviderSetup } from "components/app-layouts/provider-
import { AllChainsProvider } from "contexts/all-chains";
import { ChainsProvider } from "contexts/configured-chains";
import { ThemeProvider } from "next-themes";
import { useEffect } from "react";
import { ThirdwebProvider } from "thirdweb/react";
import { setOverrides } from "../lib/vercel-utils";

const queryClient = new QueryClient();

export function AppRouterProviders(props: { children: React.ReactNode }) {
// run this ONCE on app load
// eslint-disable-next-line no-restricted-syntax
useEffect(() => {
setOverrides();
}, []);
return (
<QueryClientProvider client={queryClient}>
<AllChainsProvider>
Expand Down
11 changes: 8 additions & 3 deletions apps/dashboard/src/components/explore/contract-card/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,22 @@ import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton, SkeletonContainer } from "@/components/ui/skeleton";
import { TrackedLinkTW } from "@/components/ui/tracked-link";
import { thirdwebClient } from "@/constants/client";
import { cn } from "@/lib/utils";
import {
type QueryClient,
useQuery,
useQueryClient,
} from "@tanstack/react-query";
import { moduleToBase64 } from "app/(dashboard)/published-contract/utils/module-base-64";
import { ensQuery } from "components/contract-components/hooks";
import { getDashboardChainRpc } from "lib/rpc";
import { getThirdwebSDK, replaceIpfsUrl } from "lib/sdk";
import { getThirdwebSDK } from "lib/sdk";
import { RocketIcon, ShieldCheckIcon } from "lucide-react";
import Link from "next/link";
import { polygon } from "thirdweb/chains";
import { resolveScheme } from "thirdweb/storage";
import invariant from "tiny-invariant";
import { moduleToBase64 } from "../../../app/(dashboard)/published-contract/utils/module-base-64";
import { ContractPublisher, replaceDeployerAddress } from "../publisher";

interface ContractCardProps {
Expand Down Expand Up @@ -134,7 +136,10 @@ export const ContractCard: React.FC<ContractCardProps> = ({
<Link
target="_blank"
className="text-success-text flex items-center gap-1 text-sm z-1 hover:underline font-medium relative"
href={replaceIpfsUrl(publishedContractResult.data?.audit || "")}
href={resolveScheme({
uri: publishedContractResult.data.audit,
client: thirdwebClient,
})}
>
<ShieldCheckIcon className="size-4" />
Audited
Expand Down
77 changes: 10 additions & 67 deletions apps/dashboard/src/lib/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,77 +5,21 @@ import {
isProd,
} from "@/constants/env";
import { ThirdwebSDK } from "@thirdweb-dev/sdk";
import {
// type GatewayUrls,
type IStorageDownloader,
type SingleDownloadOptions,
StorageDownloader,
ThirdwebStorage,
} from "@thirdweb-dev/storage";
import { ThirdwebStorage } from "@thirdweb-dev/storage";
import type { Signer } from "ethers";
import { polygon } from "thirdweb/chains";
import { getAbsoluteUrl } from "./vercel-utils";
import { resolveScheme } from "thirdweb/storage";
import { thirdwebClient } from "../@/constants/client";

export function replaceIpfsUrl(url: string) {
export function replaceIpfsUrl(uri: string) {
try {
return StorageSingleton.resolveScheme(url);
return resolveScheme({
uri,
client: thirdwebClient,
});
} catch (err) {
console.error("error resolving ipfs url", url, err);
return url;
}
}

const ProxyHostNames = new Set<string>();

const defaultDownloader = new StorageDownloader({
clientId: DASHBOARD_THIRDWEB_CLIENT_ID,
secretKey: DASHBOARD_THIRDWEB_SECRET_KEY,
});

class SpecialDownloader implements IStorageDownloader {
async download(
url: string,
// gatewayUrls?: GatewayUrls,
options?: SingleDownloadOptions,
): Promise<Response> {
if (url.startsWith("ipfs://")) {
return defaultDownloader.download(
url,
{ "ipfs://": [IPFS_GATEWAY_URL] },
options,
);
}

// data urls we always want to just fetch directly
if (url.startsWith("data")) {
return fetch(url);
}

if (url.startsWith("http")) {
const u = new URL(url);

// if we already know the hostname is bad, don't even try
if (ProxyHostNames.has(u.hostname)) {
return fetch(`${getAbsoluteUrl()}/api/proxy?url=${u.toString()}`);
}

try {
// try to just fetch it directly
const res = await fetch(u);
if (await res.clone().json()) {
return res;
}
// if we hit this we know something failed and we'll try to proxy it
ProxyHostNames.add(u.hostname);

throw new Error("not ok");
} catch {
// this is a bit scary but hey, it works
return fetch(`${getAbsoluteUrl()}/api/proxy?url=${u.toString()}`);
}
}

throw new Error("not a valid url");
console.error("error resolving ipfs url", uri, err);
return uri;
}
}

Expand All @@ -88,7 +32,6 @@ export const StorageSingleton = new ThirdwebStorage({
clientId: DASHBOARD_THIRDWEB_CLIENT_ID,
secretKey: DASHBOARD_THIRDWEB_SECRET_KEY,
uploadServerUrl: DASHBOARD_STORAGE_URL,
downloader: new SpecialDownloader(),
}) as ThirdwebStorage;

// EVM SDK
Expand Down
2 changes: 0 additions & 2 deletions apps/dashboard/src/lib/vercel-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,3 @@ export function setOverrides() {
social: THIRDWEB_SOCIAL_API_DOMAIN,
});
}

setOverrides();
9 changes: 9 additions & 0 deletions apps/dashboard/src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import chakraTheme from "../theme";
import "@/styles/globals.css";
import { DashboardRouterTopProgressBar } from "@/lib/DashboardRouter";
import { AnnouncementBanner } from "../components/notices/AnnouncementBanner";
import { setOverrides } from "../lib/vercel-utils";

const inter = interConstructor({
subsets: ["latin"],
Expand Down Expand Up @@ -51,6 +52,9 @@ const chakraThemeWithFonts = {

const fontSizeCssVars = generateBreakpointTypographyCssVars();

// run this on app load
setOverrides();

type AppPropsWithLayout = AppProps<{ dehydratedState?: DehydratedState }> & {
Component: ThirdwebNextPage;
};
Expand All @@ -59,6 +63,11 @@ const ConsoleAppWrapper: React.FC<AppPropsWithLayout> = ({
Component,
pageProps,
}) => {
// run this ONCE on app load
// eslint-disable-next-line no-restricted-syntax
useEffect(() => {
setOverrides();
}, []);
const router = useRouter();
const { shouldReload } = useBuildId();

Expand Down

0 comments on commit b2a2c97

Please sign in to comment.