Replacing the value of dynamic array inside a Solidity Struct

Viewed 457

I have a dynamic array inside the UserListing and have problems accessing the dynamic array Listing[] to change the status to Cancelled in solidity programming. The current push function is just appending another array to the list, may I ask can we delete the previous listing and replace it with the new one / change the value inside the dynamic array inside the Listing[]. Thank you so much if any help is provided :)

struct UserListing {
    address ownerAddress;
    Listing[] list;
}

struct Listing {
    uint listingId;
    ListingStatus status;
    address seller;
    address token;
    uint tokenId;
    uint price;
}

uint private _listingId = 0;

mapping(uint => Listing) private _listings;
mapping(address => UserListing) public userListings;

function cancel(uint listingId) public {
    Listing storage listing = _listings[listingId];

    require(msg.sender == listing.seller, "Only seller can cancel listing");
    require(listing.status == ListingStatus.Active, "Listing is not active");

    
    listing.status = ListingStatus.Cancelled;

    userListings[msg.sender].list.push(
        Listing({
            listingId : _listingId,
            status: ListingStatus.Cancelled,
            seller : msg.sender,
            token: listing.token,
            tokenId : listing.tokenId,
            price : listing.price
        })
    );

    IntERC721(listing.token).transferFrom(address(this), msg.sender, listing.tokenId);

    emit Cancel(listingId, listing.seller);
}
1 Answers

As far as I understood, inside cancel you want to find the item (a Listing) inside a user's list with given listingId and change its status. For this, you do not need to delete anything. You just iterate over the user's list. find the Listing and change its status.

 // i will modify userItems
 // since state variables are storage by default, modifying this will modify the state of the contract
 Listing[] storage userItems = userListings[msg.sender]

Now run a for loop:

for(uint256 i=0; i<userItems.length; i++){

   if userItems[i].listingId==listingId{
      userItems[i].status=ListingStatus.Cancelled,
}
Related