storage – How to Write to Storage with Inline Assembly in Ethereum

assemblystorage

I have this contract where I use inline assembly to add two numbers.

pragma solidity ^0.8.0;

contract Test {
    function add(uint a, uint b) external {
        assembly {
            let sum := add(a,b)
            mstore(mload(0x40), sum)
        }
    } 
}

Now the question is, how to write variable sum to storage? In other words, how to make this sum persistent?

Best Answer

Add the following line at the end of your assembly -

sstore(value.slot, sum)

That will store sum value into the slot of contract variable value.

You can also remove the mstore and local var sum and write directly to the variable -

contract Test {

    uint256 public value;

    function add(uint a, uint b) external {
        assembly {
            sstore(value.slot, add(a,b))
        }
    } 
}

Take into consideration this doesn't handle arithmetic overflow, this is not safe to use if input number a + b is larger than uint256.

Related Topic