I have used Transfer function for an erc20 in different contracts with the same codes. The point is here, in different times there was different gas while the function was the same. The input of the function was the same too but I do not know why the gases are different.
-
The exact gas costs depends on a variety of factors, primarily the state of the contract you're interacting with. Read this: Gas and fees and this: What is meant by the term "gas"?.– Paul Razvan BergJun 14, 2022 at 9:42
-
To tell the truth I mean different gas amount for example once it's 94000 second it's 77000 for the same function– Amirali SahraeiJun 14, 2022 at 9:48
-
Yes, start with reading the articles I linked in my first comment.– Paul Razvan BergJun 14, 2022 at 9:55
1 Answer
Probably you are transferring tokens to an address which previously had a balance of zero
In order to understand the difference you should know the gas cost of the following operations:
Gsset 20000 Paid for an SSTORE operation when the storage value is set to non-zero from zero.
2900 Paid for an SSTORE operation when the storage value’s zeroness remains unchanged or is set to zero.
take a look at the ethereum yellow paper (page 27)
this line in the transfer function of ERC20.sol:
_balances[recipient] += amount;
is setting the balance of the recipient of the transaction so in the first transfer, it is storing a value in a slot of data which was previously zero then you are paying for this operation (Gsset) 20000 unit of gas
in the second transfer the balance is updated but that slot is changing the value from non-zero (the value transferred in the first transaction) to a non-zero value then you are paying for this operation (Gsreset) 2900 unit of gas
that is where probably the difference came from