Skip to content

Commit

Permalink
Merge pull request #157 from NetSepio/rushikesh-nft
Browse files Browse the repository at this point in the history
add : fetch aptos nft
  • Loading branch information
Rushikeshnimkar authored Oct 15, 2024
2 parents 12bca98 + b94809c commit 1d360c0
Show file tree
Hide file tree
Showing 6 changed files with 153 additions and 111 deletions.
199 changes: 113 additions & 86 deletions components/NftdataCard.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import Link from "next/link";
// import { removePrefix } from "../utils/ipfsUtil";
import React, {useEffect} from "react";
import React, { useEffect, useState } from "react";
import axios from "axios";
import { FaPaperclip } from "react-icons/fa";
import Image from "next/image";
import Cookies from "js-cookie";

interface ReviewCardProps {
metaData: {
Expand Down Expand Up @@ -68,66 +69,72 @@ const NftdataCard: React.FC<ReviewCardProps> = ({
const [imageSrc, setImageSrc] = React.useState<string | null>(null);
const [attributes, setAttributes] = React.useState<any>(null);

// React.useEffect(() => {
// if (
// metaData &&
// metaData.current_token_data &&
// metaData.current_token_data.token_uri
// ) {
// console.log(metaData.current_token_data.token_data_id);
// fetch(metaData.current_token_data.token_uri)
// .then((response) => response.json())
// .then((jsonData: any) => {
// // Assuming there's an "image" property in the JSON containing the image URL
// const imageUrl = jsonData.image;
// setImageSrc(imageUrl);
// })
// .catch((error) => {
// console.error(
// `Error fetching token URI (${metaData.current_token_data.token_uri}): ${error}`
// );
// });
// }
// }, [metaData]);

useEffect(() => {
const fetchMetaData = async () => {
if (chainSymbol === 'sol' && metaData?.current_token_data?.token_uri) {
try {
const response = await axios.get(metaData.current_token_data.token_uri);
const metadata = response.data;
console.log("Solana Metadata:", metadata);
setImageSrc(metadata.image);
setAttributes({
name: metadata.name,
description: metadata.description,
symbol: metadata.symbol,
externalUrl: metadata.external_url,
collection: metadata.collection,
});
} catch (error) {
console.error("Error fetching Solana metadata:", error);
}
const [isLoading, setIsLoading] = useState(true);
const getUserAddressFromCookie = () => {
return Cookies.get("erebrus_wallet") || "";
};
const userAddress = getUserAddressFromCookie();
const fetchMetaData = async () => {
if (
!metaData ||
!metaData.current_token_data ||
!metaData.current_token_data.token_uri
) {
console.log("Missing metadata or token URI");
setIsLoading(false);
return;
}

try {
let metadata;
if (chainSymbol === "sol") {
const response = await axios.get(metaData.current_token_data.token_uri);
metadata = response.data;
console.log("Solana Metadata:", metadata);
} else if (chainSymbol === "apt") {
const ipfsCid = metaData.current_token_data.token_uri.replace(
"ipfs://",
""
);
console.log("IPFS CID:", ipfsCid);
const metadataResponse = await axios.get(
`https://ipfs.io/ipfs/${ipfsCid}`
);
metadata = metadataResponse.data;
console.log("Aptos Metadata:", metadata);
} else {
// Existing code for Aptos NFTs
const ipfsCid = metaData?.current_token_data?.token_uri.replace("ipfs://", "");
if (ipfsCid) {
try {
const metadataResponse = await axios.get(`https://ipfs.io/ipfs/${ipfsCid}`);
const metadata = metadataResponse.data;
console.log("Aptos Metadata:", metadata);
setImageSrc(metadata?.image.replace("ipfs://", ""));
setAttributes(metadata?.attributes);
} catch (error) {
console.error("Error fetching Aptos metadata:", error);
}
}
console.log("Unsupported chain");
setIsLoading(false);
return;
}
};

const imageUrl =
metadata?.image ||
metadata?.image_url ||
metadata?.imageUrl ||
metadata?.url;
setImageSrc(imageUrl?.replace("ipfs://", "https://ipfs.io/ipfs/"));
setAttributes({
name: metadata.name,
description: metadata.description,
symbol: metadata.symbol,
externalUrl: metadata.external_url,
collection: metadata.collection,
...metadata.attributes,
});
} catch (error) {
console.error("Error fetching metadata:", error);
} finally {
setIsLoading(false);
}
};

// Call fetchMetaData immediately if metaData is available
if (metaData && isLoading) {
fetchMetaData();
}, [metaData, chainSymbol]);
}

if (!metaData) {
if (isLoading) {
return (
<div className="flex flex-col items-center justify-center w-full max-w-sm mx-auto">
<div
Expand All @@ -140,17 +147,23 @@ const NftdataCard: React.FC<ReviewCardProps> = ({
);
}

if (!metaData) {
return null;
}

return (
<div className="w-full cursor-pointer rounded-3xl" style={{ backgroundColor:'#202333', border: '1px solid #0162FF'}}>
<div
className="w-full cursor-pointer rounded-3xl"
style={{ backgroundColor: "#202333", border: "1px solid #0162FF" }}
>
<div className="w-full h-full rounded-lg p-6 relative">
{chainSymbol === 'sol' && (
{chainSymbol === "sol" && (
<div className="absolute top-2 left-2 flex items-center">
<img
src="./solanaicon.png" // Update with the correct path to your Solana icon
alt="Solana Icon"
className="w-10 h-10 rounded-full"
/>

</div>
)}
<div>
Expand All @@ -159,53 +172,67 @@ const NftdataCard: React.FC<ReviewCardProps> = ({
<img
alt={metaData.current_token_data.token_name}
src={
chainSymbol === 'sol'
? imageSrc || metaData.current_token_data.cdn_asset_uris.cdn_image_uri
: `https://nftstorage.link/ipfs/${imageSrc}`
imageSrc ||
metaData.current_token_data.cdn_asset_uris?.cdn_image_uri
}
className="w-full h-48 object-cover rounded-lg"
onError={(e) => {
console.error(
"Image failed to load:",
(e.target as HTMLImageElement).src
);
(e.target as HTMLImageElement).src =
"/path/to/placeholder/image.png"; // Fallback image
}}
/>
</div>
<div className="w-full">
<h3 className="leading-12 mb-2 text-white">
<div className="lg:flex md:flex justify-between">
<div className="text-xl font-semibold mt-4">
{attributes?.name || metaData.current_token_data.token_name}
{attributes?.name || metaData.current_token_data.token_name}
</div>
<a
href={attributes?.externalUrl}
target="_blank"
rel="noopener noreferrer"
className="mt-5 text-white"
>
<FaPaperclip size={20} />
</a>
href={
chainSymbol === "apt"
? `https://aptoscan.com/account/${userAddress}#tokens`
: attributes?.externalUrl
}
target="_blank"
rel="noopener noreferrer"
className="mt-5 text-white"
>
<FaPaperclip size={20} />
</a>
</div>
</h3>

<div className="rounded-xl">
<div className="text-sm text-white text-start flex mt-2">
<div className="">
{attributes?.description || metaData.current_token_data.description}
{attributes?.description ||
metaData.current_token_data.description}
</div>
</div>
</div>

{attributes && chainSymbol === 'sol' && (

<div className="flex-wrap flex gap-2 text-xs text-white justify-center rounded-full px-4 py-2 mt-4" style={{backgroundColor:'#0162FF'}}>
<div>Symbol: {attributes.symbol}</div>
<div>Collection: {attributes.collection?.name}</div>
<div>Family: {attributes.collection?.family}</div>
</div>

{attributes && chainSymbol === "sol" && (
<div
className="flex-wrap flex gap-2 text-xs text-white justify-center rounded-full px-4 py-2 mt-4"
style={{ backgroundColor: "#0162FF" }}
>
<div>Symbol: {attributes.symbol}</div>
<div>Collection: {attributes.collection?.name}</div>
<div>Family: {attributes.collection?.family}</div>
</div>
)}

{attributes && chainSymbol !== 'sol' && (
<div className="flex-wrap flex gap-2 text-xs text-white rounded-full px-4 py-2 mt-4" style={{backgroundColor:'#0162FF'}}>
{Object.entries(attributes).map(([key, value]) => (
<div key={key} className="ml-4">{key}: {value.toString()}</div>
))}
{attributes && chainSymbol === "apt" && (
<div
className="flex-wrap flex gap-2 text-xs text-white rounded-full px-4 py-2 mt-4 justify-center"
style={{ backgroundColor: "#0162FF" }}
>
Access Vpn
</div>
)}
</div>
Expand All @@ -216,4 +243,4 @@ const NftdataCard: React.FC<ReviewCardProps> = ({
);
};

export default NftdataCard;
export default NftdataCard;
10 changes: 5 additions & 5 deletions components/NodesData.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ const NodesData = () => {
};

const handleSort = (key) => {
console.log("in handle sort ")
// console.log("in handle sort ")
setSortConfig((prevConfig) => {
console.log("in handle sort config ", prevConfig, sortConfig)
// console.log("in handle sort config ", prevConfig, sortConfig)
const direction = prevConfig.key === key && prevConfig.direction === "ascending"
? "descending"
: "ascending";
Expand All @@ -70,11 +70,11 @@ const NodesData = () => {
};

const handleSortChange = (value) => {
console.log("in handle sort change ");
// console.log("in handle sort change ");

if (value) {
handleSort(value);
console.log("in handle sort change done ");
// console.log("in handle sort change done ");
setSortBy(value);
setSortByDisplay(sortOptions[value]);
setTimeout(() => {
Expand Down Expand Up @@ -124,7 +124,7 @@ const NodesData = () => {
setUniqueRegionsCount(uniqueRegions.size);
}
} catch (error) {
console.error("Error fetching nodes data:", error);
// console.error("Error fetching nodes data:", error);
setNodesData([]);
setActiveNodesData([]);
setUniqueRegionsCount(0);
Expand Down
15 changes: 12 additions & 3 deletions components/UserNFTs.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { Connection, PublicKey } from '@solana/web3.js';
import { Metaplex } from '@metaplex-foundation/js';
import { AptosClient, TokenClient } from 'aptos';

const ALLOWED_NAMES = ['SMB Gen2', 'sharx by sharky.fi', 'Superteam Member NFT', 'Deanslist', 'SMB Gen3', "Erebrus Community NFT #001"];
const ALLOWED_COLLECTIONS = {
sol: ['SMB Gen2', 'sharx by sharky.fi', 'Superteam Member NFT', 'Deanslist', 'SMB Gen3', "Erebrus Community NFT #001"],
apt: ["Undying City Equipment Collection"]
};

const fetchUserNFTs = async (userAddress: string, chainSymbol: string) => {
if (!userAddress) {
Expand Down Expand Up @@ -32,7 +36,7 @@ const fetchUserNFTs = async (userAddress: string, chainSymbol: string) => {
console.log('All user NFTs:', userNFTs);

const filteredNFTs = userNFTs.filter(nft =>
ALLOWED_NAMES.includes(nft.name)
ALLOWED_COLLECTIONS.sol.includes(nft.name)
).map(nft => ({
amount: 1,
current_token_data: {
Expand All @@ -48,9 +52,14 @@ const fetchUserNFTs = async (userAddress: string, chainSymbol: string) => {
},
}));

console.log('Filtered NFTs with specified Names:', filteredNFTs);
console.log('Filtered Solana NFTs:', filteredNFTs);

return filteredNFTs;

} if (chainSymbol === 'apt') {
const client = new AptosClient(process.env.NEXT_PUBLIC_APTOS_NODE_URL);

console.log('Connected to Aptos network');
} else {
console.log('NFT fetching for this chain not implemented yet');
return [];
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"@web3modal/wagmi": "^4.1.11",
"@welldone-studio/aptos-wallet-adapter": "^0.1.5",
"antd": "^5.18.1",
"aptos": "^1.21.0",
"axios": "^1.6.5",
"blockies": "^0.0.2",
"crypto": "^1.0.1",
Expand Down
Loading

0 comments on commit 1d360c0

Please sign in to comment.