-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBasicHotelManager.sol
84 lines (67 loc) · 2.91 KB
/
BasicHotelManager.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.17;
import {StringUtils} from "./StringUtils.sol";
contract BasicHotelManager {
mapping (string => string) private clientBalances;
string private roomOwner;
string private roomPrice;
function isRoomAvailable() public view returns (bool) {
return StringUtils.isEmpty(roomOwner);
}
function queryRoomPrice() external view returns (uint256) {
// default price is 500
uint256 result = 500;
if (!StringUtils.isEmpty(roomPrice)) {
result = StringUtils.stringToUint(roomPrice);
}
return result;
}
function queryClientBalance() public view returns (uint256) {
string memory varName = formulateClientBalanceVarName(tx.origin);
string memory balance = clientBalances[varName];
if (!StringUtils.isEmpty(balance)) {
return StringUtils.stringToUint(balance);
}
// initial balance
return 1000;
}
function changeRoomPrice(uint256 newPrice) external {
string memory priceS = StringUtils.uintToString(newPrice);
roomPrice = priceS;
}
function addToClientBalance(uint256 amountToAdd) external {
require(amountToAdd > 0, "The amount must be a positive value!");
string memory varName = formulateClientBalanceVarName(tx.origin);
uint256 balance = queryClientBalance();
uint256 newBalance = balance + amountToAdd;
string memory newBalanceS = StringUtils.uintToString(newBalance);
clientBalances[varName] = newBalanceS;
}
function bookRoom() external {
bool available = isRoomAvailable();
require(available, "the room must be available!");
uint256 price = this.queryRoomPrice();
deductFromClientBalance(price);
roomOwner = StringUtils.addressToHexString(tx.origin);
}
function hasReservation() external view returns (bool) {
string memory currentClient = StringUtils.addressToHexString(tx.origin);
return StringUtils.compareStrings(roomOwner, currentClient);
}
function checkout() external {
bool gotReservation = this.hasReservation();
require(gotReservation, "you must have a reservation in order to checkout!");
roomOwner = "";
}
function deductFromClientBalance(uint256 amountToDeduct) internal {
string memory varName = formulateClientBalanceVarName(tx.origin);
uint256 balance = queryClientBalance();
uint256 newBalance = balance - amountToDeduct;
require(newBalance >= 0, "The amount to deduct cannot be larger than the current balance!");
string memory newBalanceS = StringUtils.uintToString(newBalance);
clientBalances[varName] = newBalanceS;
}
function formulateClientBalanceVarName(address client) private pure returns (string memory) {
return StringUtils.addressToHexString(client);
}
}