0

I have a solidity contract with a method that mints an ERC721 token and returns the tokenId

function createItem(string memory tokenURI) public returns (uint256)
    {
        _tokenIds.increment();

        uint256 newItemId = _tokenIds.current();
        _mint(msg.sender, newItemId);
        _setTokenURI(newItemId, tokenURI);

        return newItemId;
    }

In a react application, I'm doing a "send" call to the method in order to get the tokenId. Usually, it works well.

The problem is that when the transaction takes time, Metamask returns an error "Transaction was not mined within 50 blocks", so I cannot get the tokenId.

I have the transactionHash, I have the receipt (by calling web3.eth.getTransactionReceipt(transactionHash);) but I'm not able to get the tokenId

I tried getting it from the events:

const receipt = await new web3.eth.getTransactionReceipt(transactionHash);
    console.log(receipt);
    if (receipt && receipt.status === true && !status) {
        if (receipt.events) {
            const { Transfer } = receipt.events;
            const tokenId = Transfer && Transfer["returnValues"] ? Transfer["returnValues"]["tokenId"] : 0;
            if (tokenId) {
                console.log(tokenId);
            }

Also from the logs, as in my truffle tests, I can get the tokenId from there:

 it("Should create 3rd nft", async () => {
    var tokenIdResponse = await instance.createItem("www.somemetadata.com", { from: owner });
    assert.equal(tokenIdResponse.logs[0].args.tokenId, 3);
  });

But the receipt object I get when calling getTransactionReceipt, did not have that info in the logs: Logs screenshot

So, could anyone help me? I'm stuck.

How can I get a returned value when the "send" did not return immediately?

1 Answer 1

2

You have to listen to the contract events. "mint" function is done by the standards that should emit the Mint event. And then you can do something like this:

contract.events.allEvents()
.on('data', (event) => {
    console.log(event);
})
.on('error', console.error);

There are many manuals out there for "listen for smart contract events"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.