If you’re an expert Solidity developer and have worked on various projects, this has surely been a matter of concern for you most of the time.

Wtf is a memory array?

Memory arrays are usually dynamically constructed arrays in functions with mutability modifiers like pure or view, where we generally read the state and construct a dynamic array rather than modifying state.

While modifying state, we usually read from storage and hence can construct dynamic arrays. So that’s a whole different issue.

Theory Aside… Let’s Jump into Action

Problem

We’ve created a smart contract that stores the IDs of NFTs owned by a wallet address, and on the fly, we should generate a dynamic array that returns the IDs of NFTs that were bought within the last 30 days.

Solution

We need to construct a dynamic array.

// SPDX-License-Identifier: ISC
pragma solidity ^0.8.13;

contract DynamicArray {
    uint256 public supply;

    struct NFT {
        uint256 id;
        uint256 purchasedAt;
    }

    struct User {
        uint256[] nfts;
    }

    mapping(address => User) private user;
    mapping(uint256 => NFT) public nft;

    function purchase() external virtual {
        supply += 1;
        nft[supply] = NFT(supply, block.timestamp);
        user[msg.sender].nfts.push(supply);
    }

    function fetchUserNfts(address userAddress)
             external
             view
             returns (uint256[] memory)
    {
        return user[userAddress].nfts;
    }
}

So in the above smart contract, it is clear that when we return a static memory array it works like a hot knife through butter.

But we don’t need to fetch all the NFTs of a user; instead, we need to fetch the NFTs that were purchased within the last 30 days. So here comes the need for a dynamic array.

function fetchUserNftsInLast30Days(address userAddress) 
         external 
         view 
         returns (uint256[] memory) {
        uint256[] memory nfts = user[userAddress].nfts;
        uint256 size;
        uint256 counter;

        for(uint256 i=0; i<nfts.length; i++) {
            if(
              nft[nfts[i]].purchasedAt + 30 days 
              > block.timestamp) 
            {
                size ++;
            }
        }

        uint256[] memory filtered = new uint256[](size);

        for(uint256 i=0; i<nfts.length; i++) {
            if(
              nft[nfts[i]].purchasedAt + 30 days 
              > block.timestamp) 
            {
                filtered[counter] = nfts[i];
                counter ++;
            }
        }

        return filtered;
    }

Analysis

The above code will allow you to fetch the IDs of NFTs purchased by a user in the last 30 days, but the gas consumption grows with the number of NFTs. We don’t spend gas for view calls, but there is still a risk of hitting the block gas limit.

Safe limit: 200 IDs

If your array length will always be less than 200, then you could practically apply this solution in your smart contract.

Another approach to this would be removing the size calculation in the first part of this function and just declaring the total size of the array as the size of the new array, except that we end up with zeros in the array for the entries that don’t satisfy the condition.

Gas difference: 98,435 vs. 600,000

But the returned array would have a lot of zero entries, since the entries that are not updated are returned as zeros, and these zero entries cannot be popped from the array because memory arrays do not have a pop() method.