[英]Function declared as view error in solidity
pragma solidity >=0.4.16 <0.9.0;
contract Wallet {
uint balance = 0;
bool a = true;
function deposit(uint dep_amt) public {
balance += dep_amt;
}
function withdraw (uint wdraw_amt) public view returns(string memory error){
if(wdraw_amt<=balance){
balance -= wdraw_amt;
}
else{
error = "Insufficient Balance";
return error;
}
}
function getBalnce() public view returns (uint) {
return balance;
}
}
I'm very new to solidity and I'm trying to code a simple bank system which shows the balance and updates the balance according to the deposits and withdraws.我对solidity非常陌生,我正在尝试编写一个简单的银行系统,该系统显示余额并根据存款和取款更新余额。 I want to display an error in withdraw function when the amount to be withdrawn is greater than the balance but it shows an error saying:
当要提取的金额大于余额时,我想在提取功能中显示错误,但它显示一条错误消息:
TypeError: Function declared as view, but this expression (potentially) modifies the state and thus requires non-payable (the default) or payable.
Is there a way to possibly show the error from the same function?有没有办法可能显示来自同一函数的错误?
If not, Please let me know an alternative.如果没有,请让我知道替代方案。
Thanks in advance!!.提前致谢!!。
A view
function promises not to modify the contract state - such as not to modify storage variables. view
函数承诺不修改合约状态——例如不修改存储变量。 See the docs for more info.有关更多信息,请参阅文档。
But your code modifies the balance
variable, which is a storage variable.但是您的代码修改了
balance
变量,这是一个存储变量。
function withdraw (uint wdraw_amt) public view returns(string memory error){
if(wdraw_amt<=balance){
balance -= wdraw_amt; // <-- here
}
and updates the balance according to the deposits and withdraws
并根据存取款更新余额
Since one of your requirements is to actually update the storage variable, you need to remove the view
modifier in order to be able to do that.由于您的要求之一是实际更新存储变量,因此您需要删除
view
修饰符才能做到这一点。
function withdraw (uint wdraw_amt) public returns(string memory error){
Users will then need to send a transaction (not a call) to execute the withdraw()
function.然后用户需要发送交易(而不是调用)来执行
withdraw()
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.