Gas optimization in Solidity, Ethereum

I’m sorry but my English is terrible. I hope you understand that generously.

Recently, I was developing a toy project named Blind Market. It’s a simple P2P trading application using smart contract.

I was making a contract using Solidity, and the trade stage proceeded in the order of pending, shipping, and done.

The problem was appeared in done phase. The problem was that when I tried to close the transaction by paying the price raised by the seller in msg.value, the following error occurred.

Pending...

I was conducting a test in the Remix VM environment, and there was no shortage of ether. But the pending status does not end.

But if there was any doubt, the turnIntoDone force was doing too much.

Looking at it again, it's really long and a lot of work. It became too long because I wrote the code first.

There were parts where data was obtained using the view function in the middle, I thought it was safer to call from inside the function than to call from the outside and get it and inject the data.

The first method I prescribed to solve the problem was to optimize gas. It seemed clear that this function would require a considerable amount of gas, even if this was not the cause.

So I started to rebuild the data structures in contract first.

Before optimization

After optimization

The first thing I tried was to reconstruct the variables of the structure.

I change the value type of usedBLI and price to uint128 from uint256.

Because the SSTORE command consumes a lot of gas, it was determined that it was necessary to pack the variables according to uint256.

Second is declare every fee ratio variable as constant variable.

Third is add encode and decode function for encoding two variable (usedBLI, price) and for decoding when we use them.

I judged that it would be more efficient to keep the encoded bytes32 variable instead of keeping the two variables in the structure. The encoding function and the decoding function were written as follows.

Finally, local variable was actively used to minimize the number of times the storage data is read.

As I made the correction, the reason was actually payable.

There was a part of transferring to the contract using payable, and when I annotated that part, everything worked smoothly.

However, through this process, my knowledge of gas optimization seems to have improved than before, so I share it in writing.

Below are the links that helped solve the problem. It would be good to refer to.

Sources …

Last updated