Skip to content

Commit

Permalink
feat: useNft hook with onwer info
Browse files Browse the repository at this point in the history
  • Loading branch information
marcomariscal committed Aug 10, 2023
1 parent 5c8eac6 commit 2ec5685
Show file tree
Hide file tree
Showing 3 changed files with 110 additions and 55 deletions.
21 changes: 13 additions & 8 deletions src/components/experimental_/widgets/nft/BuyNft.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import axios from 'axios';
import { BigNumber, BigNumberish, ethers } from 'ethers';
// @ts-ignore TODO: fix this
import * as JSONbigint from 'json-bigint';
import { useAccount } from 'wagmi';
import { Address, useAccount } from 'wagmi';
import SeaportAbi from '@/abi/SeaportAbi.json';
import { NftOwner } from '@/components/CheckNftOwner';
import { ActionResponse, HeaderResponse } from '@/components/cactiComponents';
import { ImageVariant } from '@/components/cactiComponents/ImageResponse';
import { TxBasicParams } from '@/components/cactiComponents/hooks/useSubmitTx';
import useNft from '@/hooks/useNft';
import { Order } from '@/types';
import { ConnectFirst } from '../helpers/ConnectFirst';
import { NftAsset } from './NftAsset';
Expand Down Expand Up @@ -62,8 +62,13 @@ const fetchFulfillParams = async (
export const BuyNft = ({ nftAddress, tokenId }: { nftAddress: string; tokenId: string }) => {
// // The new owner will be the receiver
const { address: account } = useAccount();
//const addRecentTransaction = useAddRecentTransaction();
// const { refetch: refetchBal } = useBalance();
const {
data: { isOwner },
} = useNft({
address: nftAddress as Address,
tokenId: +tokenId,
network: 'ethereum-mainnet',
});

// fetchListing possible states:
// If order array is empty, show the NFT is not currently for sale
Expand Down Expand Up @@ -127,8 +132,8 @@ export const BuyNft = ({ nftAddress, tokenId }: { nftAddress: string; tokenId: s
<ConnectFirst>
<HeaderResponse text={`Buy NFT`} projectName={'Opensea Seaport'} />
<NftAsset
address={nftAddress}
tokenId={tokenId}
address={nftAddress as Address}
tokenId={+tokenId}
network="ethereum-mainnet"
variant={ImageVariant.SHOWCASE}
price={
Expand All @@ -138,8 +143,8 @@ export const BuyNft = ({ nftAddress, tokenId }: { nftAddress: string; tokenId: s
<ActionResponse
txParams={tx}
approvalParams={undefined}
label={notForSale ? 'Item not for sale' : 'Purchase NFT'}
disabled={isExpired || notForSale}
label={isOwner ? 'Already Owner' : notForSale ? 'Item not for sale' : 'Purchase NFT'}
disabled={isExpired || notForSale || isOwner}
/>
</ConnectFirst>
);
Expand Down
58 changes: 11 additions & 47 deletions src/components/experimental_/widgets/nft/NftAsset.tsx
Original file line number Diff line number Diff line change
@@ -1,46 +1,21 @@
import { useQuery } from 'react-query';
import { useAsset } from '@center-inc/react';
import axios from 'axios';
import { Network } from '@center-inc/react';
import { Address } from 'wagmi';
import { ImageResponse } from '@/components/cactiComponents';
import { ImageVariant } from '@/components/cactiComponents/ImageResponse';
import { InlineChip } from '@/components/cactiComponents/InlineChip';
import { ETHEREUM_NETWORK } from '@/utils/constants';
import useNft from '@/hooks/useNft';

export interface NftAssetProps {
network: string;
address: string;
tokenId: string | number;
network: Network;
address: Address;
tokenId: number;
collectionName?: string;
name?: string;
previewImageUrl?: string;

variant?: ImageVariant; // widget variant

price?: string;
}

const fetchNftAsset = async (
nftAddress: string,
tokenId: string,
network: string = ETHEREUM_NETWORK
) => {
return axios
.get(`https://api.center.dev/v1/${network}/${nftAddress}/${tokenId}`, {
// .get(`https://api.center.app/v2/${network}/${nftAddress}/nft/${tokenId}/metadata`,{
headers: {
Accept: 'application/json',
'X-API-Key': process.env.NEXT_PUBLIC_CENTER_APP_KEY || 'test',
},
})
.then((res) => {
console.log(res.data);
return res.data;
})
.catch((err) => {
console.log(err);
});
};

export const NftAsset = ({
network,
address,
Expand All @@ -51,34 +26,23 @@ export const NftAsset = ({
variant,
price,
}: NftAssetProps) => {
const {
data: nftData,
error,
isLoading,
} = useQuery(
['NftAsset', address, tokenId],
async () => fetchNftAsset(address, tokenId.toString(), network),
{
enabled: true,
}
);
const { data: nftData } = useNft({ network, address, tokenId });

return (
<ImageResponse
description={nftData?.description}
image={nftData?.smallPreviewImageUrl || previewImageUrl}
image={nftData.smallPreviewImageUrl || previewImageUrl}
imageTags={
variant === ImageVariant.SHOWCASE
? [`Token Id: ${tokenId}`, `${network.replace('-mainnet', '')}`]
: []
}
title={nftData?.name || name}
subTitle={nftData?.collection?.name || nftData?.collectionName || collectionName}
title={nftData.name || name}
subTitle={nftData.collectionName || collectionName}
imageLink={`https://center.app/${network}/collections/${address}/${tokenId}`}
variant={variant}
>
{variant === ImageVariant.SHOWCASE && (
<div className="text-xs">{nftData?.metadata?.description}</div>
<div className="text-xs">{nftData.metadata?.description}</div>
)}
{price && (
<InlineChip
Expand Down
86 changes: 86 additions & 0 deletions src/hooks/useNft.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { useQuery } from 'react-query';
import { Network } from '@center-inc/react';
import axios from 'axios';
import { BigNumber } from 'ethers';
import { Address, erc721ABI, useAccount } from 'wagmi';
import { readContract } from 'wagmi/actions';
import { ETHEREUM_NETWORK } from '@/utils/constants';

interface NftRes {
address: string;
collectionName: string;
collection_name: string;
mediumPreviewImageUrl: string;
metadata: {
attributes: {
trait_type: string;
value: string;
}[];
description: string;
image: string;
name: string;
tokenId: number;
};
name: string;
smallPreviewImageUrl: string;
small_preview_image_url: string;
tokenId: string;
token_id: string;
url: string;
owner?: Address;
isOwner?: boolean;
}

const useNft = ({
address,
tokenId,
network,
}: {
address: Address;
tokenId: number;
network: Network;
}) => {
const { address: account } = useAccount();
const fetchNft = async (
nftAddress: string,
tokenId: number,
network: string = ETHEREUM_NETWORK
) => {
const { data } = await axios.get<NftRes>(
`https://api.center.dev/v1/${network}/${nftAddress}/${tokenId}`,
{
headers: {
Accept: 'application/json',
'X-API-Key': process.env.NEXT_PUBLIC_CENTER_APP_KEY || 'test',
},
}
);
return data;
};

const { data: centerData, ...rest } = useQuery({
queryKey: ['nft', address, tokenId, network],
queryFn: async () => await fetchNft(address, tokenId, network),
});

const { data: owner } = useQuery({
queryKey: ['nftOwner', address, tokenId, network],
queryFn: async () =>
await readContract({
address,
abi: erc721ABI,
functionName: 'ownerOf',
args: [BigNumber.from(tokenId)],
}),
refetchOnWindowFocus: false,
});

const data = { ...centerData, owner, isOwner: owner === account };

return {
data,
...rest,
};
};

export default useNft;

0 comments on commit 2ec5685

Please sign in to comment.