contract_name
stringlengths 1
61
| file_path
stringlengths 5
50.4k
| contract_address
stringlengths 42
42
| language
stringclasses 1
value | class_name
stringlengths 1
61
| class_code
stringlengths 4
330k
| class_documentation
stringlengths 0
29.1k
| class_documentation_type
stringclasses 6
values | func_name
stringlengths 0
62
| func_code
stringlengths 1
303k
| func_documentation
stringlengths 2
14.9k
| func_documentation_type
stringclasses 4
values | compiler_version
stringlengths 15
42
| license_type
stringclasses 14
values | swarm_source
stringlengths 0
71
| meta
dict | __index_level_0__
int64 0
60.4k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | change | function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
| /// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
8733,
8872
]
} | 9,300 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | change | function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
| /// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
9074,
9742
]
} | 9,301 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | exchange | function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
| /// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
10008,
10482
]
} | 9,302 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | updateReserve | function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
| /// @dev update token reserves from temp values | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
10536,
10610
]
} | 9,303 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | validateReserves | function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
| /// @dev validate that the tokens balances don't goes below reserves | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
10685,
10825
]
} | 9,304 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | withdrawExcessReserves | function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
| /// @dev allow admin to withraw excess tokens accumulated due to precision | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
10906,
11499
]
} | 9,305 |
|
ValueVaultProfitSharer | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x7c1c3116c99b7f8a35163331a33a09e2ebd1e862 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | name | function name() public view returns (string memory) {
return _name;
}
| /**
* @dev Returns the name of the token.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://085864682220b518f31f4a2d8935ceb8b807e3cd25dce5015ffaecd05caad3a2 | {
"func_code_index": [
902,
990
]
} | 9,306 |
ValueVaultProfitSharer | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x7c1c3116c99b7f8a35163331a33a09e2ebd1e862 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | symbol | function symbol() public view returns (string memory) {
return _symbol;
}
| /**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://085864682220b518f31f4a2d8935ceb8b807e3cd25dce5015ffaecd05caad3a2 | {
"func_code_index": [
1104,
1196
]
} | 9,307 |
ValueVaultProfitSharer | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x7c1c3116c99b7f8a35163331a33a09e2ebd1e862 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | decimals | function decimals() public view returns (uint8) {
return _decimals;
}
| /**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://085864682220b518f31f4a2d8935ceb8b807e3cd25dce5015ffaecd05caad3a2 | {
"func_code_index": [
1829,
1917
]
} | 9,308 |
ValueVaultProfitSharer | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x7c1c3116c99b7f8a35163331a33a09e2ebd1e862 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | totalSupply | function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
| /**
* @dev See {IERC20-totalSupply}.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://085864682220b518f31f4a2d8935ceb8b807e3cd25dce5015ffaecd05caad3a2 | {
"func_code_index": [
1977,
2082
]
} | 9,309 |
ValueVaultProfitSharer | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x7c1c3116c99b7f8a35163331a33a09e2ebd1e862 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
| /**
* @dev See {IERC20-balanceOf}.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://085864682220b518f31f4a2d8935ceb8b807e3cd25dce5015ffaecd05caad3a2 | {
"func_code_index": [
2140,
2264
]
} | 9,310 |
ValueVaultProfitSharer | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x7c1c3116c99b7f8a35163331a33a09e2ebd1e862 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | transfer | function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
| /**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://085864682220b518f31f4a2d8935ceb8b807e3cd25dce5015ffaecd05caad3a2 | {
"func_code_index": [
2472,
2652
]
} | 9,311 |
ValueVaultProfitSharer | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x7c1c3116c99b7f8a35163331a33a09e2ebd1e862 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | allowance | function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
| /**
* @dev See {IERC20-allowance}.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://085864682220b518f31f4a2d8935ceb8b807e3cd25dce5015ffaecd05caad3a2 | {
"func_code_index": [
2710,
2866
]
} | 9,312 |
ValueVaultProfitSharer | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x7c1c3116c99b7f8a35163331a33a09e2ebd1e862 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | approve | function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
| /**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://085864682220b518f31f4a2d8935ceb8b807e3cd25dce5015ffaecd05caad3a2 | {
"func_code_index": [
3008,
3182
]
} | 9,313 |
ValueVaultProfitSharer | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x7c1c3116c99b7f8a35163331a33a09e2ebd1e862 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | transferFrom | function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
| /**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://085864682220b518f31f4a2d8935ceb8b807e3cd25dce5015ffaecd05caad3a2 | {
"func_code_index": [
3651,
3977
]
} | 9,314 |
ValueVaultProfitSharer | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x7c1c3116c99b7f8a35163331a33a09e2ebd1e862 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | increaseAllowance | function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
| /**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://085864682220b518f31f4a2d8935ceb8b807e3cd25dce5015ffaecd05caad3a2 | {
"func_code_index": [
4381,
4604
]
} | 9,315 |
ValueVaultProfitSharer | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x7c1c3116c99b7f8a35163331a33a09e2ebd1e862 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | decreaseAllowance | function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
| /**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://085864682220b518f31f4a2d8935ceb8b807e3cd25dce5015ffaecd05caad3a2 | {
"func_code_index": [
5102,
5376
]
} | 9,316 |
ValueVaultProfitSharer | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x7c1c3116c99b7f8a35163331a33a09e2ebd1e862 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _transfer | function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| /**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://085864682220b518f31f4a2d8935ceb8b807e3cd25dce5015ffaecd05caad3a2 | {
"func_code_index": [
5861,
6405
]
} | 9,317 |
ValueVaultProfitSharer | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x7c1c3116c99b7f8a35163331a33a09e2ebd1e862 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _mint | function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
| /** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://085864682220b518f31f4a2d8935ceb8b807e3cd25dce5015ffaecd05caad3a2 | {
"func_code_index": [
6681,
7064
]
} | 9,318 |
ValueVaultProfitSharer | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x7c1c3116c99b7f8a35163331a33a09e2ebd1e862 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _burn | function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
| /**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://085864682220b518f31f4a2d8935ceb8b807e3cd25dce5015ffaecd05caad3a2 | {
"func_code_index": [
7391,
7814
]
} | 9,319 |
ValueVaultProfitSharer | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x7c1c3116c99b7f8a35163331a33a09e2ebd1e862 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _approve | function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| /**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://085864682220b518f31f4a2d8935ceb8b807e3cd25dce5015ffaecd05caad3a2 | {
"func_code_index": [
8247,
8598
]
} | 9,320 |
ValueVaultProfitSharer | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x7c1c3116c99b7f8a35163331a33a09e2ebd1e862 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _setupDecimals | function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
| /**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://085864682220b518f31f4a2d8935ceb8b807e3cd25dce5015ffaecd05caad3a2 | {
"func_code_index": [
8925,
9020
]
} | 9,321 |
ValueVaultProfitSharer | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x7c1c3116c99b7f8a35163331a33a09e2ebd1e862 | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _beforeTokenTransfer | function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
| /**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://085864682220b518f31f4a2d8935ceb8b807e3cd25dce5015ffaecd05caad3a2 | {
"func_code_index": [
9618,
9715
]
} | 9,322 |
PremiaVesting | contracts/PremiaVesting.sol | 0x4ba7c8b012b3edae910ddee79edf9e3f5b1ff68c | Solidity | PremiaVesting | contract PremiaVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The premia token
IERC20 public premia;
// The timestamp at which release ends
uint256 public endTimestamp;
// The length of the release period (Once this period is passed, amount is fully unlocked)
uint256 public releasePeriod = 365 days;
// The timestamp at which last withdrawal has been done
uint256 public lastWithdrawalTimestamp;
//////////////////////////////////////////////////
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// @param _premia The premia token
constructor(IERC20 _premia) {
premia = _premia;
endTimestamp = block.timestamp.add(releasePeriod);
lastWithdrawalTimestamp = block.timestamp;
}
//////////////////////////////////////////////////
//////////////////////////////////////////////////
//////////////////////////////////////////////////
/// @notice Withdraw portion of allocation unlocked
function withdraw() public onlyOwner {
uint256 timestamp = block.timestamp;
if (timestamp == lastWithdrawalTimestamp) return;
uint256 _lastWithdrawalTimestamp = lastWithdrawalTimestamp;
lastWithdrawalTimestamp = timestamp;
uint256 balance = premia.balanceOf(address(this));
if (timestamp >= endTimestamp) {
premia.safeTransfer(msg.sender, balance);
} else {
uint256 elapsedSinceLastWithdrawal = timestamp.sub(_lastWithdrawalTimestamp);
uint256 timeLeft = endTimestamp.sub(_lastWithdrawalTimestamp);
premia.safeTransfer(msg.sender, balance.mul(elapsedSinceLastWithdrawal).div(timeLeft));
}
}
} | /// @author Premia
/// @title Vesting contract for Premia founder allocations, releasing the allocations over the course of a year | NatSpecSingleLine | withdraw | function withdraw() public onlyOwner {
uint256 timestamp = block.timestamp;
if (timestamp == lastWithdrawalTimestamp) return;
uint256 _lastWithdrawalTimestamp = lastWithdrawalTimestamp;
lastWithdrawalTimestamp = timestamp;
uint256 balance = premia.balanceOf(address(this));
if (timestamp >= endTimestamp) {
premia.safeTransfer(msg.sender, balance);
} else {
uint256 elapsedSinceLastWithdrawal = timestamp.sub(_lastWithdrawalTimestamp);
uint256 timeLeft = endTimestamp.sub(_lastWithdrawalTimestamp);
premia.safeTransfer(msg.sender, balance.mul(elapsedSinceLastWithdrawal).div(timeLeft));
}
}
| //////////////////////////////////////////////////
//////////////////////////////////////////////////
//////////////////////////////////////////////////
/// @notice Withdraw portion of allocation unlocked | NatSpecSingleLine | v0.7.6+commit.7338295f | {
"func_code_index": [
1107,
1841
]
} | 9,323 |
||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | Ownable | contract Ownable {
address public owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
| /**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
649,
757
]
} | 9,324 |
|
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | Ownable | contract Ownable {
address public owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | _transferOwnership | function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
| /**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
895,
1073
]
} | 9,325 |
|
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | Destructible | contract Destructible is Ownable {
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() public onlyOwner {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) public onlyOwner {
selfdestruct(_recipient);
}
} | /**
* @title Destructible
* @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
*/ | NatSpecMultiLine | destroy | function destroy() public onlyOwner {
selfdestruct(owner);
}
| /**
* @dev Transfers the current balance to the owner and terminates the contract.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
133,
204
]
} | 9,326 |
|
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | giftCharacter | function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
| /**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
4573,
4792
]
} | 9,327 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | addCharacters | function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
| /**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
4948,
5073
]
} | 9,328 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | addCharacter | function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
| /**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
6886,
7041
]
} | 9,329 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | exit | function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
| /**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
7167,
8811
]
} | 9,330 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | replaceCharacter | function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
| /**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
9021,
9335
]
} | 9,331 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | triggerVolcanoEruption | function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
| /**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
9610,
11114
]
} | 9,332 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | fight | function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
| /**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
11645,
15351
]
} | 9,333 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | isValidAdversary | function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
| /*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/ | Comment | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
15508,
16383
]
} | 9,334 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | getRandomAdversary | function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
| /**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
16593,
17467
]
} | 9,335 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | generateRandomNumber | function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
| /**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
17655,
17828
]
} | 9,336 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | hitCharacter | function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
| /**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
18176,
18724
]
} | 9,337 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | findOldest | function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
| /**
* finds the oldest character
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
18776,
19043
]
} | 9,338 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | distribute | function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
| /**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
19174,
20437
]
} | 9,339 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | collectFees | function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
| /**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
20749,
20935
]
} | 9,340 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | withdraw | function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
| /**
* withdraw NDC and TPT tokens
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
20984,
21308
]
} | 9,341 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | payOut | function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
| /**
* pays out the players.
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
21355,
21599
]
} | 9,342 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | stop | function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
| /**
* pays out the players and kills the game.
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
21665,
21755
]
} | 9,343 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | distributeCastleLoot | function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
| /* @dev distributes castle loot among archers */ | Comment | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
22646,
23925
]
} | 9,344 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | sellCharacter | function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
| /**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
24111,
24974
]
} | 9,345 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | receiveApproval | function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
| /**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
25279,
27563
]
} | 9,346 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | teleportCharacter | function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
| /**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
27738,
28285
]
} | 9,347 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | protectCharacter | function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
| /**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
28419,
28552
]
} | 9,348 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | setLuckRound | function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
| /**
* set the castle loot factor (percent of the luck factor being distributed)
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
28653,
28784
]
} | 9,349 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | getCharacter | function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
| /**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
29008,
29219
]
} | 9,350 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | getCharacterIndex | function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
| /**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
29366,
29587
]
} | 9,351 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | get10Characters | function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
| /**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
29798,
30335
]
} | 9,352 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | getNumDragons | function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
| /**
* returns the number of dragons in the game
* @return the number of dragons
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
30438,
30623
]
} | 9,353 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | getNumWizards | function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
| /**
* returns the number of wizards in the game
* @return the number of wizards
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
30726,
30911
]
} | 9,354 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | getNumArchers | function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
| /**
* returns the number of archers in the game
* @return the number of archers
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
31012,
31197
]
} | 9,355 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | getNumKnights | function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
| /**
* returns the number of knights in the game
* @return the number of knights
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
31300,
31485
]
} | 9,356 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | getFees | function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
| /**
* @return the accumulated fees
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
31539,
31773
]
} | 9,357 |
|||
DragonKing | DragonKing.sol | 0x8059d8d6b6053f99be81166c9a625fa9db8bf6e2 | Solidity | DragonKing | contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
uint8 fightCount;
}
DragonKingConfig public config;
/** the neverdie token contract used to purchase protection from eruptions and fights */
ERC20 neverdieToken;
/** the teleport token contract used to send knights to the game scene */
ERC20 teleportToken;
/** the luck token contract **/
ERC20 luckToken;
/** the SKL token contract **/
ERC20 sklToken;
/** the XP token contract **/
ERC20 xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the castle loot distribution factor **/
uint8 public luckRounds = 2;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestamp of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestamp of the last castle loot distribution **/
mapping(uint32 => uint256) public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot, uint32 characterId, uint128 luckFactor);
/* initializes the contract parameter */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address luckAddress, address _configAddress) public {
nextId = 1;
teleportToken = ERC20(tptAddress);
neverdieToken = ERC20(ndcAddress);
sklToken = ERC20(sklAddress);
xperToken = ERC20(xperAddress);
luckToken = ERC20(luckAddress);
config = DragonKingConfig(_configAddress);
}
/**
* gifts one character
* @param receiver gift character owner
* @param characterType type of the character to create as a gift
*/
function giftCharacter(address receiver, uint8 characterType) payable public onlyUser {
_addCharacters(receiver, characterType);
assert(config.giftToken().transfer(receiver, config.giftTokenAmount()));
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
_addCharacters(msg.sender, characterType);
}
function _addCharacters(address receiver, uint8 characterType) internal {
uint16 amount = uint16(msg.value / config.costs(characterType));
require(
amount > 0,
"insufficient amount of ether to purchase a given type of character");
uint16 nchars = numCharacters;
require(
config.hasEnoughTokensToPurchase(receiver, characterType),
"insufficinet amount of tokens to purchase a given type of character"
);
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), receiver, uint64(now), 0);
}
}
nextId = nid + amount;
emit NewPurchase(receiver, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint16 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
require(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
if (luckToken.balanceOf(msg.sender) >= config.luckThreshold()) {
base_probability = uint16(generateRandomNumber(dice) % 100);
if (base_probability < dice) {
dice = base_probability;
}
base_probability = 0;
}
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (characters[characterID].fightCount < 3) {
characters[characterID].fightCount++;
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
} else {
cooldown[characterID] = now;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
cooldown[characterID] = now;
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
castleTreasury += totalAmount / 20; //5% into castle treasury
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 100 * 85;
} else {
amount = totalAmount / 100 * 95;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE + 1;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
if(ndcBalance > 0)
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
if(tptBalance > 0)
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
function generateLuckFactor(uint128 nonce) internal view returns(uint128 luckFactor) {
uint128 f;
luckFactor = 50;
for(uint8 i = 0; i < luckRounds; i++){
f = roll(uint128(generateRandomNumber(nonce+i*7)%1000));
if(f < luckFactor) luckFactor = f;
}
}
function roll(uint128 nonce) internal view returns(uint128) {
uint128 sum = 0;
uint128 inc = 1;
for (uint128 i = 45; i >= 3; i--) {
if (sum > nonce) {
return i;
}
sum += inc;
if (i != 35) {
inc += 1;
}
}
return 3;
}
function distributeCastleLootMulti(uint32[] characterIds) external onlyUser {
require(characterIds.length <= 50);
for(uint i = 0; i < characterIds.length; i++){
distributeCastleLoot(characterIds[i]);
}
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
require(castleTreasury > 0, "empty treasury");
Character archer = characters[characterId];
require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
if(lastCastleLootDistributionTimestamp[characterId] == 0)
require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(),
"not enough time has passed since the purchase");
else
require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
require(archer.fightCount >= 3, "need to fight 3 times");
lastCastleLootDistributionTimestamp[characterId] = now;
archer.fightCount = 0;
uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
if (luckFactor < 3) {
luckFactor = 3;
}
assert(luckFactor <= 50);
uint128 amount = castleTreasury * luckFactor / 100;
archer.value += amount;
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount, characterId, luckFactor);
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
if (characterIndex >= numCharacters || characterId != ids[characterIndex])
characterIndex = getCharacterIndex(characterId);
Character storage char = characters[characterId];
require(msg.sender == char.owner,
"only owners can sell their characters");
require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(char.purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = char.value;
numCharacters--;
replaceCharacter(characterIndex, numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
require(tokenContract == address(teleportToken), "everything is paid with teleport tokens");
bool forProtection = secondToUint32(callData) == 1 ? true : false;
uint32 id;
uint256 price;
if (!forProtection) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE ){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
} else if (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(teleportToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/**
* set the castle loot factor (percent of the luck factor being distributed)
* */
function setLuckRound(uint8 rounds) public onlyOwner{
require(rounds >= 1 && rounds <= 100);
luckRounds = rounds;
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = castleTreasury;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
function secondToUint32(bytes b) internal pure returns(uint32){
bytes32 newB;
assembly {
newB: = mload(0xc0)
}
return uint32(newB);
}
} | toUint32 | function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
| /**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://67949d9f96abb63cbad0550203e0ab8cd2695e80d6e3628f574cf82a32544f7a | {
"func_code_index": [
31935,
32096
]
} | 9,358 |
|||
Mushroom_ZapIn_V1 | contracts/Mushroom/Mushroom_ZapIn_V1.sol | 0x84b95b8a9566fcb5ca5e6aef7c39b11166fd12c4 | Solidity | Mushroom_ZapIn_V1 | contract Mushroom_ZapIn_V1 is ZapInBaseV2 {
mapping(address => bool) public approvedTargets;
event zapIn(address sender, address pool, uint256 tokensRec);
constructor(uint256 _goodwill, uint256 _affiliateSplit)
public
ZapBaseV1(_goodwill, _affiliateSplit)
{}
/**
@notice This function adds liquidity to Mushroom vaults with ETH or ERC20 tokens
@param fromToken The token used for entry (address(0) if ether)
@param amountIn The amount of fromToken to invest
@param toVault Harvest vault address
@param minMVTokens The minimum acceptable quantity vault tokens to receive. Reverts otherwise
@param intermediateToken Token to swap fromToken to before entering vault
@param swapTarget Excecution target for the swap or zap
@param swapData DEX or Zap data
@param affiliate Affiliate address
@param shouldSellEntireBalance True if amountIn is determined at execution time (i.e. contract is caller)
@return tokensReceived- Quantity of Vault tokens received
*/
function ZapIn(
address fromToken,
uint256 amountIn,
address toVault,
uint256 minMVTokens,
address intermediateToken,
address swapTarget,
bytes calldata swapData,
address affiliate,
bool shouldSellEntireBalance
) external payable stopInEmergency returns (uint256 tokensReceived) {
require(
approvedTargets[swapTarget] || swapTarget == address(0),
"Target not Authorized"
);
// get incoming tokens
uint256 toInvest =
_pullTokens(
fromToken,
amountIn,
affiliate,
true,
shouldSellEntireBalance
);
// get intermediate token
uint256 intermediateAmt =
_fillQuote(
fromToken,
intermediateToken,
toInvest,
swapTarget,
swapData
);
// Deposit to Vault
tokensReceived = _vaultDeposit(intermediateAmt, toVault, minMVTokens);
}
function _vaultDeposit(
uint256 amount,
address toVault,
uint256 minTokensRec
) internal returns (uint256 tokensReceived) {
address underlyingVaultToken = IMVault(toVault).token();
_approveToken(underlyingVaultToken, toVault);
uint256 iniVaultBal = IERC20(toVault).balanceOf(address(this));
IMVault(toVault).deposit(amount);
tokensReceived = IERC20(toVault).balanceOf(address(this)).sub(
iniVaultBal
);
require(tokensReceived >= minTokensRec, "Err: High Slippage");
IERC20(toVault).safeTransfer(msg.sender, tokensReceived);
emit zapIn(msg.sender, toVault, tokensReceived);
}
function _fillQuote(
address _fromTokenAddress,
address toToken,
uint256 _amount,
address _swapTarget,
bytes memory swapCallData
) internal returns (uint256 amtBought) {
uint256 valueToSend;
if (_fromTokenAddress == toToken) {
return _amount;
}
if (_fromTokenAddress == address(0)) {
valueToSend = _amount;
} else {
_approveToken(_fromTokenAddress, _swapTarget);
}
uint256 iniBal = _getBalance(toToken);
(bool success, ) = _swapTarget.call.value(valueToSend)(swapCallData);
require(success, "Error Swapping Tokens 1");
uint256 finalBal = _getBalance(toToken);
amtBought = finalBal.sub(iniBal);
}
function setApprovedTargets(
address[] calldata targets,
bool[] calldata isApproved
) external onlyOwner {
require(targets.length == isApproved.length, "Invalid Input length");
for (uint256 i = 0; i < targets.length; i++) {
approvedTargets[targets[i]] = isApproved[i];
}
}
} | ZapIn | function ZapIn(
address fromToken,
uint256 amountIn,
address toVault,
uint256 minMVTokens,
address intermediateToken,
address swapTarget,
bytes calldata swapData,
address affiliate,
bool shouldSellEntireBalance
) external payable stopInEmergency returns (uint256 tokensReceived) {
require(
approvedTargets[swapTarget] || swapTarget == address(0),
"Target not Authorized"
);
// get incoming tokens
uint256 toInvest =
_pullTokens(
fromToken,
amountIn,
affiliate,
true,
shouldSellEntireBalance
);
// get intermediate token
uint256 intermediateAmt =
_fillQuote(
fromToken,
intermediateToken,
toInvest,
swapTarget,
swapData
);
// Deposit to Vault
tokensReceived = _vaultDeposit(intermediateAmt, toVault, minMVTokens);
}
| /**
@notice This function adds liquidity to Mushroom vaults with ETH or ERC20 tokens
@param fromToken The token used for entry (address(0) if ether)
@param amountIn The amount of fromToken to invest
@param toVault Harvest vault address
@param minMVTokens The minimum acceptable quantity vault tokens to receive. Reverts otherwise
@param intermediateToken Token to swap fromToken to before entering vault
@param swapTarget Excecution target for the swap or zap
@param swapData DEX or Zap data
@param affiliate Affiliate address
@param shouldSellEntireBalance True if amountIn is determined at execution time (i.e. contract is caller)
@return tokensReceived- Quantity of Vault tokens received
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | GNU GPLv2 | bzzr://3ed888fd9b38624332ec59278c2938bd8fd51dd75b90b5574cf3b094568c1172 | {
"func_code_index": [
1064,
2200
]
} | 9,359 |
||
EtherMoney | EtherMoney.sol | 0x6f55a4ad49d5580ed9a03a2c4228d8c833401bca | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | totalSupply | function totalSupply() constant returns (uint256 supply) {}
| /// @return total amount of tokens | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://29dc38a3e8df1ff819cabc9d1d569851b2cb2725548b09229daf4de5de1016c6 | {
"func_code_index": [
60,
124
]
} | 9,360 |
|||
EtherMoney | EtherMoney.sol | 0x6f55a4ad49d5580ed9a03a2c4228d8c833401bca | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | balanceOf | function balanceOf(address _owner) constant returns (uint256 balance) {}
| /// @param _owner The address from which the balance will be retrieved
/// @return The balance | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://29dc38a3e8df1ff819cabc9d1d569851b2cb2725548b09229daf4de5de1016c6 | {
"func_code_index": [
232,
309
]
} | 9,361 |
|||
EtherMoney | EtherMoney.sol | 0x6f55a4ad49d5580ed9a03a2c4228d8c833401bca | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transfer | function transfer(address _to, uint256 _value) returns (bool success) {}
| /// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://29dc38a3e8df1ff819cabc9d1d569851b2cb2725548b09229daf4de5de1016c6 | {
"func_code_index": [
546,
623
]
} | 9,362 |
|||
EtherMoney | EtherMoney.sol | 0x6f55a4ad49d5580ed9a03a2c4228d8c833401bca | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transferFrom | function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
| /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://29dc38a3e8df1ff819cabc9d1d569851b2cb2725548b09229daf4de5de1016c6 | {
"func_code_index": [
946,
1042
]
} | 9,363 |
|||
EtherMoney | EtherMoney.sol | 0x6f55a4ad49d5580ed9a03a2c4228d8c833401bca | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | approve | function approve(address _spender, uint256 _value) returns (bool success) {}
| /// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://29dc38a3e8df1ff819cabc9d1d569851b2cb2725548b09229daf4de5de1016c6 | {
"func_code_index": [
1326,
1407
]
} | 9,364 |
|||
EtherMoney | EtherMoney.sol | 0x6f55a4ad49d5580ed9a03a2c4228d8c833401bca | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | allowance | function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
| /// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://29dc38a3e8df1ff819cabc9d1d569851b2cb2725548b09229daf4de5de1016c6 | {
"func_code_index": [
1615,
1712
]
} | 9,365 |
|||
EtherMoney | EtherMoney.sol | 0x6f55a4ad49d5580ed9a03a2c4228d8c833401bca | Solidity | EtherMoney | contract EtherMoney is StandardToken { // CHANGE THIS. Update the contract name.
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
uint256 public unitsOneEthCanBuy;
uint256 public totalEthInWei;
address public fundsWallet;
// This is a constructor function
// which means the following function name has to match the contract name declared above
function EtherMoney() {
balances[msg.sender] = 30000000000000000000000000000;
totalSupply = 30000000000000000000000000000;
name = "EtherMoney";
decimals = 18;
symbol = "EMN";
unitsOneEthCanBuy = 500000000;
fundsWallet = msg.sender;
}
function() public payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain
//Transfer ether to fundsWallet
fundsWallet.transfer(msg.value);
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | EtherMoney | function EtherMoney() {
balances[msg.sender] = 30000000000000000000000000000;
totalSupply = 30000000000000000000000000000;
name = "EtherMoney";
decimals = 18;
symbol = "EMN";
unitsOneEthCanBuy = 500000000;
fundsWallet = msg.sender;
}
| // This is a constructor function
// which means the following function name has to match the contract name declared above | LineComment | v0.4.24+commit.e67f0147 | bzzr://29dc38a3e8df1ff819cabc9d1d569851b2cb2725548b09229daf4de5de1016c6 | {
"func_code_index": [
856,
1350
]
} | 9,366 |
|||
EtherMoney | EtherMoney.sol | 0x6f55a4ad49d5580ed9a03a2c4228d8c833401bca | Solidity | EtherMoney | contract EtherMoney is StandardToken { // CHANGE THIS. Update the contract name.
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
uint256 public unitsOneEthCanBuy;
uint256 public totalEthInWei;
address public fundsWallet;
// This is a constructor function
// which means the following function name has to match the contract name declared above
function EtherMoney() {
balances[msg.sender] = 30000000000000000000000000000;
totalSupply = 30000000000000000000000000000;
name = "EtherMoney";
decimals = 18;
symbol = "EMN";
unitsOneEthCanBuy = 500000000;
fundsWallet = msg.sender;
}
function() public payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain
//Transfer ether to fundsWallet
fundsWallet.transfer(msg.value);
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | approveAndCall | function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
| /* Approves and then calls the receiving contract */ | Comment | v0.4.24+commit.e67f0147 | bzzr://29dc38a3e8df1ff819cabc9d1d569851b2cb2725548b09229daf4de5de1016c6 | {
"func_code_index": [
1951,
2756
]
} | 9,367 |
|||
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | ERC20 | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | name | function name() public view virtual override returns (string memory) {
return _name;
}
| /**
* @dev Returns the name of the token.
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
779,
884
]
} | 9,368 |
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | ERC20 | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | symbol | function symbol() public view virtual override returns (string memory) {
return _symbol;
}
| /**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
998,
1107
]
} | 9,369 |
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | ERC20 | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | decimals | function decimals() public view virtual override returns (uint8) {
return 18;
}
| /**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
1741,
1839
]
} | 9,370 |
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | ERC20 | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | totalSupply | function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
| /**
* @dev See {IERC20-totalSupply}.
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
1899,
2012
]
} | 9,371 |
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | ERC20 | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
| /**
* @dev See {IERC20-balanceOf}.
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
2070,
2202
]
} | 9,372 |
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | ERC20 | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | transfer | function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
| /**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
2410,
2590
]
} | 9,373 |
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | ERC20 | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | allowance | function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
| /**
* @dev See {IERC20-allowance}.
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
2648,
2804
]
} | 9,374 |
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | ERC20 | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | approve | function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
| /**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
2946,
3120
]
} | 9,375 |
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | ERC20 | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | transferFrom | function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
| /**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
3597,
4024
]
} | 9,376 |
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | ERC20 | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | increaseAllowance | function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
| /**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
4428,
4648
]
} | 9,377 |
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | ERC20 | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | decreaseAllowance | function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
| /**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
5146,
5528
]
} | 9,378 |
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | ERC20 | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _transfer | function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
| /**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
6013,
6622
]
} | 9,379 |
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | ERC20 | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _mint | function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
| /** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
6899,
7242
]
} | 9,380 |
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | ERC20 | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _burn | function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
| /**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
7570,
8069
]
} | 9,381 |
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | ERC20 | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _approve | function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| /**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
8502,
8853
]
} | 9,382 |
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | ERC20 | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _beforeTokenTransfer | function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
| /**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
9451,
9548
]
} | 9,383 |
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | MilionTenshi | contract MilionTenshi is ERC20, Owned {
uint256 public minSupply;
address public beneficiary;
bool public feesEnabled;
mapping(address => bool) public isExcludedFromFee;
event MinSupplyUpdated(uint256 oldAmount, uint256 newAmount);
event BeneficiaryUpdated(address oldBeneficiary, address newBeneficiary);
event FeesEnabledUpdated(bool enabled);
event ExcludedFromFeeUpdated(address account, bool excluded);
constructor() ERC20("MilionTenshi", "MSHI") {
minSupply = 100000000 ether;
uint256 totalSupply = 1000000000000 ether;
feesEnabled = false;
_mint(_msgSender(), totalSupply);
isExcludedFromFee[msg.sender] = true;
isExcludedFromFee[0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = true;
beneficiary = msg.sender;
}
/**
* @dev if fees are enabled, subtract 2.25% fee and send it to beneficiary
* @dev after a certain threshold, try to swap collected fees automatically
* @dev if automatic swap fails (or beneficiary does not implement swapTokens function) transfer should still succeed
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
require(
recipient != address(this),
"Cannot send tokens to token contract"
);
if (
!feesEnabled ||
isExcludedFromFee[sender] ||
isExcludedFromFee[recipient]
) {
ERC20._transfer(sender, recipient, amount);
return;
}
// burn tokens if min supply not reached yet
uint256 burnedFee = calculateFee(amount, 25);
if (totalSupply() - burnedFee >= minSupply) {
_burn(sender, burnedFee);
} else {
burnedFee = 0;
}
uint256 transferFee = calculateFee(amount, 200);
ERC20._transfer(sender, beneficiary, transferFee);
ERC20._transfer(sender, recipient, amount - transferFee - burnedFee);
}
function calculateFee(uint256 _amount, uint256 _fee)
public
pure
returns (uint256)
{
return (_amount * _fee) / 10000;
}
/**
* @notice allows to burn tokens from own balance
* @dev only allows burning tokens until minimum supply is reached
* @param value amount of tokens to burn
*/
function burn(uint256 value) public {
_burn(_msgSender(), value);
require(totalSupply() >= minSupply, "total supply exceeds min supply");
}
/**
* @notice sets minimum supply of the token
* @dev only callable by owner
* @param _newMinSupply new minimum supply
*/
function setMinSupply(uint256 _newMinSupply) public onlyOwner {
emit MinSupplyUpdated(minSupply, _newMinSupply);
minSupply = _newMinSupply;
}
/**
* @notice sets recipient of transfer fee
* @dev only callable by owner
* @param _newBeneficiary new beneficiary
*/
function setBeneficiary(address _newBeneficiary) public onlyOwner {
setExcludeFromFee(_newBeneficiary, true);
emit BeneficiaryUpdated(beneficiary, _newBeneficiary);
beneficiary = _newBeneficiary;
}
/**
* @notice sets whether account collects fees on token transfer
* @dev only callable by owner
* @param _enabled bool whether fees are enabled
*/
function setFeesEnabled(bool _enabled) public onlyOwner {
emit FeesEnabledUpdated(_enabled);
feesEnabled = _enabled;
}
/**
* @notice adds or removes an account that is exempt from fee collection
* @dev only callable by owner
* @param _account account to modify
* @param _excluded new value
*/
function setExcludeFromFee(address _account, bool _excluded)
public
onlyOwner
{
isExcludedFromFee[_account] = _excluded;
emit ExcludedFromFeeUpdated(_account, _excluded);
}
} | _transfer | function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
require(
recipient != address(this),
"Cannot send tokens to token contract"
);
if (
!feesEnabled ||
isExcludedFromFee[sender] ||
isExcludedFromFee[recipient]
) {
ERC20._transfer(sender, recipient, amount);
return;
}
// burn tokens if min supply not reached yet
uint256 burnedFee = calculateFee(amount, 25);
if (totalSupply() - burnedFee >= minSupply) {
_burn(sender, burnedFee);
} else {
burnedFee = 0;
}
uint256 transferFee = calculateFee(amount, 200);
ERC20._transfer(sender, beneficiary, transferFee);
ERC20._transfer(sender, recipient, amount - transferFee - burnedFee);
}
| /**
* @dev if fees are enabled, subtract 2.25% fee and send it to beneficiary
* @dev after a certain threshold, try to swap collected fees automatically
* @dev if automatic swap fails (or beneficiary does not implement swapTokens function) transfer should still succeed
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
1140,
2084
]
} | 9,384 |
||
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | MilionTenshi | contract MilionTenshi is ERC20, Owned {
uint256 public minSupply;
address public beneficiary;
bool public feesEnabled;
mapping(address => bool) public isExcludedFromFee;
event MinSupplyUpdated(uint256 oldAmount, uint256 newAmount);
event BeneficiaryUpdated(address oldBeneficiary, address newBeneficiary);
event FeesEnabledUpdated(bool enabled);
event ExcludedFromFeeUpdated(address account, bool excluded);
constructor() ERC20("MilionTenshi", "MSHI") {
minSupply = 100000000 ether;
uint256 totalSupply = 1000000000000 ether;
feesEnabled = false;
_mint(_msgSender(), totalSupply);
isExcludedFromFee[msg.sender] = true;
isExcludedFromFee[0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = true;
beneficiary = msg.sender;
}
/**
* @dev if fees are enabled, subtract 2.25% fee and send it to beneficiary
* @dev after a certain threshold, try to swap collected fees automatically
* @dev if automatic swap fails (or beneficiary does not implement swapTokens function) transfer should still succeed
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
require(
recipient != address(this),
"Cannot send tokens to token contract"
);
if (
!feesEnabled ||
isExcludedFromFee[sender] ||
isExcludedFromFee[recipient]
) {
ERC20._transfer(sender, recipient, amount);
return;
}
// burn tokens if min supply not reached yet
uint256 burnedFee = calculateFee(amount, 25);
if (totalSupply() - burnedFee >= minSupply) {
_burn(sender, burnedFee);
} else {
burnedFee = 0;
}
uint256 transferFee = calculateFee(amount, 200);
ERC20._transfer(sender, beneficiary, transferFee);
ERC20._transfer(sender, recipient, amount - transferFee - burnedFee);
}
function calculateFee(uint256 _amount, uint256 _fee)
public
pure
returns (uint256)
{
return (_amount * _fee) / 10000;
}
/**
* @notice allows to burn tokens from own balance
* @dev only allows burning tokens until minimum supply is reached
* @param value amount of tokens to burn
*/
function burn(uint256 value) public {
_burn(_msgSender(), value);
require(totalSupply() >= minSupply, "total supply exceeds min supply");
}
/**
* @notice sets minimum supply of the token
* @dev only callable by owner
* @param _newMinSupply new minimum supply
*/
function setMinSupply(uint256 _newMinSupply) public onlyOwner {
emit MinSupplyUpdated(minSupply, _newMinSupply);
minSupply = _newMinSupply;
}
/**
* @notice sets recipient of transfer fee
* @dev only callable by owner
* @param _newBeneficiary new beneficiary
*/
function setBeneficiary(address _newBeneficiary) public onlyOwner {
setExcludeFromFee(_newBeneficiary, true);
emit BeneficiaryUpdated(beneficiary, _newBeneficiary);
beneficiary = _newBeneficiary;
}
/**
* @notice sets whether account collects fees on token transfer
* @dev only callable by owner
* @param _enabled bool whether fees are enabled
*/
function setFeesEnabled(bool _enabled) public onlyOwner {
emit FeesEnabledUpdated(_enabled);
feesEnabled = _enabled;
}
/**
* @notice adds or removes an account that is exempt from fee collection
* @dev only callable by owner
* @param _account account to modify
* @param _excluded new value
*/
function setExcludeFromFee(address _account, bool _excluded)
public
onlyOwner
{
isExcludedFromFee[_account] = _excluded;
emit ExcludedFromFeeUpdated(_account, _excluded);
}
} | burn | function burn(uint256 value) public {
_burn(_msgSender(), value);
require(totalSupply() >= minSupply, "total supply exceeds min supply");
}
| /**
* @notice allows to burn tokens from own balance
* @dev only allows burning tokens until minimum supply is reached
* @param value amount of tokens to burn
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
2451,
2618
]
} | 9,385 |
||
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | MilionTenshi | contract MilionTenshi is ERC20, Owned {
uint256 public minSupply;
address public beneficiary;
bool public feesEnabled;
mapping(address => bool) public isExcludedFromFee;
event MinSupplyUpdated(uint256 oldAmount, uint256 newAmount);
event BeneficiaryUpdated(address oldBeneficiary, address newBeneficiary);
event FeesEnabledUpdated(bool enabled);
event ExcludedFromFeeUpdated(address account, bool excluded);
constructor() ERC20("MilionTenshi", "MSHI") {
minSupply = 100000000 ether;
uint256 totalSupply = 1000000000000 ether;
feesEnabled = false;
_mint(_msgSender(), totalSupply);
isExcludedFromFee[msg.sender] = true;
isExcludedFromFee[0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = true;
beneficiary = msg.sender;
}
/**
* @dev if fees are enabled, subtract 2.25% fee and send it to beneficiary
* @dev after a certain threshold, try to swap collected fees automatically
* @dev if automatic swap fails (or beneficiary does not implement swapTokens function) transfer should still succeed
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
require(
recipient != address(this),
"Cannot send tokens to token contract"
);
if (
!feesEnabled ||
isExcludedFromFee[sender] ||
isExcludedFromFee[recipient]
) {
ERC20._transfer(sender, recipient, amount);
return;
}
// burn tokens if min supply not reached yet
uint256 burnedFee = calculateFee(amount, 25);
if (totalSupply() - burnedFee >= minSupply) {
_burn(sender, burnedFee);
} else {
burnedFee = 0;
}
uint256 transferFee = calculateFee(amount, 200);
ERC20._transfer(sender, beneficiary, transferFee);
ERC20._transfer(sender, recipient, amount - transferFee - burnedFee);
}
function calculateFee(uint256 _amount, uint256 _fee)
public
pure
returns (uint256)
{
return (_amount * _fee) / 10000;
}
/**
* @notice allows to burn tokens from own balance
* @dev only allows burning tokens until minimum supply is reached
* @param value amount of tokens to burn
*/
function burn(uint256 value) public {
_burn(_msgSender(), value);
require(totalSupply() >= minSupply, "total supply exceeds min supply");
}
/**
* @notice sets minimum supply of the token
* @dev only callable by owner
* @param _newMinSupply new minimum supply
*/
function setMinSupply(uint256 _newMinSupply) public onlyOwner {
emit MinSupplyUpdated(minSupply, _newMinSupply);
minSupply = _newMinSupply;
}
/**
* @notice sets recipient of transfer fee
* @dev only callable by owner
* @param _newBeneficiary new beneficiary
*/
function setBeneficiary(address _newBeneficiary) public onlyOwner {
setExcludeFromFee(_newBeneficiary, true);
emit BeneficiaryUpdated(beneficiary, _newBeneficiary);
beneficiary = _newBeneficiary;
}
/**
* @notice sets whether account collects fees on token transfer
* @dev only callable by owner
* @param _enabled bool whether fees are enabled
*/
function setFeesEnabled(bool _enabled) public onlyOwner {
emit FeesEnabledUpdated(_enabled);
feesEnabled = _enabled;
}
/**
* @notice adds or removes an account that is exempt from fee collection
* @dev only callable by owner
* @param _account account to modify
* @param _excluded new value
*/
function setExcludeFromFee(address _account, bool _excluded)
public
onlyOwner
{
isExcludedFromFee[_account] = _excluded;
emit ExcludedFromFeeUpdated(_account, _excluded);
}
} | setMinSupply | function setMinSupply(uint256 _newMinSupply) public onlyOwner {
emit MinSupplyUpdated(minSupply, _newMinSupply);
minSupply = _newMinSupply;
}
| /**
* @notice sets minimum supply of the token
* @dev only callable by owner
* @param _newMinSupply new minimum supply
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
2772,
2941
]
} | 9,386 |
||
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | MilionTenshi | contract MilionTenshi is ERC20, Owned {
uint256 public minSupply;
address public beneficiary;
bool public feesEnabled;
mapping(address => bool) public isExcludedFromFee;
event MinSupplyUpdated(uint256 oldAmount, uint256 newAmount);
event BeneficiaryUpdated(address oldBeneficiary, address newBeneficiary);
event FeesEnabledUpdated(bool enabled);
event ExcludedFromFeeUpdated(address account, bool excluded);
constructor() ERC20("MilionTenshi", "MSHI") {
minSupply = 100000000 ether;
uint256 totalSupply = 1000000000000 ether;
feesEnabled = false;
_mint(_msgSender(), totalSupply);
isExcludedFromFee[msg.sender] = true;
isExcludedFromFee[0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = true;
beneficiary = msg.sender;
}
/**
* @dev if fees are enabled, subtract 2.25% fee and send it to beneficiary
* @dev after a certain threshold, try to swap collected fees automatically
* @dev if automatic swap fails (or beneficiary does not implement swapTokens function) transfer should still succeed
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
require(
recipient != address(this),
"Cannot send tokens to token contract"
);
if (
!feesEnabled ||
isExcludedFromFee[sender] ||
isExcludedFromFee[recipient]
) {
ERC20._transfer(sender, recipient, amount);
return;
}
// burn tokens if min supply not reached yet
uint256 burnedFee = calculateFee(amount, 25);
if (totalSupply() - burnedFee >= minSupply) {
_burn(sender, burnedFee);
} else {
burnedFee = 0;
}
uint256 transferFee = calculateFee(amount, 200);
ERC20._transfer(sender, beneficiary, transferFee);
ERC20._transfer(sender, recipient, amount - transferFee - burnedFee);
}
function calculateFee(uint256 _amount, uint256 _fee)
public
pure
returns (uint256)
{
return (_amount * _fee) / 10000;
}
/**
* @notice allows to burn tokens from own balance
* @dev only allows burning tokens until minimum supply is reached
* @param value amount of tokens to burn
*/
function burn(uint256 value) public {
_burn(_msgSender(), value);
require(totalSupply() >= minSupply, "total supply exceeds min supply");
}
/**
* @notice sets minimum supply of the token
* @dev only callable by owner
* @param _newMinSupply new minimum supply
*/
function setMinSupply(uint256 _newMinSupply) public onlyOwner {
emit MinSupplyUpdated(minSupply, _newMinSupply);
minSupply = _newMinSupply;
}
/**
* @notice sets recipient of transfer fee
* @dev only callable by owner
* @param _newBeneficiary new beneficiary
*/
function setBeneficiary(address _newBeneficiary) public onlyOwner {
setExcludeFromFee(_newBeneficiary, true);
emit BeneficiaryUpdated(beneficiary, _newBeneficiary);
beneficiary = _newBeneficiary;
}
/**
* @notice sets whether account collects fees on token transfer
* @dev only callable by owner
* @param _enabled bool whether fees are enabled
*/
function setFeesEnabled(bool _enabled) public onlyOwner {
emit FeesEnabledUpdated(_enabled);
feesEnabled = _enabled;
}
/**
* @notice adds or removes an account that is exempt from fee collection
* @dev only callable by owner
* @param _account account to modify
* @param _excluded new value
*/
function setExcludeFromFee(address _account, bool _excluded)
public
onlyOwner
{
isExcludedFromFee[_account] = _excluded;
emit ExcludedFromFeeUpdated(_account, _excluded);
}
} | setBeneficiary | function setBeneficiary(address _newBeneficiary) public onlyOwner {
setExcludeFromFee(_newBeneficiary, true);
emit BeneficiaryUpdated(beneficiary, _newBeneficiary);
beneficiary = _newBeneficiary;
}
| /**
* @notice sets recipient of transfer fee
* @dev only callable by owner
* @param _newBeneficiary new beneficiary
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
3097,
3331
]
} | 9,387 |
||
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | MilionTenshi | contract MilionTenshi is ERC20, Owned {
uint256 public minSupply;
address public beneficiary;
bool public feesEnabled;
mapping(address => bool) public isExcludedFromFee;
event MinSupplyUpdated(uint256 oldAmount, uint256 newAmount);
event BeneficiaryUpdated(address oldBeneficiary, address newBeneficiary);
event FeesEnabledUpdated(bool enabled);
event ExcludedFromFeeUpdated(address account, bool excluded);
constructor() ERC20("MilionTenshi", "MSHI") {
minSupply = 100000000 ether;
uint256 totalSupply = 1000000000000 ether;
feesEnabled = false;
_mint(_msgSender(), totalSupply);
isExcludedFromFee[msg.sender] = true;
isExcludedFromFee[0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = true;
beneficiary = msg.sender;
}
/**
* @dev if fees are enabled, subtract 2.25% fee and send it to beneficiary
* @dev after a certain threshold, try to swap collected fees automatically
* @dev if automatic swap fails (or beneficiary does not implement swapTokens function) transfer should still succeed
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
require(
recipient != address(this),
"Cannot send tokens to token contract"
);
if (
!feesEnabled ||
isExcludedFromFee[sender] ||
isExcludedFromFee[recipient]
) {
ERC20._transfer(sender, recipient, amount);
return;
}
// burn tokens if min supply not reached yet
uint256 burnedFee = calculateFee(amount, 25);
if (totalSupply() - burnedFee >= minSupply) {
_burn(sender, burnedFee);
} else {
burnedFee = 0;
}
uint256 transferFee = calculateFee(amount, 200);
ERC20._transfer(sender, beneficiary, transferFee);
ERC20._transfer(sender, recipient, amount - transferFee - burnedFee);
}
function calculateFee(uint256 _amount, uint256 _fee)
public
pure
returns (uint256)
{
return (_amount * _fee) / 10000;
}
/**
* @notice allows to burn tokens from own balance
* @dev only allows burning tokens until minimum supply is reached
* @param value amount of tokens to burn
*/
function burn(uint256 value) public {
_burn(_msgSender(), value);
require(totalSupply() >= minSupply, "total supply exceeds min supply");
}
/**
* @notice sets minimum supply of the token
* @dev only callable by owner
* @param _newMinSupply new minimum supply
*/
function setMinSupply(uint256 _newMinSupply) public onlyOwner {
emit MinSupplyUpdated(minSupply, _newMinSupply);
minSupply = _newMinSupply;
}
/**
* @notice sets recipient of transfer fee
* @dev only callable by owner
* @param _newBeneficiary new beneficiary
*/
function setBeneficiary(address _newBeneficiary) public onlyOwner {
setExcludeFromFee(_newBeneficiary, true);
emit BeneficiaryUpdated(beneficiary, _newBeneficiary);
beneficiary = _newBeneficiary;
}
/**
* @notice sets whether account collects fees on token transfer
* @dev only callable by owner
* @param _enabled bool whether fees are enabled
*/
function setFeesEnabled(bool _enabled) public onlyOwner {
emit FeesEnabledUpdated(_enabled);
feesEnabled = _enabled;
}
/**
* @notice adds or removes an account that is exempt from fee collection
* @dev only callable by owner
* @param _account account to modify
* @param _excluded new value
*/
function setExcludeFromFee(address _account, bool _excluded)
public
onlyOwner
{
isExcludedFromFee[_account] = _excluded;
emit ExcludedFromFeeUpdated(_account, _excluded);
}
} | setFeesEnabled | function setFeesEnabled(bool _enabled) public onlyOwner {
emit FeesEnabledUpdated(_enabled);
feesEnabled = _enabled;
}
| /**
* @notice sets whether account collects fees on token transfer
* @dev only callable by owner
* @param _enabled bool whether fees are enabled
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
3511,
3657
]
} | 9,388 |
||
MilionTenshi | @openzeppelin/contracts/token/ERC20/IERC20.sol | 0x73e87a637bf2ae2565cc07514cf2cf1aaf2fba5a | Solidity | MilionTenshi | contract MilionTenshi is ERC20, Owned {
uint256 public minSupply;
address public beneficiary;
bool public feesEnabled;
mapping(address => bool) public isExcludedFromFee;
event MinSupplyUpdated(uint256 oldAmount, uint256 newAmount);
event BeneficiaryUpdated(address oldBeneficiary, address newBeneficiary);
event FeesEnabledUpdated(bool enabled);
event ExcludedFromFeeUpdated(address account, bool excluded);
constructor() ERC20("MilionTenshi", "MSHI") {
minSupply = 100000000 ether;
uint256 totalSupply = 1000000000000 ether;
feesEnabled = false;
_mint(_msgSender(), totalSupply);
isExcludedFromFee[msg.sender] = true;
isExcludedFromFee[0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = true;
beneficiary = msg.sender;
}
/**
* @dev if fees are enabled, subtract 2.25% fee and send it to beneficiary
* @dev after a certain threshold, try to swap collected fees automatically
* @dev if automatic swap fails (or beneficiary does not implement swapTokens function) transfer should still succeed
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
require(
recipient != address(this),
"Cannot send tokens to token contract"
);
if (
!feesEnabled ||
isExcludedFromFee[sender] ||
isExcludedFromFee[recipient]
) {
ERC20._transfer(sender, recipient, amount);
return;
}
// burn tokens if min supply not reached yet
uint256 burnedFee = calculateFee(amount, 25);
if (totalSupply() - burnedFee >= minSupply) {
_burn(sender, burnedFee);
} else {
burnedFee = 0;
}
uint256 transferFee = calculateFee(amount, 200);
ERC20._transfer(sender, beneficiary, transferFee);
ERC20._transfer(sender, recipient, amount - transferFee - burnedFee);
}
function calculateFee(uint256 _amount, uint256 _fee)
public
pure
returns (uint256)
{
return (_amount * _fee) / 10000;
}
/**
* @notice allows to burn tokens from own balance
* @dev only allows burning tokens until minimum supply is reached
* @param value amount of tokens to burn
*/
function burn(uint256 value) public {
_burn(_msgSender(), value);
require(totalSupply() >= minSupply, "total supply exceeds min supply");
}
/**
* @notice sets minimum supply of the token
* @dev only callable by owner
* @param _newMinSupply new minimum supply
*/
function setMinSupply(uint256 _newMinSupply) public onlyOwner {
emit MinSupplyUpdated(minSupply, _newMinSupply);
minSupply = _newMinSupply;
}
/**
* @notice sets recipient of transfer fee
* @dev only callable by owner
* @param _newBeneficiary new beneficiary
*/
function setBeneficiary(address _newBeneficiary) public onlyOwner {
setExcludeFromFee(_newBeneficiary, true);
emit BeneficiaryUpdated(beneficiary, _newBeneficiary);
beneficiary = _newBeneficiary;
}
/**
* @notice sets whether account collects fees on token transfer
* @dev only callable by owner
* @param _enabled bool whether fees are enabled
*/
function setFeesEnabled(bool _enabled) public onlyOwner {
emit FeesEnabledUpdated(_enabled);
feesEnabled = _enabled;
}
/**
* @notice adds or removes an account that is exempt from fee collection
* @dev only callable by owner
* @param _account account to modify
* @param _excluded new value
*/
function setExcludeFromFee(address _account, bool _excluded)
public
onlyOwner
{
isExcludedFromFee[_account] = _excluded;
emit ExcludedFromFeeUpdated(_account, _excluded);
}
} | setExcludeFromFee | function setExcludeFromFee(address _account, bool _excluded)
public
onlyOwner
{
isExcludedFromFee[_account] = _excluded;
emit ExcludedFromFeeUpdated(_account, _excluded);
}
| /**
* @notice adds or removes an account that is exempt from fee collection
* @dev only callable by owner
* @param _account account to modify
* @param _excluded new value
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | None | ipfs://4429f4ad8cb268d65d861cba8496deb3c1952fca23f8aeb8c5ec4c88600ce5cc | {
"func_code_index": [
3869,
4092
]
} | 9,389 |
||
UltraToken | contracts/Ultra_IEO.sol | 0xd13c7342e1ef687c5ad21b27c2b65d772cab5c8c | Solidity | UltraToken | contract UltraToken is ERC20Pausable, Ownable {
using SafeMath for uint256;
// using Math for uint256;
string private _name = "Ultra Token";
string private _symbol = "UOS";
uint8 private _decimals = 4; // the token precision on UOS mainnet is 4, can be adjusted there as necessary.
/* 0--------------------------------------> time in month(30 days)
* ^ ^ ^
* | | |
* deploy start ... end
* 10.00% ... 20.00% adds up to 100.00%
*/
uint256 private _deployTime; // the deployment time of the contract
uint256 private _month = 30 days; // time unit
struct VestingContract {
uint256[] basisPoints; // the basis points array of each vesting. The last one won't matter, cause we give the remainder to the user at last, but the sum will be validated against 10000
uint256 startMonth; // the index of the month at the beginning of which the first vesting is available
uint256 endMonth; // the index of the month at the beginning of which the last vesting is available; _endMonth = _startMonth + _basisPoints.length -1;
}
struct BuyerInfo {
uint256 total; // the total number of tokens purchased by the buyer
uint256 claimed; // the number of tokens has been claimed so far
string contractName; // with what contract the buyer purchased the tokens
}
mapping (string => VestingContract) private _vestingContracts;
mapping (address => BuyerInfo) private _buyerInfos;
mapping (address => string) private _keys; // ethereum to eos public key mapping
mapping (address => bool) private _updateApproval; // whether allow an account to update its registerred eos key
constructor() public {
_mint(address(this), uint256(1000000000).mul(10**uint256(_decimals))); // mint all tokens and send to the contract, 1,000,000,000 UOS;
_deployTime = block.timestamp;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function deployTime() public view returns (uint256) {
return _deployTime;
}
function buyerInformation() public view returns (uint256, uint256, string memory) {
BuyerInfo storage buyerInfo = _buyerInfos[msg.sender];
return (buyerInfo.total, buyerInfo.claimed, buyerInfo.contractName );
}
function nextVestingDate() public view returns (uint256) {
BuyerInfo storage buyerInfo = _buyerInfos[msg.sender];
require(buyerInfo.total > 0, "Buyer does not exist");
VestingContract storage vestingContract = _vestingContracts[buyerInfo.contractName];
uint256 currentMonth = block.timestamp.sub(_deployTime).div(_month);
if(currentMonth < vestingContract.startMonth) {
return _deployTime.add(vestingContract.startMonth.mul(_month));
} else if(currentMonth >= vestingContract.endMonth) {
return _deployTime.add(vestingContract.endMonth.mul(_month));
} else {
return _deployTime.add(currentMonth.add(1).mul(_month));
}
}
event SetVestingContract(string contractName, uint256[] basisPoints, uint256 startMonth);
function setVestingContract(string memory contractName, uint256[] memory basisPoints, uint256 startMonth) public onlyOwner whenNotPaused returns (bool) {
VestingContract storage vestingContract = _vestingContracts[contractName];
require(vestingContract.basisPoints.length == 0, "can't change an existing contract");
uint256 totalBPs = 0;
for(uint256 i = 0; i < basisPoints.length; i++) {
totalBPs = totalBPs.add(basisPoints[i]);
}
require(totalBPs == 10000, "invalid basis points array"); // this also ensures array length is not zero
vestingContract.basisPoints = basisPoints;
vestingContract.startMonth = startMonth;
vestingContract.endMonth = startMonth.add(basisPoints.length).sub(1);
emit SetVestingContract(contractName, basisPoints, startMonth);
return true;
}
event ImportBalance(address[] buyers, uint256[] tokens, string contractName);
// import balance for a group of user with a specific contract terms
function importBalance(address[] memory buyers, uint256[] memory tokens, string memory contractName) public onlyOwner whenNotPaused returns (bool) {
require(buyers.length == tokens.length, "buyers and balances mismatch");
VestingContract storage vestingContract = _vestingContracts[contractName];
require(vestingContract.basisPoints.length > 0, "contract does not exist");
for(uint256 i = 0; i < buyers.length; i++) {
require(tokens[i] > 0, "cannot import zero balance");
BuyerInfo storage buyerInfo = _buyerInfos[buyers[i]];
require(buyerInfo.total == 0, "have already imported balance for this buyer");
buyerInfo.total = tokens[i];
buyerInfo.contractName = contractName;
}
emit ImportBalance(buyers, tokens, contractName);
return true;
}
event Claim(address indexed claimer, uint256 claimed);
function claim() public whenNotPaused returns (bool) {
uint256 canClaim = claimableToken();
require(canClaim > 0, "No token is available to claim");
_buyerInfos[msg.sender].claimed = _buyerInfos[msg.sender].claimed.add(canClaim);
_transfer(address(this), msg.sender, canClaim);
emit Claim(msg.sender, canClaim);
return true;
}
// the number of token can be claimed by the msg.sender at the moment
function claimableToken() public view returns (uint256) {
BuyerInfo storage buyerInfo = _buyerInfos[msg.sender];
if(buyerInfo.claimed < buyerInfo.total) {
VestingContract storage vestingContract = _vestingContracts[buyerInfo.contractName];
uint256 currentMonth = block.timestamp.sub(_deployTime).div(_month);
if(currentMonth < vestingContract.startMonth) {
return uint256(0);
}
if(currentMonth >= vestingContract.endMonth) { // vest the unclaimed token all at once so there's no remainder
return buyerInfo.total.sub(buyerInfo.claimed);
} else {
uint256 claimableIndex = currentMonth.sub(vestingContract.startMonth);
uint256 canClaim = 0;
for(uint256 i = 0; i <= claimableIndex; ++i) {
canClaim = canClaim.add(vestingContract.basisPoints[i]);
}
return canClaim.mul(buyerInfo.total).div(10000).sub(buyerInfo.claimed);
}
}
return uint256(0);
}
event SetKey(address indexed buyer, string EOSKey);
function _register(string memory EOSKey) internal {
require(bytes(EOSKey).length > 0 && bytes(EOSKey).length <= 64, "EOS public key length should be less than 64 characters");
_keys[msg.sender] = EOSKey;
emit SetKey(msg.sender, EOSKey);
}
function register(string memory EOSKey) public whenNotPaused returns (bool) {
_register(EOSKey);
return true;
}
function keyOf() public view returns (string memory) {
return _keys[msg.sender];
}
event SetUpdateApproval(address indexed buyer, bool isApproved);
function setUpdateApproval(address buyer, bool isApproved) public onlyOwner returns (bool) {
require(balanceOf(buyer) > 0 || _buyerInfos[buyer].total > 0, "This account has no token"); // allowance will not be considered
_updateApproval[buyer] = isApproved;
emit SetUpdateApproval(buyer, isApproved);
return true;
}
function updateApproved() public view returns (bool) {
return _updateApproval[msg.sender];
}
function update(string memory EOSKey) public returns (bool) {
require(_updateApproval[msg.sender], "Need approval from ultra after contract is frozen");
_register(EOSKey);
return true;
}
} | //import 'openzeppelin-solidity/contracts/math/Math.sol'; | LineComment | importBalance | function importBalance(address[] memory buyers, uint256[] memory tokens, string memory contractName) public onlyOwner whenNotPaused returns (bool) {
require(buyers.length == tokens.length, "buyers and balances mismatch");
VestingContract storage vestingContract = _vestingContracts[contractName];
require(vestingContract.basisPoints.length > 0, "contract does not exist");
for(uint256 i = 0; i < buyers.length; i++) {
require(tokens[i] > 0, "cannot import zero balance");
BuyerInfo storage buyerInfo = _buyerInfos[buyers[i]];
require(buyerInfo.total == 0, "have already imported balance for this buyer");
buyerInfo.total = tokens[i];
buyerInfo.contractName = contractName;
}
emit ImportBalance(buyers, tokens, contractName);
return true;
}
| // import balance for a group of user with a specific contract terms | LineComment | v0.5.9+commit.e560f70d | bzzr://241dbe33cfdd9eba72a7f16c4cc2eebb12bea4ec9690917c5ee82c6d8b04f9c1 | {
"func_code_index": [
4724,
5616
]
} | 9,390 |
|
UltraToken | contracts/Ultra_IEO.sol | 0xd13c7342e1ef687c5ad21b27c2b65d772cab5c8c | Solidity | UltraToken | contract UltraToken is ERC20Pausable, Ownable {
using SafeMath for uint256;
// using Math for uint256;
string private _name = "Ultra Token";
string private _symbol = "UOS";
uint8 private _decimals = 4; // the token precision on UOS mainnet is 4, can be adjusted there as necessary.
/* 0--------------------------------------> time in month(30 days)
* ^ ^ ^
* | | |
* deploy start ... end
* 10.00% ... 20.00% adds up to 100.00%
*/
uint256 private _deployTime; // the deployment time of the contract
uint256 private _month = 30 days; // time unit
struct VestingContract {
uint256[] basisPoints; // the basis points array of each vesting. The last one won't matter, cause we give the remainder to the user at last, but the sum will be validated against 10000
uint256 startMonth; // the index of the month at the beginning of which the first vesting is available
uint256 endMonth; // the index of the month at the beginning of which the last vesting is available; _endMonth = _startMonth + _basisPoints.length -1;
}
struct BuyerInfo {
uint256 total; // the total number of tokens purchased by the buyer
uint256 claimed; // the number of tokens has been claimed so far
string contractName; // with what contract the buyer purchased the tokens
}
mapping (string => VestingContract) private _vestingContracts;
mapping (address => BuyerInfo) private _buyerInfos;
mapping (address => string) private _keys; // ethereum to eos public key mapping
mapping (address => bool) private _updateApproval; // whether allow an account to update its registerred eos key
constructor() public {
_mint(address(this), uint256(1000000000).mul(10**uint256(_decimals))); // mint all tokens and send to the contract, 1,000,000,000 UOS;
_deployTime = block.timestamp;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function deployTime() public view returns (uint256) {
return _deployTime;
}
function buyerInformation() public view returns (uint256, uint256, string memory) {
BuyerInfo storage buyerInfo = _buyerInfos[msg.sender];
return (buyerInfo.total, buyerInfo.claimed, buyerInfo.contractName );
}
function nextVestingDate() public view returns (uint256) {
BuyerInfo storage buyerInfo = _buyerInfos[msg.sender];
require(buyerInfo.total > 0, "Buyer does not exist");
VestingContract storage vestingContract = _vestingContracts[buyerInfo.contractName];
uint256 currentMonth = block.timestamp.sub(_deployTime).div(_month);
if(currentMonth < vestingContract.startMonth) {
return _deployTime.add(vestingContract.startMonth.mul(_month));
} else if(currentMonth >= vestingContract.endMonth) {
return _deployTime.add(vestingContract.endMonth.mul(_month));
} else {
return _deployTime.add(currentMonth.add(1).mul(_month));
}
}
event SetVestingContract(string contractName, uint256[] basisPoints, uint256 startMonth);
function setVestingContract(string memory contractName, uint256[] memory basisPoints, uint256 startMonth) public onlyOwner whenNotPaused returns (bool) {
VestingContract storage vestingContract = _vestingContracts[contractName];
require(vestingContract.basisPoints.length == 0, "can't change an existing contract");
uint256 totalBPs = 0;
for(uint256 i = 0; i < basisPoints.length; i++) {
totalBPs = totalBPs.add(basisPoints[i]);
}
require(totalBPs == 10000, "invalid basis points array"); // this also ensures array length is not zero
vestingContract.basisPoints = basisPoints;
vestingContract.startMonth = startMonth;
vestingContract.endMonth = startMonth.add(basisPoints.length).sub(1);
emit SetVestingContract(contractName, basisPoints, startMonth);
return true;
}
event ImportBalance(address[] buyers, uint256[] tokens, string contractName);
// import balance for a group of user with a specific contract terms
function importBalance(address[] memory buyers, uint256[] memory tokens, string memory contractName) public onlyOwner whenNotPaused returns (bool) {
require(buyers.length == tokens.length, "buyers and balances mismatch");
VestingContract storage vestingContract = _vestingContracts[contractName];
require(vestingContract.basisPoints.length > 0, "contract does not exist");
for(uint256 i = 0; i < buyers.length; i++) {
require(tokens[i] > 0, "cannot import zero balance");
BuyerInfo storage buyerInfo = _buyerInfos[buyers[i]];
require(buyerInfo.total == 0, "have already imported balance for this buyer");
buyerInfo.total = tokens[i];
buyerInfo.contractName = contractName;
}
emit ImportBalance(buyers, tokens, contractName);
return true;
}
event Claim(address indexed claimer, uint256 claimed);
function claim() public whenNotPaused returns (bool) {
uint256 canClaim = claimableToken();
require(canClaim > 0, "No token is available to claim");
_buyerInfos[msg.sender].claimed = _buyerInfos[msg.sender].claimed.add(canClaim);
_transfer(address(this), msg.sender, canClaim);
emit Claim(msg.sender, canClaim);
return true;
}
// the number of token can be claimed by the msg.sender at the moment
function claimableToken() public view returns (uint256) {
BuyerInfo storage buyerInfo = _buyerInfos[msg.sender];
if(buyerInfo.claimed < buyerInfo.total) {
VestingContract storage vestingContract = _vestingContracts[buyerInfo.contractName];
uint256 currentMonth = block.timestamp.sub(_deployTime).div(_month);
if(currentMonth < vestingContract.startMonth) {
return uint256(0);
}
if(currentMonth >= vestingContract.endMonth) { // vest the unclaimed token all at once so there's no remainder
return buyerInfo.total.sub(buyerInfo.claimed);
} else {
uint256 claimableIndex = currentMonth.sub(vestingContract.startMonth);
uint256 canClaim = 0;
for(uint256 i = 0; i <= claimableIndex; ++i) {
canClaim = canClaim.add(vestingContract.basisPoints[i]);
}
return canClaim.mul(buyerInfo.total).div(10000).sub(buyerInfo.claimed);
}
}
return uint256(0);
}
event SetKey(address indexed buyer, string EOSKey);
function _register(string memory EOSKey) internal {
require(bytes(EOSKey).length > 0 && bytes(EOSKey).length <= 64, "EOS public key length should be less than 64 characters");
_keys[msg.sender] = EOSKey;
emit SetKey(msg.sender, EOSKey);
}
function register(string memory EOSKey) public whenNotPaused returns (bool) {
_register(EOSKey);
return true;
}
function keyOf() public view returns (string memory) {
return _keys[msg.sender];
}
event SetUpdateApproval(address indexed buyer, bool isApproved);
function setUpdateApproval(address buyer, bool isApproved) public onlyOwner returns (bool) {
require(balanceOf(buyer) > 0 || _buyerInfos[buyer].total > 0, "This account has no token"); // allowance will not be considered
_updateApproval[buyer] = isApproved;
emit SetUpdateApproval(buyer, isApproved);
return true;
}
function updateApproved() public view returns (bool) {
return _updateApproval[msg.sender];
}
function update(string memory EOSKey) public returns (bool) {
require(_updateApproval[msg.sender], "Need approval from ultra after contract is frozen");
_register(EOSKey);
return true;
}
} | //import 'openzeppelin-solidity/contracts/math/Math.sol'; | LineComment | claimableToken | function claimableToken() public view returns (uint256) {
BuyerInfo storage buyerInfo = _buyerInfos[msg.sender];
if(buyerInfo.claimed < buyerInfo.total) {
VestingContract storage vestingContract = _vestingContracts[buyerInfo.contractName];
uint256 currentMonth = block.timestamp.sub(_deployTime).div(_month);
if(currentMonth < vestingContract.startMonth) {
return uint256(0);
}
if(currentMonth >= vestingContract.endMonth) { // vest the unclaimed token all at once so there's no remainder
return buyerInfo.total.sub(buyerInfo.claimed);
} else {
uint256 claimableIndex = currentMonth.sub(vestingContract.startMonth);
uint256 canClaim = 0;
for(uint256 i = 0; i <= claimableIndex; ++i) {
canClaim = canClaim.add(vestingContract.basisPoints[i]);
}
return canClaim.mul(buyerInfo.total).div(10000).sub(buyerInfo.claimed);
}
}
return uint256(0);
}
| // the number of token can be claimed by the msg.sender at the moment | LineComment | v0.5.9+commit.e560f70d | bzzr://241dbe33cfdd9eba72a7f16c4cc2eebb12bea4ec9690917c5ee82c6d8b04f9c1 | {
"func_code_index": [
6163,
7298
]
} | 9,391 |
|
FavorUSD | BurnableTokenWithBounds.sol | 0xe59d7e8bdc197aaa626e154020e149a14faca03b | Solidity | BurnableTokenWithBounds | abstract contract BurnableTokenWithBounds is ReclaimerToken {
/**
* @dev Emitted when `value` tokens are burnt from one account (`burner`)
* @param burner address which burned tokens
* @param value amount of tokens burned
*/
event Burn(address indexed burner, uint256 value);
/**
* @dev Emitted when new burn bounds were set
* @param newMin new minimum burn amount
* @param newMax new maximum burn amount
* @notice `newMin` should never be greater than `newMax`
*/
event SetBurnBounds(uint256 newMin, uint256 newMax);
/**
* @dev Destroys `amount` tokens from `msg.sender`, reducing the
* total supply.
* @param amount amount of tokens to burn
*
* Emits a {Transfer} event with `to` set to the zero address.
* Emits a {Burn} event with `burner` set to `msg.sender`
*
* Requirements
*
* - `msg.sender` must have at least `amount` tokens.
*
*/
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
/**
* @dev Change the minimum and maximum amount that can be burned at once.
* Burning may be disabled by setting both to 0 (this will not be done
* under normal operation, but we can't add checks to disallow it without
* losing a lot of flexibility since burning could also be as good as disabled
* by setting the minimum extremely high, and we don't want to lock
* in any particular cap for the minimum)
* @param _min minimum amount that can be burned at once
* @param _max maximum amount that can be burned at once
*/
function setBurnBounds(uint256 _min, uint256 _max) external onlyOwner {
require(_min <= _max, "BurnableTokenWithBounds: min > max");
burnMin = _min;
burnMax = _max;
emit SetBurnBounds(_min, _max);
}
/**
* @dev Checks if amount is within allowed burn bounds and
* destroys `amount` tokens from `account`, reducing the
* total supply.
* @param account account to burn tokens for
* @param amount amount of tokens to burn
*
* Emits a {Burn} event
*/
function _burn(address account, uint256 amount) internal virtual override {
require(amount >= burnMin, "BurnableTokenWithBounds: below min burn bound");
require(amount <= burnMax, "BurnableTokenWithBounds: exceeds max burn bound");
super._burn(account, amount);
emit Burn(account, amount);
}
} | /**
* @title BurnableTokenWithBounds
* @dev Burning functions as redeeming money from the system.
* The platform will keep track of who burns coins,
* and will send them back the equivalent amount of money (rounded down to the nearest cent).
*/ | NatSpecMultiLine | burn | function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
| /**
* @dev Destroys `amount` tokens from `msg.sender`, reducing the
* total supply.
* @param amount amount of tokens to burn
*
* Emits a {Transfer} event with `to` set to the zero address.
* Emits a {Burn} event with `burner` set to `msg.sender`
*
* Requirements
*
* - `msg.sender` must have at least `amount` tokens.
*
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | ipfs://ab27100e8b3558a4e8d3f0d334f675339a375af40333a549acb1b2f03ffab0a0 | {
"func_code_index": [
968,
1053
]
} | 9,392 |
FavorUSD | BurnableTokenWithBounds.sol | 0xe59d7e8bdc197aaa626e154020e149a14faca03b | Solidity | BurnableTokenWithBounds | abstract contract BurnableTokenWithBounds is ReclaimerToken {
/**
* @dev Emitted when `value` tokens are burnt from one account (`burner`)
* @param burner address which burned tokens
* @param value amount of tokens burned
*/
event Burn(address indexed burner, uint256 value);
/**
* @dev Emitted when new burn bounds were set
* @param newMin new minimum burn amount
* @param newMax new maximum burn amount
* @notice `newMin` should never be greater than `newMax`
*/
event SetBurnBounds(uint256 newMin, uint256 newMax);
/**
* @dev Destroys `amount` tokens from `msg.sender`, reducing the
* total supply.
* @param amount amount of tokens to burn
*
* Emits a {Transfer} event with `to` set to the zero address.
* Emits a {Burn} event with `burner` set to `msg.sender`
*
* Requirements
*
* - `msg.sender` must have at least `amount` tokens.
*
*/
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
/**
* @dev Change the minimum and maximum amount that can be burned at once.
* Burning may be disabled by setting both to 0 (this will not be done
* under normal operation, but we can't add checks to disallow it without
* losing a lot of flexibility since burning could also be as good as disabled
* by setting the minimum extremely high, and we don't want to lock
* in any particular cap for the minimum)
* @param _min minimum amount that can be burned at once
* @param _max maximum amount that can be burned at once
*/
function setBurnBounds(uint256 _min, uint256 _max) external onlyOwner {
require(_min <= _max, "BurnableTokenWithBounds: min > max");
burnMin = _min;
burnMax = _max;
emit SetBurnBounds(_min, _max);
}
/**
* @dev Checks if amount is within allowed burn bounds and
* destroys `amount` tokens from `account`, reducing the
* total supply.
* @param account account to burn tokens for
* @param amount amount of tokens to burn
*
* Emits a {Burn} event
*/
function _burn(address account, uint256 amount) internal virtual override {
require(amount >= burnMin, "BurnableTokenWithBounds: below min burn bound");
require(amount <= burnMax, "BurnableTokenWithBounds: exceeds max burn bound");
super._burn(account, amount);
emit Burn(account, amount);
}
} | /**
* @title BurnableTokenWithBounds
* @dev Burning functions as redeeming money from the system.
* The platform will keep track of who burns coins,
* and will send them back the equivalent amount of money (rounded down to the nearest cent).
*/ | NatSpecMultiLine | setBurnBounds | function setBurnBounds(uint256 _min, uint256 _max) external onlyOwner {
require(_min <= _max, "BurnableTokenWithBounds: min > max");
burnMin = _min;
burnMax = _max;
emit SetBurnBounds(_min, _max);
}
| /**
* @dev Change the minimum and maximum amount that can be burned at once.
* Burning may be disabled by setting both to 0 (this will not be done
* under normal operation, but we can't add checks to disallow it without
* losing a lot of flexibility since burning could also be as good as disabled
* by setting the minimum extremely high, and we don't want to lock
* in any particular cap for the minimum)
* @param _min minimum amount that can be burned at once
* @param _max maximum amount that can be burned at once
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | ipfs://ab27100e8b3558a4e8d3f0d334f675339a375af40333a549acb1b2f03ffab0a0 | {
"func_code_index": [
1625,
1863
]
} | 9,393 |
FavorUSD | BurnableTokenWithBounds.sol | 0xe59d7e8bdc197aaa626e154020e149a14faca03b | Solidity | BurnableTokenWithBounds | abstract contract BurnableTokenWithBounds is ReclaimerToken {
/**
* @dev Emitted when `value` tokens are burnt from one account (`burner`)
* @param burner address which burned tokens
* @param value amount of tokens burned
*/
event Burn(address indexed burner, uint256 value);
/**
* @dev Emitted when new burn bounds were set
* @param newMin new minimum burn amount
* @param newMax new maximum burn amount
* @notice `newMin` should never be greater than `newMax`
*/
event SetBurnBounds(uint256 newMin, uint256 newMax);
/**
* @dev Destroys `amount` tokens from `msg.sender`, reducing the
* total supply.
* @param amount amount of tokens to burn
*
* Emits a {Transfer} event with `to` set to the zero address.
* Emits a {Burn} event with `burner` set to `msg.sender`
*
* Requirements
*
* - `msg.sender` must have at least `amount` tokens.
*
*/
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
/**
* @dev Change the minimum and maximum amount that can be burned at once.
* Burning may be disabled by setting both to 0 (this will not be done
* under normal operation, but we can't add checks to disallow it without
* losing a lot of flexibility since burning could also be as good as disabled
* by setting the minimum extremely high, and we don't want to lock
* in any particular cap for the minimum)
* @param _min minimum amount that can be burned at once
* @param _max maximum amount that can be burned at once
*/
function setBurnBounds(uint256 _min, uint256 _max) external onlyOwner {
require(_min <= _max, "BurnableTokenWithBounds: min > max");
burnMin = _min;
burnMax = _max;
emit SetBurnBounds(_min, _max);
}
/**
* @dev Checks if amount is within allowed burn bounds and
* destroys `amount` tokens from `account`, reducing the
* total supply.
* @param account account to burn tokens for
* @param amount amount of tokens to burn
*
* Emits a {Burn} event
*/
function _burn(address account, uint256 amount) internal virtual override {
require(amount >= burnMin, "BurnableTokenWithBounds: below min burn bound");
require(amount <= burnMax, "BurnableTokenWithBounds: exceeds max burn bound");
super._burn(account, amount);
emit Burn(account, amount);
}
} | /**
* @title BurnableTokenWithBounds
* @dev Burning functions as redeeming money from the system.
* The platform will keep track of who burns coins,
* and will send them back the equivalent amount of money (rounded down to the nearest cent).
*/ | NatSpecMultiLine | _burn | function _burn(address account, uint256 amount) internal virtual override {
require(amount >= burnMin, "BurnableTokenWithBounds: below min burn bound");
require(amount <= burnMax, "BurnableTokenWithBounds: exceeds max burn bound");
super._burn(account, amount);
emit Burn(account, amount);
}
| /**
* @dev Checks if amount is within allowed burn bounds and
* destroys `amount` tokens from `account`, reducing the
* total supply.
* @param account account to burn tokens for
* @param amount amount of tokens to burn
*
* Emits a {Burn} event
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | MIT | ipfs://ab27100e8b3558a4e8d3f0d334f675339a375af40333a549acb1b2f03ffab0a0 | {
"func_code_index": [
2156,
2488
]
} | 9,394 |
Minings | J\contracts\Minings(MININGS).sol | 0xd108fc421d7e22819ef3307903ee5950fd716415 | Solidity | Minings | contract Minings is ERC20 {
string public constant name = "Minings";
string public constant symbol = "MININGS";
uint8 public constant decimals = 18;
uint256 public constant initialSupply = 100000000000 * (10 ** uint256(decimals));
constructor() public {
super._mint(msg.sender, initialSupply);
owner = msg.sender;
}
//ownership
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0), "Already owner");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
//pausable
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused, "Paused by owner");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused, "Not paused now");
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
//freezable
event Frozen(address target);
event Unfrozen(address target);
mapping(address => bool) internal freezes;
modifier whenNotFrozen() {
require(!freezes[msg.sender], "Sender account is locked.");
_;
}
function freeze(address _target) public onlyOwner {
freezes[_target] = true;
emit Frozen(_target);
}
function unfreeze(address _target) public onlyOwner {
freezes[_target] = false;
emit Unfrozen(_target);
}
function isFrozen(address _target) public view returns (bool) {
return freezes[_target];
}
function transfer(
address _to,
uint256 _value
)
public
whenNotFrozen
whenNotPaused
returns (bool)
{
releaseLock(msg.sender);
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
require(!freezes[_from], "From account is locked.");
releaseLock(_from);
return super.transferFrom(_from, _to, _value);
}
//mintable
event Mint(address indexed to, uint256 amount);
function mint(
address _to,
uint256 _amount
)
public
onlyOwner
returns (bool)
{
super._mint(_to, _amount);
emit Mint(_to, _amount);
return true;
}
//burnable
event Burn(address indexed burner, uint256 value);
function burn(address _who, uint256 _value) public onlyOwner {
require(_value <= super.balanceOf(_who), "Balance is too small.");
_burn(_who, _value);
emit Burn(_who, _value);
}
//lockable
struct LockInfo {
uint256 releaseTime;
uint256 balance;
}
mapping(address => LockInfo[]) internal lockInfo;
event Lock(address indexed holder, uint256 value, uint256 releaseTime);
event Unlock(address indexed holder, uint256 value);
function balanceOf(address _holder) public view returns (uint256 balance) {
uint256 lockedBalance = 0;
for(uint256 i = 0; i < lockInfo[_holder].length ; i++ ) {
lockedBalance = lockedBalance.add(lockInfo[_holder][i].balance);
}
return super.balanceOf(_holder).add(lockedBalance);
}
function releaseLock(address _holder) internal {
for(uint256 i = 0; i < lockInfo[_holder].length ; i++ ) {
if (lockInfo[_holder][i].releaseTime <= now) {
_balances[_holder] = _balances[_holder].add(lockInfo[_holder][i].balance);
emit Unlock(_holder, lockInfo[_holder][i].balance);
lockInfo[_holder][i].balance = 0;
if (i != lockInfo[_holder].length - 1) {
lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1];
i--;
}
lockInfo[_holder].length--;
}
}
}
function lockCount(address _holder) public view returns (uint256) {
return lockInfo[_holder].length;
}
function lockState(address _holder, uint256 _idx) public view returns (uint256, uint256) {
return (lockInfo[_holder][_idx].releaseTime, lockInfo[_holder][_idx].balance);
}
function lock(address _holder, uint256 _amount, uint256 _releaseTime) public onlyOwner {
require(super.balanceOf(_holder) >= _amount, "Balance is too small.");
_balances[_holder] = _balances[_holder].sub(_amount);
lockInfo[_holder].push(
LockInfo(_releaseTime, _amount)
);
emit Lock(_holder, _amount, _releaseTime);
}
function lockAfter(address _holder, uint256 _amount, uint256 _afterTime) public onlyOwner {
require(super.balanceOf(_holder) >= _amount, "Balance is too small.");
_balances[_holder] = _balances[_holder].sub(_amount);
lockInfo[_holder].push(
LockInfo(now + _afterTime, _amount)
);
emit Lock(_holder, _amount, now + _afterTime);
}
function unlock(address _holder, uint256 i) public onlyOwner {
require(i < lockInfo[_holder].length, "No lock information.");
_balances[_holder] = _balances[_holder].add(lockInfo[_holder][i].balance);
emit Unlock(_holder, lockInfo[_holder][i].balance);
lockInfo[_holder][i].balance = 0;
if (i != lockInfo[_holder].length - 1) {
lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1];
}
lockInfo[_holder].length--;
}
function transferWithLock(address _to, uint256 _value, uint256 _releaseTime) public onlyOwner returns (bool) {
require(_to != address(0), "wrong address");
require(_value <= super.balanceOf(owner), "Not enough balance");
_balances[owner] = _balances[owner].sub(_value);
lockInfo[_to].push(
LockInfo(_releaseTime, _value)
);
emit Transfer(owner, _to, _value);
emit Lock(_to, _value, _releaseTime);
return true;
}
function transferWithLockAfter(address _to, uint256 _value, uint256 _afterTime) public onlyOwner returns (bool) {
require(_to != address(0), "wrong address");
require(_value <= super.balanceOf(owner), "Not enough balance");
_balances[owner] = _balances[owner].sub(_value);
lockInfo[_to].push(
LockInfo(now + _afterTime, _value)
);
emit Transfer(owner, _to, _value);
emit Lock(_to, _value, now + _afterTime);
return true;
}
function currentTime() public view returns (uint256) {
return now;
}
function afterTime(uint256 _value) public view returns (uint256) {
return now + _value;
}
//airdrop
mapping (address => uint256) public airDropHistory;
event AirDrop(address _receiver, uint256 _amount);
function dropToken(address[] memory receivers, uint256[] memory values) onlyOwner public {
require(receivers.length != 0);
require(receivers.length == values.length);
for (uint256 i = 0; i < receivers.length; i++) {
address receiver = receivers[i];
uint256 amount = values[i];
transfer(receiver, amount);
airDropHistory[receiver] += amount;
emit AirDrop(receiver, amount);
}
}
} | renounceOwnership | function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
| /**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/ | NatSpecMultiLine | v0.5.8+commit.23d335f2 | MIT | bzzr://4a464ec22eebac100e03dd18189f807780d2bc6e01e39e81d8fa202c76d761ed | {
"func_code_index": [
960,
1089
]
} | 9,395 |
||
Minings | J\contracts\Minings(MININGS).sol | 0xd108fc421d7e22819ef3307903ee5950fd716415 | Solidity | Minings | contract Minings is ERC20 {
string public constant name = "Minings";
string public constant symbol = "MININGS";
uint8 public constant decimals = 18;
uint256 public constant initialSupply = 100000000000 * (10 ** uint256(decimals));
constructor() public {
super._mint(msg.sender, initialSupply);
owner = msg.sender;
}
//ownership
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0), "Already owner");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
//pausable
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused, "Paused by owner");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused, "Not paused now");
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
//freezable
event Frozen(address target);
event Unfrozen(address target);
mapping(address => bool) internal freezes;
modifier whenNotFrozen() {
require(!freezes[msg.sender], "Sender account is locked.");
_;
}
function freeze(address _target) public onlyOwner {
freezes[_target] = true;
emit Frozen(_target);
}
function unfreeze(address _target) public onlyOwner {
freezes[_target] = false;
emit Unfrozen(_target);
}
function isFrozen(address _target) public view returns (bool) {
return freezes[_target];
}
function transfer(
address _to,
uint256 _value
)
public
whenNotFrozen
whenNotPaused
returns (bool)
{
releaseLock(msg.sender);
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
require(!freezes[_from], "From account is locked.");
releaseLock(_from);
return super.transferFrom(_from, _to, _value);
}
//mintable
event Mint(address indexed to, uint256 amount);
function mint(
address _to,
uint256 _amount
)
public
onlyOwner
returns (bool)
{
super._mint(_to, _amount);
emit Mint(_to, _amount);
return true;
}
//burnable
event Burn(address indexed burner, uint256 value);
function burn(address _who, uint256 _value) public onlyOwner {
require(_value <= super.balanceOf(_who), "Balance is too small.");
_burn(_who, _value);
emit Burn(_who, _value);
}
//lockable
struct LockInfo {
uint256 releaseTime;
uint256 balance;
}
mapping(address => LockInfo[]) internal lockInfo;
event Lock(address indexed holder, uint256 value, uint256 releaseTime);
event Unlock(address indexed holder, uint256 value);
function balanceOf(address _holder) public view returns (uint256 balance) {
uint256 lockedBalance = 0;
for(uint256 i = 0; i < lockInfo[_holder].length ; i++ ) {
lockedBalance = lockedBalance.add(lockInfo[_holder][i].balance);
}
return super.balanceOf(_holder).add(lockedBalance);
}
function releaseLock(address _holder) internal {
for(uint256 i = 0; i < lockInfo[_holder].length ; i++ ) {
if (lockInfo[_holder][i].releaseTime <= now) {
_balances[_holder] = _balances[_holder].add(lockInfo[_holder][i].balance);
emit Unlock(_holder, lockInfo[_holder][i].balance);
lockInfo[_holder][i].balance = 0;
if (i != lockInfo[_holder].length - 1) {
lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1];
i--;
}
lockInfo[_holder].length--;
}
}
}
function lockCount(address _holder) public view returns (uint256) {
return lockInfo[_holder].length;
}
function lockState(address _holder, uint256 _idx) public view returns (uint256, uint256) {
return (lockInfo[_holder][_idx].releaseTime, lockInfo[_holder][_idx].balance);
}
function lock(address _holder, uint256 _amount, uint256 _releaseTime) public onlyOwner {
require(super.balanceOf(_holder) >= _amount, "Balance is too small.");
_balances[_holder] = _balances[_holder].sub(_amount);
lockInfo[_holder].push(
LockInfo(_releaseTime, _amount)
);
emit Lock(_holder, _amount, _releaseTime);
}
function lockAfter(address _holder, uint256 _amount, uint256 _afterTime) public onlyOwner {
require(super.balanceOf(_holder) >= _amount, "Balance is too small.");
_balances[_holder] = _balances[_holder].sub(_amount);
lockInfo[_holder].push(
LockInfo(now + _afterTime, _amount)
);
emit Lock(_holder, _amount, now + _afterTime);
}
function unlock(address _holder, uint256 i) public onlyOwner {
require(i < lockInfo[_holder].length, "No lock information.");
_balances[_holder] = _balances[_holder].add(lockInfo[_holder][i].balance);
emit Unlock(_holder, lockInfo[_holder][i].balance);
lockInfo[_holder][i].balance = 0;
if (i != lockInfo[_holder].length - 1) {
lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1];
}
lockInfo[_holder].length--;
}
function transferWithLock(address _to, uint256 _value, uint256 _releaseTime) public onlyOwner returns (bool) {
require(_to != address(0), "wrong address");
require(_value <= super.balanceOf(owner), "Not enough balance");
_balances[owner] = _balances[owner].sub(_value);
lockInfo[_to].push(
LockInfo(_releaseTime, _value)
);
emit Transfer(owner, _to, _value);
emit Lock(_to, _value, _releaseTime);
return true;
}
function transferWithLockAfter(address _to, uint256 _value, uint256 _afterTime) public onlyOwner returns (bool) {
require(_to != address(0), "wrong address");
require(_value <= super.balanceOf(owner), "Not enough balance");
_balances[owner] = _balances[owner].sub(_value);
lockInfo[_to].push(
LockInfo(now + _afterTime, _value)
);
emit Transfer(owner, _to, _value);
emit Lock(_to, _value, now + _afterTime);
return true;
}
function currentTime() public view returns (uint256) {
return now;
}
function afterTime(uint256 _value) public view returns (uint256) {
return now + _value;
}
//airdrop
mapping (address => uint256) public airDropHistory;
event AirDrop(address _receiver, uint256 _amount);
function dropToken(address[] memory receivers, uint256[] memory values) onlyOwner public {
require(receivers.length != 0);
require(receivers.length == values.length);
for (uint256 i = 0; i < receivers.length; i++) {
address receiver = receivers[i];
uint256 amount = values[i];
transfer(receiver, amount);
airDropHistory[receiver] += amount;
emit AirDrop(receiver, amount);
}
}
} | transferOwnership | function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
| /**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.5.8+commit.23d335f2 | MIT | bzzr://4a464ec22eebac100e03dd18189f807780d2bc6e01e39e81d8fa202c76d761ed | {
"func_code_index": [
1254,
1370
]
} | 9,396 |
||
Minings | J\contracts\Minings(MININGS).sol | 0xd108fc421d7e22819ef3307903ee5950fd716415 | Solidity | Minings | contract Minings is ERC20 {
string public constant name = "Minings";
string public constant symbol = "MININGS";
uint8 public constant decimals = 18;
uint256 public constant initialSupply = 100000000000 * (10 ** uint256(decimals));
constructor() public {
super._mint(msg.sender, initialSupply);
owner = msg.sender;
}
//ownership
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0), "Already owner");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
//pausable
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused, "Paused by owner");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused, "Not paused now");
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
//freezable
event Frozen(address target);
event Unfrozen(address target);
mapping(address => bool) internal freezes;
modifier whenNotFrozen() {
require(!freezes[msg.sender], "Sender account is locked.");
_;
}
function freeze(address _target) public onlyOwner {
freezes[_target] = true;
emit Frozen(_target);
}
function unfreeze(address _target) public onlyOwner {
freezes[_target] = false;
emit Unfrozen(_target);
}
function isFrozen(address _target) public view returns (bool) {
return freezes[_target];
}
function transfer(
address _to,
uint256 _value
)
public
whenNotFrozen
whenNotPaused
returns (bool)
{
releaseLock(msg.sender);
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
require(!freezes[_from], "From account is locked.");
releaseLock(_from);
return super.transferFrom(_from, _to, _value);
}
//mintable
event Mint(address indexed to, uint256 amount);
function mint(
address _to,
uint256 _amount
)
public
onlyOwner
returns (bool)
{
super._mint(_to, _amount);
emit Mint(_to, _amount);
return true;
}
//burnable
event Burn(address indexed burner, uint256 value);
function burn(address _who, uint256 _value) public onlyOwner {
require(_value <= super.balanceOf(_who), "Balance is too small.");
_burn(_who, _value);
emit Burn(_who, _value);
}
//lockable
struct LockInfo {
uint256 releaseTime;
uint256 balance;
}
mapping(address => LockInfo[]) internal lockInfo;
event Lock(address indexed holder, uint256 value, uint256 releaseTime);
event Unlock(address indexed holder, uint256 value);
function balanceOf(address _holder) public view returns (uint256 balance) {
uint256 lockedBalance = 0;
for(uint256 i = 0; i < lockInfo[_holder].length ; i++ ) {
lockedBalance = lockedBalance.add(lockInfo[_holder][i].balance);
}
return super.balanceOf(_holder).add(lockedBalance);
}
function releaseLock(address _holder) internal {
for(uint256 i = 0; i < lockInfo[_holder].length ; i++ ) {
if (lockInfo[_holder][i].releaseTime <= now) {
_balances[_holder] = _balances[_holder].add(lockInfo[_holder][i].balance);
emit Unlock(_holder, lockInfo[_holder][i].balance);
lockInfo[_holder][i].balance = 0;
if (i != lockInfo[_holder].length - 1) {
lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1];
i--;
}
lockInfo[_holder].length--;
}
}
}
function lockCount(address _holder) public view returns (uint256) {
return lockInfo[_holder].length;
}
function lockState(address _holder, uint256 _idx) public view returns (uint256, uint256) {
return (lockInfo[_holder][_idx].releaseTime, lockInfo[_holder][_idx].balance);
}
function lock(address _holder, uint256 _amount, uint256 _releaseTime) public onlyOwner {
require(super.balanceOf(_holder) >= _amount, "Balance is too small.");
_balances[_holder] = _balances[_holder].sub(_amount);
lockInfo[_holder].push(
LockInfo(_releaseTime, _amount)
);
emit Lock(_holder, _amount, _releaseTime);
}
function lockAfter(address _holder, uint256 _amount, uint256 _afterTime) public onlyOwner {
require(super.balanceOf(_holder) >= _amount, "Balance is too small.");
_balances[_holder] = _balances[_holder].sub(_amount);
lockInfo[_holder].push(
LockInfo(now + _afterTime, _amount)
);
emit Lock(_holder, _amount, now + _afterTime);
}
function unlock(address _holder, uint256 i) public onlyOwner {
require(i < lockInfo[_holder].length, "No lock information.");
_balances[_holder] = _balances[_holder].add(lockInfo[_holder][i].balance);
emit Unlock(_holder, lockInfo[_holder][i].balance);
lockInfo[_holder][i].balance = 0;
if (i != lockInfo[_holder].length - 1) {
lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1];
}
lockInfo[_holder].length--;
}
function transferWithLock(address _to, uint256 _value, uint256 _releaseTime) public onlyOwner returns (bool) {
require(_to != address(0), "wrong address");
require(_value <= super.balanceOf(owner), "Not enough balance");
_balances[owner] = _balances[owner].sub(_value);
lockInfo[_to].push(
LockInfo(_releaseTime, _value)
);
emit Transfer(owner, _to, _value);
emit Lock(_to, _value, _releaseTime);
return true;
}
function transferWithLockAfter(address _to, uint256 _value, uint256 _afterTime) public onlyOwner returns (bool) {
require(_to != address(0), "wrong address");
require(_value <= super.balanceOf(owner), "Not enough balance");
_balances[owner] = _balances[owner].sub(_value);
lockInfo[_to].push(
LockInfo(now + _afterTime, _value)
);
emit Transfer(owner, _to, _value);
emit Lock(_to, _value, now + _afterTime);
return true;
}
function currentTime() public view returns (uint256) {
return now;
}
function afterTime(uint256 _value) public view returns (uint256) {
return now + _value;
}
//airdrop
mapping (address => uint256) public airDropHistory;
event AirDrop(address _receiver, uint256 _amount);
function dropToken(address[] memory receivers, uint256[] memory values) onlyOwner public {
require(receivers.length != 0);
require(receivers.length == values.length);
for (uint256 i = 0; i < receivers.length; i++) {
address receiver = receivers[i];
uint256 amount = values[i];
transfer(receiver, amount);
airDropHistory[receiver] += amount;
emit AirDrop(receiver, amount);
}
}
} | _transferOwnership | function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0), "Already owner");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
| /**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.5.8+commit.23d335f2 | MIT | bzzr://4a464ec22eebac100e03dd18189f807780d2bc6e01e39e81d8fa202c76d761ed | {
"func_code_index": [
1508,
1719
]
} | 9,397 |
||
Minings | J\contracts\Minings(MININGS).sol | 0xd108fc421d7e22819ef3307903ee5950fd716415 | Solidity | Minings | contract Minings is ERC20 {
string public constant name = "Minings";
string public constant symbol = "MININGS";
uint8 public constant decimals = 18;
uint256 public constant initialSupply = 100000000000 * (10 ** uint256(decimals));
constructor() public {
super._mint(msg.sender, initialSupply);
owner = msg.sender;
}
//ownership
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0), "Already owner");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
//pausable
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused, "Paused by owner");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused, "Not paused now");
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
//freezable
event Frozen(address target);
event Unfrozen(address target);
mapping(address => bool) internal freezes;
modifier whenNotFrozen() {
require(!freezes[msg.sender], "Sender account is locked.");
_;
}
function freeze(address _target) public onlyOwner {
freezes[_target] = true;
emit Frozen(_target);
}
function unfreeze(address _target) public onlyOwner {
freezes[_target] = false;
emit Unfrozen(_target);
}
function isFrozen(address _target) public view returns (bool) {
return freezes[_target];
}
function transfer(
address _to,
uint256 _value
)
public
whenNotFrozen
whenNotPaused
returns (bool)
{
releaseLock(msg.sender);
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
require(!freezes[_from], "From account is locked.");
releaseLock(_from);
return super.transferFrom(_from, _to, _value);
}
//mintable
event Mint(address indexed to, uint256 amount);
function mint(
address _to,
uint256 _amount
)
public
onlyOwner
returns (bool)
{
super._mint(_to, _amount);
emit Mint(_to, _amount);
return true;
}
//burnable
event Burn(address indexed burner, uint256 value);
function burn(address _who, uint256 _value) public onlyOwner {
require(_value <= super.balanceOf(_who), "Balance is too small.");
_burn(_who, _value);
emit Burn(_who, _value);
}
//lockable
struct LockInfo {
uint256 releaseTime;
uint256 balance;
}
mapping(address => LockInfo[]) internal lockInfo;
event Lock(address indexed holder, uint256 value, uint256 releaseTime);
event Unlock(address indexed holder, uint256 value);
function balanceOf(address _holder) public view returns (uint256 balance) {
uint256 lockedBalance = 0;
for(uint256 i = 0; i < lockInfo[_holder].length ; i++ ) {
lockedBalance = lockedBalance.add(lockInfo[_holder][i].balance);
}
return super.balanceOf(_holder).add(lockedBalance);
}
function releaseLock(address _holder) internal {
for(uint256 i = 0; i < lockInfo[_holder].length ; i++ ) {
if (lockInfo[_holder][i].releaseTime <= now) {
_balances[_holder] = _balances[_holder].add(lockInfo[_holder][i].balance);
emit Unlock(_holder, lockInfo[_holder][i].balance);
lockInfo[_holder][i].balance = 0;
if (i != lockInfo[_holder].length - 1) {
lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1];
i--;
}
lockInfo[_holder].length--;
}
}
}
function lockCount(address _holder) public view returns (uint256) {
return lockInfo[_holder].length;
}
function lockState(address _holder, uint256 _idx) public view returns (uint256, uint256) {
return (lockInfo[_holder][_idx].releaseTime, lockInfo[_holder][_idx].balance);
}
function lock(address _holder, uint256 _amount, uint256 _releaseTime) public onlyOwner {
require(super.balanceOf(_holder) >= _amount, "Balance is too small.");
_balances[_holder] = _balances[_holder].sub(_amount);
lockInfo[_holder].push(
LockInfo(_releaseTime, _amount)
);
emit Lock(_holder, _amount, _releaseTime);
}
function lockAfter(address _holder, uint256 _amount, uint256 _afterTime) public onlyOwner {
require(super.balanceOf(_holder) >= _amount, "Balance is too small.");
_balances[_holder] = _balances[_holder].sub(_amount);
lockInfo[_holder].push(
LockInfo(now + _afterTime, _amount)
);
emit Lock(_holder, _amount, now + _afterTime);
}
function unlock(address _holder, uint256 i) public onlyOwner {
require(i < lockInfo[_holder].length, "No lock information.");
_balances[_holder] = _balances[_holder].add(lockInfo[_holder][i].balance);
emit Unlock(_holder, lockInfo[_holder][i].balance);
lockInfo[_holder][i].balance = 0;
if (i != lockInfo[_holder].length - 1) {
lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1];
}
lockInfo[_holder].length--;
}
function transferWithLock(address _to, uint256 _value, uint256 _releaseTime) public onlyOwner returns (bool) {
require(_to != address(0), "wrong address");
require(_value <= super.balanceOf(owner), "Not enough balance");
_balances[owner] = _balances[owner].sub(_value);
lockInfo[_to].push(
LockInfo(_releaseTime, _value)
);
emit Transfer(owner, _to, _value);
emit Lock(_to, _value, _releaseTime);
return true;
}
function transferWithLockAfter(address _to, uint256 _value, uint256 _afterTime) public onlyOwner returns (bool) {
require(_to != address(0), "wrong address");
require(_value <= super.balanceOf(owner), "Not enough balance");
_balances[owner] = _balances[owner].sub(_value);
lockInfo[_to].push(
LockInfo(now + _afterTime, _value)
);
emit Transfer(owner, _to, _value);
emit Lock(_to, _value, now + _afterTime);
return true;
}
function currentTime() public view returns (uint256) {
return now;
}
function afterTime(uint256 _value) public view returns (uint256) {
return now + _value;
}
//airdrop
mapping (address => uint256) public airDropHistory;
event AirDrop(address _receiver, uint256 _amount);
function dropToken(address[] memory receivers, uint256[] memory values) onlyOwner public {
require(receivers.length != 0);
require(receivers.length == values.length);
for (uint256 i = 0; i < receivers.length; i++) {
address receiver = receivers[i];
uint256 amount = values[i];
transfer(receiver, amount);
airDropHistory[receiver] += amount;
emit AirDrop(receiver, amount);
}
}
} | pause | function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
| /**
* @dev called by the owner to pause, triggers stopped state
*/ | NatSpecMultiLine | v0.5.8+commit.23d335f2 | MIT | bzzr://4a464ec22eebac100e03dd18189f807780d2bc6e01e39e81d8fa202c76d761ed | {
"func_code_index": [
2300,
2408
]
} | 9,398 |
||
Minings | J\contracts\Minings(MININGS).sol | 0xd108fc421d7e22819ef3307903ee5950fd716415 | Solidity | Minings | contract Minings is ERC20 {
string public constant name = "Minings";
string public constant symbol = "MININGS";
uint8 public constant decimals = 18;
uint256 public constant initialSupply = 100000000000 * (10 ** uint256(decimals));
constructor() public {
super._mint(msg.sender, initialSupply);
owner = msg.sender;
}
//ownership
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0), "Already owner");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
//pausable
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused, "Paused by owner");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused, "Not paused now");
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
//freezable
event Frozen(address target);
event Unfrozen(address target);
mapping(address => bool) internal freezes;
modifier whenNotFrozen() {
require(!freezes[msg.sender], "Sender account is locked.");
_;
}
function freeze(address _target) public onlyOwner {
freezes[_target] = true;
emit Frozen(_target);
}
function unfreeze(address _target) public onlyOwner {
freezes[_target] = false;
emit Unfrozen(_target);
}
function isFrozen(address _target) public view returns (bool) {
return freezes[_target];
}
function transfer(
address _to,
uint256 _value
)
public
whenNotFrozen
whenNotPaused
returns (bool)
{
releaseLock(msg.sender);
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
require(!freezes[_from], "From account is locked.");
releaseLock(_from);
return super.transferFrom(_from, _to, _value);
}
//mintable
event Mint(address indexed to, uint256 amount);
function mint(
address _to,
uint256 _amount
)
public
onlyOwner
returns (bool)
{
super._mint(_to, _amount);
emit Mint(_to, _amount);
return true;
}
//burnable
event Burn(address indexed burner, uint256 value);
function burn(address _who, uint256 _value) public onlyOwner {
require(_value <= super.balanceOf(_who), "Balance is too small.");
_burn(_who, _value);
emit Burn(_who, _value);
}
//lockable
struct LockInfo {
uint256 releaseTime;
uint256 balance;
}
mapping(address => LockInfo[]) internal lockInfo;
event Lock(address indexed holder, uint256 value, uint256 releaseTime);
event Unlock(address indexed holder, uint256 value);
function balanceOf(address _holder) public view returns (uint256 balance) {
uint256 lockedBalance = 0;
for(uint256 i = 0; i < lockInfo[_holder].length ; i++ ) {
lockedBalance = lockedBalance.add(lockInfo[_holder][i].balance);
}
return super.balanceOf(_holder).add(lockedBalance);
}
function releaseLock(address _holder) internal {
for(uint256 i = 0; i < lockInfo[_holder].length ; i++ ) {
if (lockInfo[_holder][i].releaseTime <= now) {
_balances[_holder] = _balances[_holder].add(lockInfo[_holder][i].balance);
emit Unlock(_holder, lockInfo[_holder][i].balance);
lockInfo[_holder][i].balance = 0;
if (i != lockInfo[_holder].length - 1) {
lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1];
i--;
}
lockInfo[_holder].length--;
}
}
}
function lockCount(address _holder) public view returns (uint256) {
return lockInfo[_holder].length;
}
function lockState(address _holder, uint256 _idx) public view returns (uint256, uint256) {
return (lockInfo[_holder][_idx].releaseTime, lockInfo[_holder][_idx].balance);
}
function lock(address _holder, uint256 _amount, uint256 _releaseTime) public onlyOwner {
require(super.balanceOf(_holder) >= _amount, "Balance is too small.");
_balances[_holder] = _balances[_holder].sub(_amount);
lockInfo[_holder].push(
LockInfo(_releaseTime, _amount)
);
emit Lock(_holder, _amount, _releaseTime);
}
function lockAfter(address _holder, uint256 _amount, uint256 _afterTime) public onlyOwner {
require(super.balanceOf(_holder) >= _amount, "Balance is too small.");
_balances[_holder] = _balances[_holder].sub(_amount);
lockInfo[_holder].push(
LockInfo(now + _afterTime, _amount)
);
emit Lock(_holder, _amount, now + _afterTime);
}
function unlock(address _holder, uint256 i) public onlyOwner {
require(i < lockInfo[_holder].length, "No lock information.");
_balances[_holder] = _balances[_holder].add(lockInfo[_holder][i].balance);
emit Unlock(_holder, lockInfo[_holder][i].balance);
lockInfo[_holder][i].balance = 0;
if (i != lockInfo[_holder].length - 1) {
lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1];
}
lockInfo[_holder].length--;
}
function transferWithLock(address _to, uint256 _value, uint256 _releaseTime) public onlyOwner returns (bool) {
require(_to != address(0), "wrong address");
require(_value <= super.balanceOf(owner), "Not enough balance");
_balances[owner] = _balances[owner].sub(_value);
lockInfo[_to].push(
LockInfo(_releaseTime, _value)
);
emit Transfer(owner, _to, _value);
emit Lock(_to, _value, _releaseTime);
return true;
}
function transferWithLockAfter(address _to, uint256 _value, uint256 _afterTime) public onlyOwner returns (bool) {
require(_to != address(0), "wrong address");
require(_value <= super.balanceOf(owner), "Not enough balance");
_balances[owner] = _balances[owner].sub(_value);
lockInfo[_to].push(
LockInfo(now + _afterTime, _value)
);
emit Transfer(owner, _to, _value);
emit Lock(_to, _value, now + _afterTime);
return true;
}
function currentTime() public view returns (uint256) {
return now;
}
function afterTime(uint256 _value) public view returns (uint256) {
return now + _value;
}
//airdrop
mapping (address => uint256) public airDropHistory;
event AirDrop(address _receiver, uint256 _amount);
function dropToken(address[] memory receivers, uint256[] memory values) onlyOwner public {
require(receivers.length != 0);
require(receivers.length == values.length);
for (uint256 i = 0; i < receivers.length; i++) {
address receiver = receivers[i];
uint256 amount = values[i];
transfer(receiver, amount);
airDropHistory[receiver] += amount;
emit AirDrop(receiver, amount);
}
}
} | unpause | function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
| /**
* @dev called by the owner to unpause, returns to normal state
*/ | NatSpecMultiLine | v0.5.8+commit.23d335f2 | MIT | bzzr://4a464ec22eebac100e03dd18189f807780d2bc6e01e39e81d8fa202c76d761ed | {
"func_code_index": [
2496,
2606
]
} | 9,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.