[Ethereum] Get all tokens owned by an address under the same ERC1155 contract

erc-1155remixsoliditysolidity-0.8.xtokens

I am making an ERC 1155 contract and it is a mixture of NFTs and FTs, my intention is that from a token id forward, the user only be able to own one of the token, something like the minting below:

pragma solidity ^0.8.2;

import "@openzeppelin/contracts@4.3.2/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts@4.3.2/access/Ownable.sol";
import "@openzeppelin/contracts@4.3.2/utils/Strings.sol";

contract MyToken is ERC1155, Ownable {
    constructor() ERC1155("") {}
    string private _uri;
    uint256 private _indexID = 1000000000;
    
    function mint()
        public
        payable
    {
        require(msg.value > 0.001 ether);
        _mint(msg.sender, _indexID, 1, "");
        _indexID++;
    }
    
    ...
}

Now I am trying to add a function which can be used to return all the token ids owned by an address, in case that someone already has experience with such senario or knows a work around, it will really great if you can please share it here

thank you for your attention

Best Answer

You should do that off-chain if you can. For an off-chain solution see Get a list of all token types for ERC1155

To get all tokens of an account within a smart contract you'd have to add enumeration. Openzeppelin doesn't have it to reduce gas costs.

I use solidstate, it has an enumerable extension (it's designed for eip-2535, but you can still use it)

https://github.com/solidstate-network/solidstate-solidity/blob/5a8c6745d85b3f39f8f05bcbc5b5a78e7189b216/contracts/token/ERC1155/enumerable/ERC1155Enumerable.sol

Related Topic