0

I use state variables for the interaction of calls (fallback) between contracts. But copying and clearing state variables uses a lot of gas.

Perhaps there is a better practice, how to have temporary variables in the contract scope?

bytes private myGloabalVar;

function func(calldata params, address target) {
    delete myGloabalVar;
    myGloabalVar = params;//too much gas is used here
    target.call('0x1234');//with callback
    delete myGloabalVar;
}

fallback() external payable {
    //use myGloabalVar
}

1 Answer 1

0

Temporary variables live only at the point of procedure execution. If the value in myGloabalVar is needed only for mutex definition, I will suggest a better way:

pragma solidity ^0.8.13;

contract FixedEtherVault {
    uint internal locked = 1;

    modifier noReentrant() {
        require(locked == 1, "No re-entrancy");
        locked = 2;
        _;
        locked = 1;
    }
    
    //bytes private myGloabalVar;

    function func(bytes calldata params, address target)external noReentrant {
        // delete myGloabalVar;
        // myGloabalVar = params;//too much gas is used here
        target.call('0x1234');//with callback
        // delete myGloabalVar;
    }
}

You spend gas to write to storage and then get half that amount if you write 0 to the same slot. Which is still a lot = 10000.

It is better to always leave a value in the slot (in this case 1 and 2) and then the cost will be reduced.

1
  • Value in myGloabalVar is needed for processing in callback functions. Thanks for the advice on gas savings
    – Andriy
    Oct 26, 2023 at 7:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.