How to reduce the amount of gas?

Viewed 27

I need to keep track of some events - lots

struct Lot{
        address owner,
        uint256 price,
        uint256 time
    };

There is no need to go into the details of this entity, it is only important that there are many lots and they are regularly created.

Initially, I made a mapping of all lots:

mapping(address=>Lot) lots;

However, this approach requires a lot of gas, especially when trying to change any lot.

Therefore, I thought to do it the following way - to encode each lot and store all lots as a bytecode sequence in the contract. That is, F let the encoding function:

F(x) = b1b2...bN; bi - byte
F-1(b1b2...bN) = x
S = F(lot1, lot2, ..., lotM)

Now only S will be contained in the storage and store all existing lots in itself.

Are there implementations of this?

1 Answers

I assume you want to store all the information on-chain.

I don't see a way in which your encoding is useful. Since S is basically a sequence of all lots together, it will occupy the same storage space of the mapping. Also modifying/adding a lot will use at best the same gas.

The only trick you can use is compress the Lot struct from 3 storage slot to 2 (or even 1). You can do it by lowering the bytes of the variables, for example:

    // this is 3 slots
    struct Lot{
        address owner,
        uint256 price,
        uint256 time
    };

    // this is 2 slots
    struct Lot{
        address owner,
        uint128 price,
        uint128 time
    };

    // this is 2 slots
    struct Lot{
        address owner,
        uint96 price,
        uint256 time
    };

    // this is 1 slot
    struct Lot{
        address owner,
        uint48 price,
        uint48 time
    };

Of course it all depends if price and time need to be fine-grained, their range, etc...

Related