Solidity-059 StorageAssembly

本文介绍了一个名为`StorageAssembly`的智能合约,展示了如何在以太坊虚拟机(EVM)中使用InlineAssembly直接操作存储。它演示了存储变量的使用,包括读取和更新存储槽中的值。
摘要由CSDN通过智能技术生成

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

// Define a contract named StorageAssembly

contract StorageAssembly {

    // A state variable to hold a uint256 value

    uint256 StateVariable;

    // A function that demonstrates the use of inline assembly to directly manipulate storage

    function assemblyUsage() public returns (uint256 newstatevariable, uint256 newderivedvariable) {

        assembly {

            // Directly store the value 100 at storage slot 0

            sstore(0x0, 100)

            // Load the value from storage slot 0 into the variable `newstatevariable`

            newstatevariable := sload(0x0)

            // Directly store the value 200 at storage slot 1

            sstore(0x1, 200)

            // Load the value from storage slot 1 into the variable `newderivedvariable`

            newderivedvariable := sload(0x1)

        }

    }

    // A public view function to get the current value of StateVariable

    function getStateVariable() public view returns(uint256) {

        return StateVariable;

    }

    // A function to retrieve the value stored at storage slot 1 using inline assembly

    function getNewDerivedVariable() public view returns(uint256 slot1) {

        assembly {

            // Load the value from storage slot 1 into the variable `slot1`

            slot1 := sload(0x1)

        }

    }

    // A function to update the state variable by adding a given value to the value at storage slot 1,

    // and then storing the result back into the state variable.

    function updateStateVariable(uint256 intValue) public returns (uint newValue){

        assembly {

            // Add `intValue` to the value at storage slot 1 and store the result in `newValue`

            newValue := add(intValue, sload(0x1))

            // Update the state variable `StateVariable` with `newValue`

            sstore(0, newValue)

        }

    }

}


  • 24
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值