I am developing a React NFT marketplace on Polygon where a user can create, buy and relist an NFT. The issue is I am unable to connect to Metamask/web3provider for the second time after successfully executing first time buy. Error on console is
-32603: Error: Transaction reverted: function call failed to execute"
The snapshot of the error is attached below.
My preliminary understanding is that the problem is arising from "buyNft" function that gets triggered after clicking "buy" button.
async function buyNft(nft) {
// console.log("I was able to hit buyNFT")
const web3Modal = new Web3Modal()
const connection = await web3Modal.connect()
const provider = new ethers.providers.Web3Provider(connection)
// console.log("web3 provider", provider) // There is no change in this output in both successful and failed buy transaction.
const signer = provider.getSigner()
const contract = new ethers.Contract(nftmarketaddress, Market.abi, signer)
const price = ethers.utils.parseUnits(nft.price.toString(), 'ether')
const transaction = await contract.createMarketSale(nftaddress, nft.tokenId, {
value: price
})
await transaction.wait()
loadNFTs()
history.push('/myassets')
}
The nft I am passing as argument to buyNft() function is an object and it looks like this
{
description: "Using Dev 1 Account"
image: "https://ipfs.infura.io/ipfs/QmUksTHetYR6if3yeTx6ckLoqDCgnFdjwVNHGiiideMw7X"
name: "Demo 1"
owner: "0x0000000000000000000000000000000000000000"
price: "100.0"
seller: "0x8626f6940E2eb28930eFb4CeF49B2d1F2C9C1199"
sold: true
tokenId: 1
}
I am supposing that this error pertains to web3modal and not including the code for loadNfts() function, createMarketSale smartcontract and Market.abi. Please let me know if I you need them.
Another interesting thing to note is that, if I navigate to create page and create a new NFT, buyNft function works fine and opens metamask. But after the first time, it is again throwing the same "-32603-Internal JSON RPC error" for subsequent clicks.
I tried other variations of web3modal such as passing window.ethereum into Web3Provider, not passing connection into web3provider and using JsonRpcProvider. But any of them didn't work.
This seemed like a garbage collection issue at first so I added useEffect to cleanup. Not sure if it solved anything other than memory leaks and issue still remains.
Please let me know what I am missing.