Solidity adding item to nested array in struct

I'm trying to add an item to an array that is a struct, inside a struct.

This is how my contract looks like:

contract AuctionHouse {
  struct Bid {
    address bidder;
    uint256 amount;
    uint256 timestamp;
  }
  
  struct Auction {
    address seller;
    uint256 reservePrice;
    uint256 winnerBidAmount;
    address winnerBidBidder;
    
    Bid[] Bids;
  }
  
  function listItem (uint256 _tokenId) public returns (bool) {
    Bid[] memory emptyBids;

    auctions[_tokenId] = Auction({
      seller: msg.sender,
      reservePrice: _reservePrice,
      winningBidAmount: 0,
      winningBidBidder: address(0),
      bids: emptyBids
    });

    return true;
  }
  
  function bid (uint256 _tokenId, uint256 _amount) public returns (bool) {
    Auction currentAuction = auctions[_tokenId];
    
    uint256 newBidIndex = currentAuction.bids.length + 1;
    Bid newBid = currentAuction[newBidIndex];
    newBid.bidder = msg.sender;
    newBid.amount = msg.amount;
    newBid.timestamp = block.timestamp;

    currentAuction.winningBidAmount = msg.value;
    currentAuction.winningBidBidder = msg.sender;
    
    return true;
  }
}

But I'm getting the error:

contracts/AuctinoHouse.sol:274:26: TypeError: Indexed expression has to be a type, mapping or array (is struct TripAuctionHouse.Auction storage pointer)
    Bid storage newBid = currentAuction[newBidIndex];

I also tried changing inside the bid function:

Auction currentAuction = auctions[_tokenId];

to have storage or memory and tried to play around with that, but that gives different errors.

What is the correct way to do this?


Solution 1:

You catched the newBid in a wrong way

Bid newBid = currentAuction[newBidIndex];

This will returns Auction struct, not Bid

I replaced the code like this:

function bid (uint256 _tokenId, uint256 _amount) public returns (bool) {
    Auction currentAuction = auctions[_tokenId];
    
    uint256 newBidIndex = currentAuction.bids.length + 1;
    Bid newBid = currentAuction.Bids[newBidIndex];
    newBid.bidder = msg.sender;
    newBid.amount = msg.amount;
    newBid.timestamp = block.timestamp;

    currentAuction.winningBidAmount = msg.value;
    currentAuction.winningBidBidder = msg.sender;
    
    return true;
  }