bpierre / use-nft Goto Github PK
View Code? Open in Web Editor NEW🍮 React hook to fetch metadata from any NFT.
Home Page: https://use-nft.spectre.xyz/
License: MIT License
🍮 React hook to fetch metadata from any NFT.
Home Page: https://use-nft.spectre.xyz/
License: MIT License
When trying to fetch this NFT:
https://opensea.io/assets/0x2acab3dea77832c09420663b0e1cb386031ba17b/967
it fails due to CORS:
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled
Any suggestion on how this can be solved?
That would be nice :)
See https://docs.github.com/en/actions/guides/publishing-nodejs-packages
Hello, I was rewriting my contract and came across with this issue.
useNft
seems to be requesting a uri
method which isn't present in ERC721 storage and this results in an error.
Here's the contract code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "hardhat/console.sol";
contract MyNFT is ERC721, Ownable, ERC721URIStorage {
event Mint(uint256 id);
event Claim(uint256 id);
uint256 public constant MAX_TOKENS = 50;
uint256 private constant PRICE = 50000000000000000;
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
constructor() ERC721("MyNFT", "MNFT") {}
function _burn(uint256 tokenId)
internal
override(ERC721, ERC721URIStorage)
{
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
// Mint an NFT and add URI to it
function mint(string memory tokenURI_) public onlyOwner returns (uint256) {
_tokenIds.increment();
uint256 tokenId = _tokenIds.current();
_safeMint(msg.sender, tokenId);
require(tokenId <= MAX_TOKENS, "Sold out!");
console.log(tokenId);
_setTokenURI(tokenId, tokenURI_);
return tokenId;
}
// Claim and mint NFT
function claim(uint256 id) external payable {
require(msg.value == PRICE, "Claiming an NFT costs 0.05 ETH");
require(id <= MAX_TOKENS, "Cannot claim non-existent token");
// Transfer to seller
safeTransferFrom(address(this), msg.sender, id);
emit Claim(id);
}
// withdraw bobux
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function transferTo(address acc, uint256 id) public onlyOwner {
safeTransferFrom(msg.sender, acc, id);
}
}
Dapp code:
import React, { useEffect } from 'react'
import { Contract, utils } from 'ethers'
import { useOnboard } from 'use-onboard'
import { useNft, NftProvider } from 'use-nft'
const contractAddress = 'COPY_ADDRESS_FROM_HARDHAT_DEPLOY_SCRIPT'
function NFT() {
const { loading, error, nft } = useNft(contractAddress, '1')
console.log(nft)
// nft.loading is true during load.
if (loading) return <>Loading…</>
// nft.error is an Error instance in case of error.
if (error || !nft) return <>{error.message}</>
// You can now display the NFT metadata.
return (
<section>
<h1>{nft.name}</h1>
<img src={nft.image} alt="" />
<p>{nft.description}</p>
<p>Owner: {nft.owner}</p>
<p>Metadata URL: {nft.metadataUrl}</p>
</section>
)
}
const App = () => {
const { selectWallet, address, isWalletSelected, disconnectWallet, balance, provider } = useOnboard({
options: {
networkId: 1337,
networkName: 'localhost'
}
})
return (
<div>
{
<button
onClick={async () => {
if (isWalletSelected) disconnectWallet()
else await selectWallet()
}}
>
{isWalletSelected ? 'Disconnect' : 'Connect'}
</button>
}
<p>Address: {address}</p>
<p>Balance: {balance} ETH</p>
{isWalletSelected && provider && (
<NftProvider
fetcher={[
'ethers',
{
ethers: { Contract },
provider
}
]}
>
<NFT />
</NftProvider>
)}
</div>
)
}
export default App
The error I see:
eth_call
Contract call: MyNFT#<unrecognized-selector>
From: 0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266
To: 0x2e13f7644014f6e934e314f0371585845de7b986
Error: Transaction reverted: function selector was not recognized and there's no fallback function
I came up with this function to fetch NFTs:
async function fetchNFTs(provider: Web3Provider, address: string) {
const signer = provider.getSigner()
const account = await signer.getAddress()
const contract = new Contract(contractAddress, abi, provider)
const balance = await contract.balanceOf(account)
console.log(balance.toNumber())
const data = []
for (let i = 0; i < balance.toNumber(); ++i) {
let tokenURI = await contract.tokenURI(1)
data.push(tokenURI)
}
return data
}
When using OpenSea Polygon Minting Contract 0x2953399124F0cBB46d2CbACD8A89cF0599974963
, no NFT image is found.
For example, this NFT on open sea:
https://opensea.io/assets/matic/0x2953399124f0cbb46d2cbacd8a89cf0599974963/104266429279353206028968205808007262092071789057064791600420254975229853433857
is using smart contract 0x2953399124F0cBB46d2CbACD8A89cF0599974963
and token 104266429279353206028968205808007262092071789057064791600420254975229853433857
yet, useNFT is unable to find the image
Open to offers
https://dan.com/buy-domain/reactnft.com
This field would contain the address of the current owner.
See ownerOf(uint256 _tokenId)
: https://eips.ethereum.org/EIPS/eip-721
Peer dependencies can be declared as optional by using the peerDependenciesMeta
field (supported by Yarn).
Having Ethers as an optional peer dependency and importing it dynamically (through import()
) could remove the need for app authors to inject it themselves and simplify configuration.
See #46 (comment)
Example implementations:
There is no standard for audio in NFT, but we could start by supporting EulerBeats which is using audio_url
.
I was able to use this library to pull a token using the contract address + the tokenId.
What I want to know now is to only fetch the TokenIds that belong for a given user (by connecting his Metamask wallet) and fetching that information from it.
I tried to look for example but could not find any.
Is this something possible using this library?
Thank you!
Hi there,
I am having some issues importing use-nft. Here is the error I get:
Compiled with problems:
ERROR in ./node_modules/use-nft/dist/index.js 5678:53-60
Module not found: Error: Can't resolve 'process/browser' in '/path/node_modules/use-nft/dist'
Did you mean 'browser.js'?
BREAKING CHANGE: The request 'process/browser' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.
I am using:
The app was created using React-Create-App.
Has anyone got the same error and found a solution? Thanks.
Try to get image data from NFT URI, eg: eip155:1/erc721:0xa3b7cee4e082183e69a03fc03476f28b12c545a7/5566
. There is an issue for Brave browser and in a case with Chrome everything is ok. I try to get data using useNf()
hook and fetchNft()
function with the same result.
Could you please add Brave browser supporting to your lib?
bro like use cors wtf
It could be nice to rely on the URL and provide a hint about the image type (e.g. we could have "image"
, "video"
and "unknown"
), instead of letting app authors do it themselves (example).
Attempting to use this module with NextJS results in the following message being displayed.
ReferenceError: exports is not defined in ES module scope This file is being treated as an ES module because it has a '.js' file extension and '/Users/naj/code/project/node_modules/use-nft/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
This happens both when using it with the useNFT hook and using FetchWrapper
This is using NextJS 12.1.5 with React 18.1.0
Error: node_modules/use-nft/dist/core.d.ts:6:5 - error TS2503: Cannot find namespace 'JSX'.
6 }): JSX.Element;
~~~
Somehow the @types/react
dependency is lost when installing the package. This seems to be the same issue.
It can be solved by installing @types/react
manually in the project.
Hi,
Great job, thank you!
I am trying to use the fetcher without react and got the following error:
./node_modules/swr/dist/index.esm.jsModule not found: Error: Can't resolve 'react' in '/Users/gen4/Gits/BigDay/STD-visual/node_modules/swr/dist'./node_modules/use-nft/dist/use-nft.jsModule not found: Error: Can't resolve 'react' in '/Users/gen4/Gits/BigDay/STD-visual/node_modules/use-nft/dist'
this is a code
import { FetchWrapper } from "use-nft"
import ethers from 'ethers';
const fetcher = ["ethers", { provider: ethers.getDefaultProvider() }]
const fetchWrapper = new FetchWrapper(fetcher)
async function fetchMetadata(collId, artId){
const result = await fetchWrapper.fetchNft(
collId,
artId
)
return result;
}
export default fetchMetadata;
Do I HAVE to use React even using only fecher?
See #80 (comment)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.