1

I am trying to get the token id back after minting. I have the below function in my contract sol.

    function createToken(address to) public onlyOwner returns (uint256)  {
        _tokenIdCounter.increment();
        uint256 newItemId = _tokenIdCounter.current();

        _safeMint(to, newItemId);
        return newItemId;
    }

The minting works, but instead of getting newItemId returned I am getting json data back. Same as if I just called the mint method directly.

{
  tx: '0xf...',
  receipt: {
    transactionHash: '0x...',
    transactionIndex: 0,
    blockHash: '0x...',
    blockNumber: 5,
    from: '0x...',
    to: '0x...',
    gasUsed: 154884,
    cumulativeGasUsed: 154884,
    ...

I am testing locally with truffle.

2
  • When u send a transaction to invoke a function in smart contract then u get the transaction receipt back and not the result of that function. However I think safeMint emit an event and you can find the Id of the minted token in the logs of the transaction receipt
    – Majd TL
    Sep 11 at 12:34
  • you should get the logs and then decode it
    – Majd TL
    Sep 11 at 12:35
1

This is basically an eth_getTransactionReceipt response, but you are not going to retrieve the return value using this unless your function has the view/pure modifier, in your case this function needs to modify the state of the contract so you need to create an Event to log it when the function is done, then you will be able to check it, something like:

// you can also use "indexed" if you want the value in the topics 
event Mint(uint256 _tokenId);

function createToken ...
...
emit Mint(newItemId);
...
}

the response will be the same, but in the logs field you will find something like (in this sample the tokenId is 10):

logs": [
      {
        ...
        "data": "0x000000000000000000000000000000000000000000000000000000000000000a",
        "topics": [
          "0x07883703ed0e86588a40d76551c92f8a4b329e3bf19765e0e6749473c1a84665"
        ],
      }
]

Basically the topics will store the keccak256 function name and any indexed parameter of your event (in this case none), and the data will store the non indexed values (in this case 10).

So to get the tokenId you just need to convert the data field to uint 0x000000000000000000000000000000000000000000000000000000000000000a = 64 bytes hex string => 10

Worth to give a look at:

https://docs.soliditylang.org/en/latest/contracts.html#events
https://docs.soliditylang.org/en/latest/contracts.html#functions
https://docs.soliditylang.org/en/latest/abi-spec.html

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