Last active
August 12, 2022 13:03
-
-
Save zed-wong/bb21645b2fb778323be343c877c99a60 to your computer and use it in GitHub Desktop.
The procedure of getting NFT(ERC721) information from MVM with ethers.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from 'axios'; | |
import { ethers } from 'ethers'; | |
//import ERC721ABI from '../assets/erc721.json'; | |
export async function getNFTsFromExplorer(userAddr, provider){ | |
if (!userAddr) throw new Error('UserAddr is required'); | |
if (!provider) throw new Error('Provider is required'); | |
const fetchTokens = await getTokensFromExplorer(userAddr); | |
const filteredTokens = filterTokens(fetchTokens); | |
var nfts = []; | |
for (let i=0; i<filteredTokens.length; i++){ | |
console.log(filterTokens[i]) | |
const contract = new ethers.Contract(filteredTokens[i].contractAddress, ERC721ABI, provider); | |
for (let j=0; j<filteredTokens[i].balance; j++){ | |
const tokenId = await contract.tokenOfOwnerByIndex(userAddr, j); | |
const tokenURI = await contract.tokenURI(tokenId); | |
nfts.push(tokenURI); | |
} | |
} | |
return nfts; | |
} | |
async function getTokensFromExplorer(userAddr) { | |
const uri = `https://scan.mvm.dev/api?module=account&action=tokenlist&address=${userAddr}`; | |
const resp = await axios.get(uri); | |
if (resp.data.message === "OK") { | |
return resp.data.result | |
} else { | |
throw new Error(`Failed to fetch token for ${userAddr}`); | |
} | |
} | |
function filterTokens(tokens) { | |
var ERC721 = []; | |
tokens.forEach(function(element){ | |
if (element.type === 'ERC-721') { | |
ERC721.push(element); | |
} | |
}) | |
return ERC721; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment