Skip to content

Commit

Permalink
resolve ens name using route handler
Browse files Browse the repository at this point in the history
  • Loading branch information
MattPereira committed Jan 18, 2024
1 parent ba3a798 commit 1bd3e04
Show file tree
Hide file tree
Showing 4 changed files with 107 additions and 46 deletions.
2 changes: 1 addition & 1 deletion packages/nextjs/components/MetaHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const baseUrl = process.env.NEXT_PUBLIC_VERCEL_URL ? `https://${process.env.NEXT

export const MetaHeader = ({
title = "Only Buidlors",
description = "An NFT collection for BuidlGuidl members that have shipped at least one build",
description = "A dynamic SVG NFT collection for the BuidlGuidl",
image = "thumbnail.jpg",
twitterCard = "summary_large_image",
children,
Expand Down
44 changes: 44 additions & 0 deletions packages/nextjs/pages/api/get-ens-name.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import axios from "axios";
import type { NextApiRequest, NextApiResponse } from "next";

const ensContractAddress = "0xD4416b13d2b3a9aBae7AcD5D6C2BbDBE25686401";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
console.log("hello");
const { eoaAddress } = req.query;
// Base URL
const response = await axios.get(
`https://eth-mainnet.g.alchemy.com/nft/v3/${process.env.ALCHEMY_API_KEY}/getNFTsForOwner`,
{
params: {
owner: eoaAddress,
"contractAddresses[]": ensContractAddress,
withMetadata: true,
},
},
);
console.log("response", response);

const data = response.data;
let tokenUri;
let ensName;
if (data.ownedNfts.length > 0) {
tokenUri = data.ownedNfts[0].tokenUri;
const response2 = await axios.get(tokenUri);
ensName = response2.data.name;
}

if (ensName) {
res.status(200).json({ name: ensName });
} else {
res.status(200).json({ message: "No ENS name found for the provided EOA address." });
}
} catch (error) {
// Log the error for server-side debugging
console.error("Failed to fetch NFT data for owner:", error);

// Send a generic error response to the client
res.status(500).json({ error: "Failed to fetch NFT data for owner" });
}
}
105 changes: 61 additions & 44 deletions packages/nextjs/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,32 +55,7 @@ const Home: NextPage = () => {

const { address } = useAccount();

const {
writeAsync: sendRequest,
isLoading: requestTxIsLoading,
isMining: requestTxIsMining,
} = useScaffoldContractWrite({
contractName: "OnlyBuidlorsNft",
functionName: "sendRequest",
args: [SUBSCRIPTION_ID, [address || ""], "matthu.eth"],
// blockConfirmations: 1,
onBlockConfirmation: () => {
setStepsCompleted(1);
},
});

const {
writeAsync: mintNft,
// isLoading: mintIsLoading,
// isMining: mintIsMining,
} = useScaffoldContractWrite({
contractName: "OnlyBuidlorsNft",
functionName: "mintNft",
onBlockConfirmation: () => {
setStepsCompleted(3);
},
});

/*** Read Contract ***/
const { data: buidlCount } = useScaffoldContractRead({
contractName: "OnlyBuidlorsNft",
functionName: "getBuidlCount",
Expand All @@ -93,9 +68,40 @@ const Home: NextPage = () => {
args: [address || "0x000"],
});

const { data: onlyBuildorsNftContract } = useDeployedContractInfo("OnlyBuidlorsNft");
/*** API requests ***/

// BuidlGuidl API Request
// only make the request if the eoa and contract address are defined AND the user has minted an NFT
const bgBuildersUrl = address ? `https://buidlguidl-v3.appspot.com/builders/${address}` : null;

const { data: isBuilder, error: isBuilderError } = useSWR(bgBuildersUrl, fetcher, {
shouldRetryOnError: false, // Do not retry on error
onError: error => {
if (error.status === 404) {
// Handle the 404 error specifically
console.error("Builder ddress not found in database:", error.info);
}
},
});

if (isBuilderError) {
console.log("isBuilderError", isBuilderError);
}

// ENS NFT Request to Alchemy API
const ensLookupUrl = address && isBuilder ? `/api/get-ens-name?eoaAddress=${address}` : null;

const { data: ensData, error: ensNameError } = useSWR(ensLookupUrl, fetcher);

if (ensNameError) {
console.log("ensNameError", ensNameError);
}
console.log("ensName", ensData?.name);

const { data: onlyBuildorsNftContract } = useDeployedContractInfo("OnlyBuidlorsNft");

// Only Buider NFT Contract Request to Alchemy API
// Only make the request if the eoa and contract address are defined AND the user has minted an NFT
const getNftForOwnerUrl =
address && onlyBuildorsNftContract?.address && hasMinted
? `/api/get-nft-for-owner?eoaAddress=${address}&nftContract=${onlyBuildorsNftContract?.address}`
Expand All @@ -107,6 +113,34 @@ const Home: NextPage = () => {
console.log("nftError", nftError);
}

/*** Write Contract ***/

const {
writeAsync: sendRequest,
isLoading: requestTxIsLoading,
isMining: requestTxIsMining,
} = useScaffoldContractWrite({
contractName: "OnlyBuidlorsNft",
functionName: "sendRequest",
args: [SUBSCRIPTION_ID, [address || "0x000"], ensData?.name || ""],
// blockConfirmations: 1,
onBlockConfirmation: () => {
setStepsCompleted(1);
},
});

const {
writeAsync: mintNft,
// isLoading: mintIsLoading,
// isMining: mintIsMining,
} = useScaffoldContractWrite({
contractName: "OnlyBuidlorsNft",
functionName: "mintNft",
onBlockConfirmation: () => {
setStepsCompleted(3);
},
});

// only change the image source if the nftData has been successfully fetched
useEffect(() => {
if (nftData) {
Expand Down Expand Up @@ -138,23 +172,6 @@ const Home: NextPage = () => {
}
}, [hasMinted, buidlCount, requestTxIsMining, requestTxIsLoading, stepsCompleted]);

// only make the request if the eoa and contract address are defined AND the user has minted an NFT
const bgBuildersUrl = address ? `https://buidlguidl-v3.appspot.com/builders/${address}` : null;

const { data: isBuilder, error: isBuilderError } = useSWR(bgBuildersUrl, fetcher, {
shouldRetryOnError: false, // Do not retry on error
onError: error => {
if (error.status === 404) {
// Handle the 404 error specifically
console.error("Builder ddress not found in database:", error.info);
}
},
});

if (isBuilderError) {
console.log("isBuilderError", isBuilderError);
}

return (
<>
<MetaHeader />
Expand Down
2 changes: 1 addition & 1 deletion packages/nextjs/utils/scaffold-eth/notification.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const Notification = ({
return toast.custom(
t => (
<div
className={`flex flex-row items-start justify-between max-w-sm rounded-xl shadow-center shadow-accent bg-base-200 p-4 transform-gpu relative transition-all duration-500 ease-in-out space-x-2
className={`flex flex-row items-start justify-between max-w-sm rounded-xl shadow-center shadow-accent bg-primary text-primary-content p-4 transform-gpu relative transition-all duration-500 ease-in-out space-x-2
${
position.substring(0, 3) == "top"
? `hover:translate-y-1 ${t.visible ? "top-0" : "-top-96"}`
Expand Down

0 comments on commit 1bd3e04

Please sign in to comment.