-
Notifications
You must be signed in to change notification settings - Fork 38
/
InsecureMoonToken.sol
63 lines (46 loc) · 2.28 KB
/
InsecureMoonToken.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
59
60
61
62
63
// 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-08-unexpected-ether-with-forcibly-sending-ether-e13be2c6b985
// - On serial-coder.com: https://www.serial-coder.com/post/solidity-smart-contract-security-by-example-08-unexpected-ether-with-forcibly-sending-ether/
pragma solidity 0.8.17;
contract InsecureMoonToken {
mapping (address => uint256) private userBalances;
uint256 public constant TOKEN_PRICE = 1 ether;
string public constant name = "Moon Token";
string public constant symbol = "MOON";
// The token is non-divisible
// You can buy/sell/transfer 1, 2, 3, or 46 tokens but not 33.5
uint8 public constant decimals = 0;
uint256 public totalSupply;
function buy(uint256 _amount) external payable {
require(
msg.value == _amount * TOKEN_PRICE,
"Ether submitted and Token amount to buy mismatch"
);
userBalances[msg.sender] += _amount;
totalSupply += _amount;
}
function sell(uint256 _amount) external {
require(userBalances[msg.sender] >= _amount, "Insufficient balance");
userBalances[msg.sender] -= _amount;
totalSupply -= _amount;
(bool success, ) = msg.sender.call{value: _amount * TOKEN_PRICE}("");
require(success, "Failed to send Ether");
assert(getEtherBalance() == totalSupply * TOKEN_PRICE);
}
function transfer(address _to, uint256 _amount) external {
require(_to != address(0), "_to address is not valid");
require(userBalances[msg.sender] >= _amount, "Insufficient balance");
userBalances[msg.sender] -= _amount;
userBalances[_to] += _amount;
}
function getEtherBalance() public view returns (uint256) {
return address(this).balance;
}
function getUserBalance(address _user) external view returns (uint256) {
return userBalances[_user];
}
}