pragma solidity ^0.4.18;
contract SimpleBank {
/** storages */
// 預金残高
mapping(address => uint) public bank;
/** events */
event Deposit(
address indexed addr, uint oldBalance, uint value, uint newBalance
);
event Withdraw(
address indexed addr, uint oldBalance, uint value, uint newBalance
);
/** methods */
// 残高確認
function getMyBalance() public view returns(uint) {
return bank[msg.sender];
}
// 預金
function deposit(uint _value) public {
address msgSender = msg.sender;
uint oldBalance = bank[msgSender];
uint newBalance = oldBalance + _value;
// オーバーフローチェック
if(
newBalance < oldBalance ||
newBalance < _value
){
// オーバーフロー発生!
string memory errmsg = "error! オーバーフロー! oldBalance:";
errmsg = _strConnect(errmsg, _uint2str(oldBalance));
errmsg = _strConnect(errmsg, ", _value:");
errmsg = _strConnect(errmsg, _uint2str(_value));
errmsg = _strConnect(errmsg, ", newBalance:");
errmsg = _strConnect(errmsg, _uint2str(newBalance));
require(false, errmsg);
}else{
// オーバーフローセーフ
bank[msgSender] = newBalance;
emit Deposit(msgSender, oldBalance, _value, newBalance);
}
}
// 出金
function withdraw(uint _value) public {
address msgSender = msg.sender;
uint oldBalance = bank[msgSender];
// 残高確認
if(oldBalance < _value){
// 残高不足
string memory errmsg = "error! 残高不足! oldBalance:";
errmsg = _strConnect(errmsg, _uint2str(oldBalance));
errmsg = _strConnect(errmsg, ", _value:");
errmsg = _strConnect(errmsg, _uint2str(_value));
require(false, errmsg);
}else{
// 残高は足りている
uint newBalance = oldBalance - _value;
bank[msgSender] = newBalance;
emit Withdraw(msgSender, oldBalance, _value, newBalance);
}
}
function _strConnect(string _str1, string _str2)
private pure returns(string)
{
bytes memory strbyte1 = bytes(_str1);
bytes memory strbyte2 = bytes(_str2);
bytes memory str = new bytes(strbyte1.length + strbyte2.length);
uint8 point = 0;
for(uint8 j = 0; j < strbyte1.length;j++){
str[point] = strbyte1[j];
point++;
}
for(uint8 k = 0; k < strbyte2.length;k++){
str[point] = strbyte2[k];
point++;
}
return string(str);
}
function _uint2str(uint i) private pure returns (string){
if (i == 0) return "0";
uint j = i;
uint length;
while (j != 0){
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint k = length - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
}