blockchainsoliditychainfterc721

Call smart contract function by connecting contract address in hardhat (ethers)


Background of Problem:

I am developing an NFT Marketplace. In its workflow, the admin (deployer of the smart contract) adds NFTs to the marketplace, and at that time these NFTs are owned by the Marketplace smart contract.

Now when a user comes to buy a particular NFT we have to transfer the ownership from the smart contract address to the signer/wallet address.

Actual Problem:

While writing chai tests, I need to call the function buyFromMarketplace written in marketplace contract, which transfers the ownership of nft there. I am trying connecting the marketplace smart contract address (But I can't find any way to do it) I've tried to do it this way (But I knew this won't work)

await nft.connect(marketplace).approve(addr1.address, 0);

Also tried to send a raw address while connecting to the NFT smart contract before calling approve by calling marketplace.address.

In this thread, something similar is being done but NOT in testing

While a similar thing is done with ERC20 tokens here.

Edit: I found the solution and posted in answers, maybe it helps someone in the future!


Solution

  • Answering my own question, so in the future, it may help someone else.

    Well, after some struggle and @Tahlil's answer, I found the solution to this problem.

    The actual problem was buyFromMarketplace function transfers nft's ownership from contract to the wallet/signer. So we were calling nft.transfer in it. Which need's owner/approved to call it but as mentioned in question intially nft is owned by Marketplace contract.

    Actually we didn't needed to approve caller's account by calling approve marketplace contract address before calling buyFromMarketplace.

    Opinion:

    connect function of ethers hardhat should not allow connecting contract addresses, since we are dealing with accounts there.

    Fact:

    It works exaclty the same.