0

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?

1 Answer 1

0

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.

3
  • So its not possible to allocate a storage slot within inline assembly code?\
    – Emrah
    Commented May 3, 2022 at 13:50
  • I think you can do that, can read about it here jeancvllr.medium.com/…
    – Kof
    Commented May 3, 2022 at 16:36
  • I think this is how you do it. let x := add(a,b), sstore(0, x). So no need for uint256 public value;
    – Emrah
    Commented May 3, 2022 at 16:40

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.