0

Please see the following code:

// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.1; contract Crowdfund { uint fundLimit = 3 ether; bool contractOpen = true; function donate() external payable { require(contractOpen, "Contract has stopped recieving funds"); require(address(this).balance + msg.value <= fundLimit, "Can't send specified amount"); } } 

If I try to send 2 (or) 3 ether then the transaction is failing;

The transaction has been reverted to the initial state. Reason provided by the contract: "Can't send specified amount". Debug the transaction to get more information. 

Ideally, the transaction of 2 (or) 3 ether should not fail because fundLimit is set to 3 ether. And initially, the contract balance is 0.

I am unable to know the reason for this.

1 Answer 1

0

The safest way to represent the value of your smart contract is to use a variable rather than address(this).balance. This can easily be manipulated by sending ether to your contract (even if you don't have any fallback or receive functions).

uint public balance = 0; 

And whenver you deposit money, balance += msg.value.

That being said, your require fails because when you send 2 ether, your account balance is immediately becoming 2 ether. And adding msg.value to address(this).balance makes it 4 and fails the check. You can test what I said by returning the address(this).balance + msg.value. What I would do instead:

// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; contract Crowdfund { uint fundLimit = 3 ether; bool contractOpen = true; uint public balance = 0; function donate() external payable { require(contractOpen, "Contract has stopped recieving funds"); balance += msg.value; require(balance <= fundLimit, "Too much!!"); } } 
2
  • Thanks, this solved my issue I just used address(this).balance. Actually, I am playing around with the force send / self-destruct vulnerability so didn't actually want to use a variable as you suggested. Commented May 8, 2022 at 18:11
  • yeap, selfdestruct vulnerability is exactly what I was saying. Commented May 8, 2022 at 18:12

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.