Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solidity : How does function parameters' size affects gas cost?

before anything here's some context :

Let's say I'm implementing a dApp, and I want to reduce the number of times users have to call the related smart-contract. In order to do this, all the users' actions are stacked-up, client-side. Eventually, users will have to commit their actions to the smart-contract, in order to update their datas on chain.

The smart-contract takes a queue of all the users' actions as a parameter, and iterate over it to do mainly some checkings and update. A bit like this :

function verifyUsersActions(Queue actions) public
{
    while(actions.length != 0)
    {
        Action currentAction = actions.pop(); 
            /* tests on currentAction, update datas, etc */
    }
}

My question is: how does the size of the "actions" object affects gas cost ? What's the increment in gas, between an "actions.length = 2" and an "actions.length = 3" ?

I'm still confused with "memory" and "storage" variables, and don't know in which category does function call parameters fall in.

like image 332
Folk Avatar asked Apr 09 '26 23:04

Folk


1 Answers

As i saw from comments, ignoring the gas cost of parameter is not a good idea. Parameters, that we gonna call that as calldata will be used on several op codes. To better understand how it affects gas cost we should check the op codes relevant with calldata.

You can find all opcodes at EtherVM

The opcodes we gonna look for are CALLDATALOAD, CALLDATACOPY

The explanations of these op codes are first loads the several calldata with offset, and the second copies the data to the memory.

In solidity when you make a process with parameter and save the result to the memory or storage variable, you have to copy this data to the memory and it cost gas. And simply it increases gas by non-zero values inside the calldata.

If you type dynamic array, struct like your case. At the compilation solidity will add an opcodes to find the value size. It reads each slots(32 bytes) to find the end of your payload. These are all costs gas.

like image 148
Erim Varış Avatar answered Apr 12 '26 23:04

Erim Varış