0

I want to use a mapping that stores prices for each token in my ERC721 contract but am hitting an issue with the default uint value being 0. I'd like for my getPrice(uint256 tokenId) function to account for both a zero value price and an empty value if possible. I'm wondering if there are any patterns in practice that solve this issue.

    mapping (uint256 => uint256) listing;
    
    function getPrice(uint256 tokenId) {
        // will return 0 for no value found, which could lead to the perception that the price is 0.
        return listing[tokenId];
    }

2 Answers 2

2

The default value is always gonna be zero.

One thing you can do is write an if else statement and see if it is 0 or not. And if it is zero then you can throw an error may be.

But it depends on how you are expecting the function to work.

0

Usually, you have some tokenId → token relation in smart-contract, depending on how you generate tokenId and create your listings. So when your business logic of getPrice should rely on whether the listing has been not created yet or the price is zero, you could check the listing first. Small example:

contract Foo {
    // tokenId => price
    mapping (uint256 => uint256) listing;
    // tokenId => token address
    mapping (uint256 => address) listings;
    
    function getPrice(uint256 tokenId) {
        require(listings[tokenId] != address(0), "LISTING_NOT_FOUND");
        // will return 0 for no value found, which could lead to the perception that the price is 0.
        return listing[tokenId];
    }
    function createListing (uint256 tokenId, address token, uint256 price) public onlyOwner {
        listings[tokenId] = token;
        // evtl some initial price
        listing[tokenId] = price;
    }
    // ... other methods to update listing
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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