Solidity - 为什么即使 address.call{value:msg.value}("") 没有数据也会调用 fallback()?
Solidity - why does fallback() get called even though address.call{value:msg.value}("") does not have data?
以下合约使用接口方法调用另一个合约(代码更改):
pragma solidity 0.8.7;
interface MyStorage {
function setStorageValue(uint256) external;
}
contract StorageFactory {
uint256 storageValue;
constructor(uint256 _storageValue) {
storage = _storageValue;
}
function initStorage(MyStorage store) public payable {
store.setStorageValue(storageValue);
address payable storeAddress = payable(address(store));
storeAddress.call{value: msg.value}("");
}
}
以下是StorageContract(代码不可更改):
pragma solidity 0.8.7;
contract Storage {
int _storageValue;
function setStorageValue(int storageValue) public {
_storageValue = storageValue;
}
receive() external payable {
require(_storageValue == -1 || address(this).balance <= uint(_storageValue), "Invalid storage value");
}
fallback() external {
_storageValue = -1;
}
}
我使用一个测试通过传递一个存储对象来调用第一个合约的initStorage,这个测试注定要失败,因为该值被设置为一个很大的数量。但不知何故,似乎调用了 fallback() 函数,将值设置为 -1。我不知道为什么。感谢任何帮助。
由于 solidity doc:
The fallback function is executed on a call to the contract if none of the other functions match the given function signature, or if no data was supplied at all and there is no receive Ether function. The fallback function always receives data, but in order to also receive Ether it must be marked payable.
你的函数被调用是因为函数没有重载
function setStorageValue(uint256 storageValue) public
因此,将 storageValue
从 int
更改为 uint256
会有所帮助。
以下合约使用接口方法调用另一个合约(代码更改):
pragma solidity 0.8.7;
interface MyStorage {
function setStorageValue(uint256) external;
}
contract StorageFactory {
uint256 storageValue;
constructor(uint256 _storageValue) {
storage = _storageValue;
}
function initStorage(MyStorage store) public payable {
store.setStorageValue(storageValue);
address payable storeAddress = payable(address(store));
storeAddress.call{value: msg.value}("");
}
}
以下是StorageContract(代码不可更改):
pragma solidity 0.8.7;
contract Storage {
int _storageValue;
function setStorageValue(int storageValue) public {
_storageValue = storageValue;
}
receive() external payable {
require(_storageValue == -1 || address(this).balance <= uint(_storageValue), "Invalid storage value");
}
fallback() external {
_storageValue = -1;
}
}
我使用一个测试通过传递一个存储对象来调用第一个合约的initStorage,这个测试注定要失败,因为该值被设置为一个很大的数量。但不知何故,似乎调用了 fallback() 函数,将值设置为 -1。我不知道为什么。感谢任何帮助。
由于 solidity doc:
The fallback function is executed on a call to the contract if none of the other functions match the given function signature, or if no data was supplied at all and there is no receive Ether function. The fallback function always receives data, but in order to also receive Ether it must be marked payable.
你的函数被调用是因为函数没有重载
function setStorageValue(uint256 storageValue) public
因此,将 storageValue
从 int
更改为 uint256
会有所帮助。