我想再检查一遍。
我一直在编写使用大量constants的可升级智能联系人。据我所见,智能契约并没有在它们的存储中存储constant变量。这意味着这些变量不会对可升级的智能契约造成内存冲突。
我自己编写了一些简单的代码来测试它,似乎就是这样。
//SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.3;
contract ReadStorage {
///////////////// Main Functionality /////////////////////
uint firstVariable = 1;
// Public Constant
uint public constant secondVariable = 2;
function updateFirstVariable(uint newValue) public {
firstVariable = newValue;
}
function readFirstVariable() public view returns (uint) {
return firstVariable;
}
///////////////// Assembly Functions /////////////////////
function updateSlot(uint256 slotNumber, uint256 newValue) public {
assembly {
sstore(slotNumber, newValue)
}
}
function readSlot(uint slotNumber) public view returns (uint value) {
assembly{
value := sload(slotNumber)
}
}
}我现在的问题是:如果没有存储,constants存储在哪里?在编译过程中,它们是否被“嵌入”在合同中?EVM必须从某个地方读取这些值。我假设常量可能被添加到字节码或类似的东西中。但我没能找到解释。所以如果有人能更详细地解释一下,我会很感激的。
发布于 2022-12-05 14:19:09
常量不在任何地方存储。在编译时,它们在每次使用中都被它们的常量值所取代。
例如,下面的代码。注意,当我从一个函数返回一个常量时,它建议我可以使用pure修饰符而不是view,因为没有什么可从存储中读取,因为该常量的值100将直接在函数中使用。
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
contract Example {
uint256 constant VALUE = 100;
function getValue() public pure returns(uint256) {
return VALUE;
}
}编译后会出现这样的情况:
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
contract Example{
function getValue() public pure returns(uint256) {
return 100;
}
}发布于 2022-12-05 14:20:50
正确的是,Solidity中的常量(即用常量、视图或纯修饰符标记的变量)没有存储在契约存储中。这些变量在编译时进行评估,结果值“嵌入”在契约的生成字节码中。
当契约被部署到Ethereum块链时,存储在块链上的字节码包含契约中定义的所有常量的值。当调用标记为常数、视图或纯的契约函数时,EVM将从字节码中查找常量的值,并将其用于函数的执行。
这里有一个例子来说明这是如何工作的。考虑以下合同:
pragma solidity 0.8.3;
contract MyContract {
uint public constant firstVariable = 1;
uint public constant secondVariable = 2;
function getSum() public view returns (uint) {
return firstVariable + secondVariable;
}
}在编译此契约时,firstVariable和secondVariable常量的值“嵌入”在契约的字节码中。生成的字节码可能如下所示:
0x6080604052600436106100405763ffffffff7c010000000000000000000000000000000000...(etc)
发布于 2023-01-04 07:08:07
实体中的常量不是存储在合同存储中,而是在编译契约时保存在契约的字节码中。在部署契约时,常量值包含在发送到Ethereum块链的字节码中。
契约的字节码是表示契约的代码和数据的字节序列。在编译契约时,将常量值包含在字节码中,这样可以有效地读取和使用EVM虚拟机(EVM)。
例如,考虑以下合同:
pragma solidity ^0.8.3;
contract ConstantContract {
uint public constant foo = 42;
}在编译此契约时,foo变量的常量值42将包含在契约的字节码中。在部署契约时,字节码将被发送到Ethereum块链,并存储在合同的存储中。当契约被执行时,EVM将能够从字节码中读取foo的值,并在契约的逻辑中使用它。
https://ethereum.stackexchange.com/questions/140628
复制相似问题