-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathFixedEtherVault.sol
58 lines (42 loc) · 2.01 KB
/
FixedEtherVault.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// SPDX-License-Identifier: BSL-1.0 (Boost Software License 1.0)
//-------------------------------------------------------------------------------------//
// Copyright (c) 2022 - 2023 serial-coder: Phuwanai Thummavet ([email protected]) //
//-------------------------------------------------------------------------------------//
// For more info, please refer to my article:
// - On Medium: https://medium.com/valixconsulting/solidity-smart-contract-security-by-example-01-integer-underflow-c1147c2e507b
// - On serial-coder.com: https://www.serial-coder.com/post/solidity-smart-contract-security-by-example-01-integer-underflow/
pragma solidity 0.6.12;
import "./Dependencies.sol";
// Simplified SafeMath
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
}
contract FixedEtherVault is ReentrancyGuard {
using SafeMath for uint256;
mapping (address => uint256) private userBalances;
function deposit() external payable {
userBalances[msg.sender] = userBalances[msg.sender].add(msg.value); // FIX: Apply SafeMath
}
function withdraw(uint256 _amount) external noReentrant {
uint256 balance = getUserBalance(msg.sender);
require(balance.sub(_amount) >= 0, "Insufficient balance"); // FIX: Apply SafeMath
userBalances[msg.sender] = userBalances[msg.sender].sub(_amount); // FIX: Apply SafeMath
(bool success, ) = msg.sender.call{value: _amount}("");
require(success, "Failed to send Ether");
}
function getEtherBalance() external view returns (uint256) {
return address(this).balance;
}
function getUserBalance(address _user) public view returns (uint256) {
return userBalances[_user];
}
}