Cryptokitties Storage – Why Cryptokitties Uses Storage Instead of Memory

cryptokittiesmemorysoliditystorage

There are a lot of explainations of storage and memory out there like this question or this question. But I'm wondering why cryptokitties for example uses storage instead of memory in many functions. In this case the auction is not modified. Wouldn't it be cheaper to use memory here?

function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) {

    Auction storage auction = _getAuctionByTokenId(_tokenId);
    require(_isOnAuction(auction));

    uint256 price = _currentPrice(auction);
    require(_bidAmount >= price);

    address seller = auction.seller;
    _removeAuction(_tokenId);

    // Transfer proceeds to seller (if there are any!)
    if (price > 0) {
       ...
        uint256 auctioneerCut = _computeCut(price);
        uint256 sellerProceeds = price - auctioneerCut;
        // Ether transfer
        seller.transfer(sellerProceeds);
    }

    emit AuctionSuccessful(_tokenId, price, msg.sender);
    return price;
}

Best Answer

Because is not creating a new object but is a storage pointer. _getAuctionByTokenId most probably would read something in the contract storage.

Assume this example

contract MyContract {
    struct myStruct {
        address id;
    }
    mapping(address => myStruct) myMapping;

    function doSomeStuff(address _tokenId) public view returns(address) {    
        myStruct storage myObj = myMapping[_tokenId];

        return myObj.id;
    }   
}

myObj is not a new object but a pointer to a storage location already stored inside my contract. If I remove the storage keyword I would get the following warning:

Warning: Variable is declared as a storage pointer. Use an explicit "storage" keyword to silence this warning.

Related Topic